10 #include "nodestack.h"
13 #include "clockvector.h"
14 #include "cyclegraph.h"
17 #include "threads-model.h"
18 #include "bugmessage.h"
20 #define INITIAL_THREAD_ID 0
23 * Structure for holding small ModelChecker members that should be snapshotted
25 struct model_snapshot_members {
26 model_snapshot_members() :
27 /* First thread created will have id INITIAL_THREAD_ID */
28 next_thread_id(INITIAL_THREAD_ID),
29 used_sequence_numbers(0),
32 failed_promise(false),
33 too_many_reads(false),
34 no_valid_reads(false),
35 bad_synchronization(false),
39 ~model_snapshot_members() {
40 for (unsigned int i = 0; i < bugs.size(); i++)
45 unsigned int next_thread_id;
46 modelclock_t used_sequence_numbers;
47 ModelAction *next_backtrack;
48 SnapVector<bug_message *> bugs;
52 /** @brief Incorrectly-ordered synchronization was made */
53 bool bad_synchronization;
59 /** @brief Constructor */
60 ModelExecution::ModelExecution(ModelChecker *m,
61 const struct model_params *params,
63 NodeStack *node_stack) :
68 thread_map(2), /* We'll always need at least 2 threads */
70 condvar_waiters_map(),
76 thrd_last_fence_release(),
77 node_stack(node_stack),
78 priv(new struct model_snapshot_members()),
79 mo_graph(new CycleGraph())
81 /* Initialize a model-checker thread, for special ModelActions */
82 model_thread = new Thread(get_next_id());
83 add_thread(model_thread);
84 scheduler->register_engine(this);
85 node_stack->register_engine(this);
88 /** @brief Destructor */
89 ModelExecution::~ModelExecution()
91 for (unsigned int i = 0; i < get_num_threads(); i++)
92 delete get_thread(int_to_id(i));
94 for (unsigned int i = 0; i < promises.size(); i++)
101 int ModelExecution::get_execution_number() const
103 return model->get_execution_number();
106 static action_list_t * get_safe_ptr_action(HashTable<const void *, action_list_t *, uintptr_t, 4> * hash, void * ptr)
108 action_list_t *tmp = hash->get(ptr);
110 tmp = new action_list_t();
116 static SnapVector<action_list_t> * get_safe_ptr_vect_action(HashTable<void *, SnapVector<action_list_t> *, uintptr_t, 4> * hash, void * ptr)
118 SnapVector<action_list_t> *tmp = hash->get(ptr);
120 tmp = new SnapVector<action_list_t>();
126 action_list_t * ModelExecution::get_actions_on_obj(void * obj, thread_id_t tid) const
128 SnapVector<action_list_t> *wrv = obj_thrd_map.get(obj);
131 unsigned int thread=id_to_int(tid);
132 if (thread < wrv->size())
133 return &(*wrv)[thread];
138 /** @return a thread ID for a new Thread */
139 thread_id_t ModelExecution::get_next_id()
141 return priv->next_thread_id++;
144 /** @return the number of user threads created during this execution */
145 unsigned int ModelExecution::get_num_threads() const
147 return priv->next_thread_id;
150 /** @return a sequence number for a new ModelAction */
151 modelclock_t ModelExecution::get_next_seq_num()
153 return ++priv->used_sequence_numbers;
157 * @brief Should the current action wake up a given thread?
159 * @param curr The current action
160 * @param thread The thread that we might wake up
161 * @return True, if we should wake up the sleeping thread; false otherwise
163 bool ModelExecution::should_wake_up(const ModelAction *curr, const Thread *thread) const
165 const ModelAction *asleep = thread->get_pending();
166 /* Don't allow partial RMW to wake anyone up */
169 /* Synchronizing actions may have been backtracked */
170 if (asleep->could_synchronize_with(curr))
172 /* All acquire/release fences and fence-acquire/store-release */
173 if (asleep->is_fence() && asleep->is_acquire() && curr->is_release())
175 /* Fence-release + store can awake load-acquire on the same location */
176 if (asleep->is_read() && asleep->is_acquire() && curr->same_var(asleep) && curr->is_write()) {
177 ModelAction *fence_release = get_last_fence_release(curr->get_tid());
178 if (fence_release && *(get_last_action(thread->get_id())) < *fence_release)
184 void ModelExecution::wake_up_sleeping_actions(ModelAction *curr)
186 for (unsigned int i = 0; i < get_num_threads(); i++) {
187 Thread *thr = get_thread(int_to_id(i));
188 if (scheduler->is_sleep_set(thr)) {
189 if (should_wake_up(curr, thr))
190 /* Remove this thread from sleep set */
191 scheduler->remove_sleep(thr);
196 /** @brief Alert the model-checker that an incorrectly-ordered
197 * synchronization was made */
198 void ModelExecution::set_bad_synchronization()
200 priv->bad_synchronization = true;
203 bool ModelExecution::assert_bug(const char *msg)
205 priv->bugs.push_back(new bug_message(msg));
207 if (isfeasibleprefix()) {
214 /** @return True, if any bugs have been reported for this execution */
215 bool ModelExecution::have_bug_reports() const
217 return priv->bugs.size() != 0;
220 SnapVector<bug_message *> * ModelExecution::get_bugs() const
226 * Check whether the current trace has triggered an assertion which should halt
229 * @return True, if the execution should be aborted; false otherwise
231 bool ModelExecution::has_asserted() const
233 return priv->asserted;
237 * Trigger a trace assertion which should cause this execution to be halted.
238 * This can be due to a detected bug or due to an infeasibility that should
241 void ModelExecution::set_assert()
243 priv->asserted = true;
247 * Check if we are in a deadlock. Should only be called at the end of an
248 * execution, although it should not give false positives in the middle of an
249 * execution (there should be some ENABLED thread).
251 * @return True if program is in a deadlock; false otherwise
253 bool ModelExecution::is_deadlocked() const
255 bool blocking_threads = false;
256 for (unsigned int i = 0; i < get_num_threads(); i++) {
257 thread_id_t tid = int_to_id(i);
260 Thread *t = get_thread(tid);
261 if (!t->is_model_thread() && t->get_pending())
262 blocking_threads = true;
264 return blocking_threads;
268 * Check if this is a complete execution. That is, have all thread completed
269 * execution (rather than exiting because sleep sets have forced a redundant
272 * @return True if the execution is complete.
274 bool ModelExecution::is_complete_execution() const
276 for (unsigned int i = 0; i < get_num_threads(); i++)
277 if (is_enabled(int_to_id(i)))
283 * @brief Find the last fence-related backtracking conflict for a ModelAction
285 * This function performs the search for the most recent conflicting action
286 * against which we should perform backtracking, as affected by fence
287 * operations. This includes pairs of potentially-synchronizing actions which
288 * occur due to fence-acquire or fence-release, and hence should be explored in
289 * the opposite execution order.
291 * @param act The current action
292 * @return The most recent action which conflicts with act due to fences
294 ModelAction * ModelExecution::get_last_fence_conflict(ModelAction *act) const
296 /* Only perform release/acquire fence backtracking for stores */
297 if (!act->is_write())
300 /* Find a fence-release (or, act is a release) */
301 ModelAction *last_release;
302 if (act->is_release())
305 last_release = get_last_fence_release(act->get_tid());
309 /* Skip past the release */
310 const action_list_t *list = &action_trace;
311 action_list_t::const_reverse_iterator rit;
312 for (rit = list->rbegin(); rit != list->rend(); rit++)
313 if (*rit == last_release)
315 ASSERT(rit != list->rend());
320 * load --sb-> fence-acquire */
321 ModelVector<ModelAction *> acquire_fences(get_num_threads(), NULL);
322 ModelVector<ModelAction *> prior_loads(get_num_threads(), NULL);
323 bool found_acquire_fences = false;
324 for ( ; rit != list->rend(); rit++) {
325 ModelAction *prev = *rit;
326 if (act->same_thread(prev))
329 int tid = id_to_int(prev->get_tid());
331 if (prev->is_read() && act->same_var(prev)) {
332 if (prev->is_acquire()) {
333 /* Found most recent load-acquire, don't need
334 * to search for more fences */
335 if (!found_acquire_fences)
338 prior_loads[tid] = prev;
341 if (prev->is_acquire() && prev->is_fence() && !acquire_fences[tid]) {
342 found_acquire_fences = true;
343 acquire_fences[tid] = prev;
347 ModelAction *latest_backtrack = NULL;
348 for (unsigned int i = 0; i < acquire_fences.size(); i++)
349 if (acquire_fences[i] && prior_loads[i])
350 if (!latest_backtrack || *latest_backtrack < *acquire_fences[i])
351 latest_backtrack = acquire_fences[i];
352 return latest_backtrack;
356 * @brief Find the last backtracking conflict for a ModelAction
358 * This function performs the search for the most recent conflicting action
359 * against which we should perform backtracking. This primary includes pairs of
360 * synchronizing actions which should be explored in the opposite execution
363 * @param act The current action
364 * @return The most recent action which conflicts with act
366 ModelAction * ModelExecution::get_last_conflict(ModelAction *act) const
368 switch (act->get_type()) {
370 /* Only seq-cst fences can (directly) cause backtracking */
371 if (!act->is_seqcst())
376 ModelAction *ret = NULL;
378 /* linear search: from most recent to oldest */
379 action_list_t *list = obj_map.get(act->get_location());
380 action_list_t::reverse_iterator rit;
381 for (rit = list->rbegin(); rit != list->rend(); rit++) {
382 ModelAction *prev = *rit;
385 if (prev->could_synchronize_with(act)) {
391 ModelAction *ret2 = get_last_fence_conflict(act);
401 case ATOMIC_TRYLOCK: {
402 /* linear search: from most recent to oldest */
403 action_list_t *list = obj_map.get(act->get_location());
404 action_list_t::reverse_iterator rit;
405 for (rit = list->rbegin(); rit != list->rend(); rit++) {
406 ModelAction *prev = *rit;
407 if (act->is_conflicting_lock(prev))
412 case ATOMIC_UNLOCK: {
413 /* linear search: from most recent to oldest */
414 action_list_t *list = obj_map.get(act->get_location());
415 action_list_t::reverse_iterator rit;
416 for (rit = list->rbegin(); rit != list->rend(); rit++) {
417 ModelAction *prev = *rit;
418 if (!act->same_thread(prev) && prev->is_failed_trylock())
424 /* linear search: from most recent to oldest */
425 action_list_t *list = obj_map.get(act->get_location());
426 action_list_t::reverse_iterator rit;
427 for (rit = list->rbegin(); rit != list->rend(); rit++) {
428 ModelAction *prev = *rit;
429 if (!act->same_thread(prev) && prev->is_failed_trylock())
431 if (!act->same_thread(prev) && prev->is_notify())
437 case ATOMIC_NOTIFY_ALL:
438 case ATOMIC_NOTIFY_ONE: {
439 /* linear search: from most recent to oldest */
440 action_list_t *list = obj_map.get(act->get_location());
441 action_list_t::reverse_iterator rit;
442 for (rit = list->rbegin(); rit != list->rend(); rit++) {
443 ModelAction *prev = *rit;
444 if (!act->same_thread(prev) && prev->is_wait())
455 /** This method finds backtracking points where we should try to
456 * reorder the parameter ModelAction against.
458 * @param the ModelAction to find backtracking points for.
460 void ModelExecution::set_backtracking(ModelAction *act)
462 Thread *t = get_thread(act);
463 ModelAction *prev = get_last_conflict(act);
467 Node *node = prev->get_node()->get_parent();
469 /* See Dynamic Partial Order Reduction (addendum), POPL '05 */
470 int low_tid, high_tid;
471 if (node->enabled_status(t->get_id()) == THREAD_ENABLED) {
472 low_tid = id_to_int(act->get_tid());
473 high_tid = low_tid + 1;
476 high_tid = get_num_threads();
479 for (int i = low_tid; i < high_tid; i++) {
480 thread_id_t tid = int_to_id(i);
482 /* Make sure this thread can be enabled here. */
483 if (i >= node->get_num_threads())
486 /* See Dynamic Partial Order Reduction (addendum), POPL '05 */
487 /* Don't backtrack into a point where the thread is disabled or sleeping. */
488 if (node->enabled_status(tid) != THREAD_ENABLED)
491 /* Check if this has been explored already */
492 if (node->has_been_explored(tid))
495 /* See if fairness allows */
496 if (params->fairwindow != 0 && !node->has_priority(tid)) {
498 for (int t = 0; t < node->get_num_threads(); t++) {
499 thread_id_t tother = int_to_id(t);
500 if (node->is_enabled(tother) && node->has_priority(tother)) {
509 /* See if CHESS-like yield fairness allows */
510 if (params->yieldon) {
512 for (int t = 0; t < node->get_num_threads(); t++) {
513 thread_id_t tother = int_to_id(t);
514 if (node->is_enabled(tother) && node->has_priority_over(tid, tother)) {
523 /* Cache the latest backtracking point */
524 set_latest_backtrack(prev);
526 /* If this is a new backtracking point, mark the tree */
527 if (!node->set_backtrack(tid))
529 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
530 id_to_int(prev->get_tid()),
531 id_to_int(t->get_id()));
540 * @brief Cache the a backtracking point as the "most recent", if eligible
542 * Note that this does not prepare the NodeStack for this backtracking
543 * operation, it only caches the action on a per-execution basis
545 * @param act The operation at which we should explore a different next action
546 * (i.e., backtracking point)
547 * @return True, if this action is now the most recent backtracking point;
550 bool ModelExecution::set_latest_backtrack(ModelAction *act)
552 if (!priv->next_backtrack || *act > *priv->next_backtrack) {
553 priv->next_backtrack = act;
560 * Returns last backtracking point. The model checker will explore a different
561 * path for this point in the next execution.
562 * @return The ModelAction at which the next execution should diverge.
564 ModelAction * ModelExecution::get_next_backtrack()
566 ModelAction *next = priv->next_backtrack;
567 priv->next_backtrack = NULL;
572 * Processes a read model action.
573 * @param curr is the read model action to process.
574 * @return True if processing this read updates the mo_graph.
576 bool ModelExecution::process_read(ModelAction *curr)
578 Node *node = curr->get_node();
580 bool updated = false;
581 switch (node->get_read_from_status()) {
582 case READ_FROM_PAST: {
583 const ModelAction *rf = node->get_read_from_past();
586 mo_graph->startChanges();
588 ASSERT(!is_infeasible());
589 if (!check_recency(curr, rf)) {
590 if (node->increment_read_from()) {
591 mo_graph->rollbackChanges();
594 priv->too_many_reads = true;
598 updated = r_modification_order(curr, rf);
600 mo_graph->commitChanges();
601 mo_check_promises(curr, true);
604 case READ_FROM_PROMISE: {
605 Promise *promise = curr->get_node()->get_read_from_promise();
606 if (promise->add_reader(curr))
607 priv->failed_promise = true;
608 curr->set_read_from_promise(promise);
609 mo_graph->startChanges();
610 if (!check_recency(curr, promise))
611 priv->too_many_reads = true;
612 updated = r_modification_order(curr, promise);
613 mo_graph->commitChanges();
616 case READ_FROM_FUTURE: {
617 /* Read from future value */
618 struct future_value fv = node->get_future_value();
619 Promise *promise = new Promise(this, curr, fv);
620 curr->set_read_from_promise(promise);
621 promises.push_back(promise);
622 mo_graph->startChanges();
623 updated = r_modification_order(curr, promise);
624 mo_graph->commitChanges();
630 get_thread(curr)->set_return_value(curr->get_return_value());
636 * Processes a lock, trylock, or unlock model action. @param curr is
637 * the read model action to process.
639 * The try lock operation checks whether the lock is taken. If not,
640 * it falls to the normal lock operation case. If so, it returns
643 * The lock operation has already been checked that it is enabled, so
644 * it just grabs the lock and synchronizes with the previous unlock.
646 * The unlock operation has to re-enable all of the threads that are
647 * waiting on the lock.
649 * @return True if synchronization was updated; false otherwise
651 bool ModelExecution::process_mutex(ModelAction *curr)
653 std::mutex *mutex = curr->get_mutex();
654 struct std::mutex_state *state = NULL;
657 state = mutex->get_state();
659 switch (curr->get_type()) {
660 case ATOMIC_TRYLOCK: {
661 bool success = !state->locked;
662 curr->set_try_lock(success);
664 get_thread(curr)->set_return_value(0);
667 get_thread(curr)->set_return_value(1);
669 //otherwise fall into the lock case
671 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock)
672 assert_bug("Lock access before initialization");
673 state->locked = get_thread(curr);
674 ModelAction *unlock = get_last_unlock(curr);
675 //synchronize with the previous unlock statement
676 if (unlock != NULL) {
677 synchronize(unlock, curr);
683 case ATOMIC_UNLOCK: {
684 /* wake up the other threads */
685 for (unsigned int i = 0; i < get_num_threads(); i++) {
686 Thread *t = get_thread(int_to_id(i));
687 Thread *curr_thrd = get_thread(curr);
688 if (t->waiting_on() == curr_thrd && t->get_pending()->is_lock())
692 /* unlock the lock - after checking who was waiting on it */
693 state->locked = NULL;
695 if (!curr->is_wait())
696 break; /* The rest is only for ATOMIC_WAIT */
698 /* Should we go to sleep? (simulate spurious failures) */
699 if (curr->get_node()->get_misc() == 0) {
700 get_safe_ptr_action(&condvar_waiters_map, curr->get_location())->push_back(curr);
702 scheduler->sleep(get_thread(curr));
706 case ATOMIC_NOTIFY_ALL: {
707 action_list_t *waiters = get_safe_ptr_action(&condvar_waiters_map, curr->get_location());
708 //activate all the waiting threads
709 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
710 scheduler->wake(get_thread(*rit));
715 case ATOMIC_NOTIFY_ONE: {
716 action_list_t *waiters = get_safe_ptr_action(&condvar_waiters_map, curr->get_location());
717 int wakeupthread = curr->get_node()->get_misc();
718 action_list_t::iterator it = waiters->begin();
719 advance(it, wakeupthread);
720 scheduler->wake(get_thread(*it));
732 * @brief Check if the current pending promises allow a future value to be sent
734 * If one of the following is true:
735 * (a) there are no pending promises
736 * (b) the reader and writer do not cross any promises
737 * Then, it is safe to pass a future value back now.
739 * Otherwise, we must save the pending future value until (a) or (b) is true
741 * @param writer The operation which sends the future value. Must be a write.
742 * @param reader The operation which will observe the value. Must be a read.
743 * @return True if the future value can be sent now; false if it must wait.
745 bool ModelExecution::promises_may_allow(const ModelAction *writer,
746 const ModelAction *reader) const
748 if (promises.empty())
750 for (int i = promises.size() - 1; i >= 0; i--) {
751 ModelAction *pr = promises[i]->get_reader(0);
752 //reader is after promise...doesn't cross any promise
755 //writer is after promise, reader before...bad...
763 * @brief Add a future value to a reader
765 * This function performs a few additional checks to ensure that the future
766 * value can be feasibly observed by the reader
768 * @param writer The operation whose value is sent. Must be a write.
769 * @param reader The read operation which may read the future value. Must be a read.
771 void ModelExecution::add_future_value(const ModelAction *writer, ModelAction *reader)
773 /* Do more ambitious checks now that mo is more complete */
774 if (!mo_may_allow(writer, reader))
777 Node *node = reader->get_node();
779 /* Find an ancestor thread which exists at the time of the reader */
780 Thread *write_thread = get_thread(writer);
781 while (id_to_int(write_thread->get_id()) >= node->get_num_threads())
782 write_thread = write_thread->get_parent();
784 struct future_value fv = {
785 writer->get_write_value(),
786 writer->get_seq_number() + params->maxfuturedelay,
787 write_thread->get_id(),
789 if (node->add_future_value(fv))
790 set_latest_backtrack(reader);
794 * Process a write ModelAction
795 * @param curr The ModelAction to process
796 * @return True if the mo_graph was updated or promises were resolved
798 bool ModelExecution::process_write(ModelAction *curr)
800 /* Readers to which we may send our future value */
801 ModelVector<ModelAction *> send_fv;
803 const ModelAction *earliest_promise_reader;
804 bool updated_promises = false;
806 bool updated_mod_order = w_modification_order(curr, &send_fv);
807 Promise *promise = pop_promise_to_resolve(curr);
810 earliest_promise_reader = promise->get_reader(0);
811 updated_promises = resolve_promise(curr, promise);
813 earliest_promise_reader = NULL;
815 for (unsigned int i = 0; i < send_fv.size(); i++) {
816 ModelAction *read = send_fv[i];
818 /* Don't send future values to reads after the Promise we resolve */
819 if (!earliest_promise_reader || *read < *earliest_promise_reader) {
820 /* Check if future value can be sent immediately */
821 if (promises_may_allow(curr, read)) {
822 add_future_value(curr, read);
824 futurevalues.push_back(PendingFutureValue(curr, read));
829 /* Check the pending future values */
830 for (int i = (int)futurevalues.size() - 1; i >= 0; i--) {
831 struct PendingFutureValue pfv = futurevalues[i];
832 if (promises_may_allow(pfv.writer, pfv.reader)) {
833 add_future_value(pfv.writer, pfv.reader);
834 futurevalues.erase(futurevalues.begin() + i);
838 mo_graph->commitChanges();
839 mo_check_promises(curr, false);
841 get_thread(curr)->set_return_value(VALUE_NONE);
842 return updated_mod_order || updated_promises;
846 * Process a fence ModelAction
847 * @param curr The ModelAction to process
848 * @return True if synchronization was updated
850 bool ModelExecution::process_fence(ModelAction *curr)
853 * fence-relaxed: no-op
854 * fence-release: only log the occurence (not in this function), for
855 * use in later synchronization
856 * fence-acquire (this function): search for hypothetical release
858 * fence-seq-cst: MO constraints formed in {r,w}_modification_order
860 bool updated = false;
861 if (curr->is_acquire()) {
862 action_list_t *list = &action_trace;
863 action_list_t::reverse_iterator rit;
864 /* Find X : is_read(X) && X --sb-> curr */
865 for (rit = list->rbegin(); rit != list->rend(); rit++) {
866 ModelAction *act = *rit;
869 if (act->get_tid() != curr->get_tid())
871 /* Stop at the beginning of the thread */
872 if (act->is_thread_start())
874 /* Stop once we reach a prior fence-acquire */
875 if (act->is_fence() && act->is_acquire())
879 /* read-acquire will find its own release sequences */
880 if (act->is_acquire())
883 /* Establish hypothetical release sequences */
884 rel_heads_list_t release_heads;
885 get_release_seq_heads(curr, act, &release_heads);
886 for (unsigned int i = 0; i < release_heads.size(); i++)
887 synchronize(release_heads[i], curr);
888 if (release_heads.size() != 0)
896 * @brief Process the current action for thread-related activity
898 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
899 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
900 * synchronization, etc. This function is a no-op for non-THREAD actions
901 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
903 * @param curr The current action
904 * @return True if synchronization was updated or a thread completed
906 bool ModelExecution::process_thread_action(ModelAction *curr)
908 bool updated = false;
910 switch (curr->get_type()) {
911 case THREAD_CREATE: {
912 thrd_t *thrd = (thrd_t *)curr->get_location();
913 struct thread_params *params = (struct thread_params *)curr->get_value();
914 Thread *th = new Thread(get_next_id(), thrd, params->func, params->arg, get_thread(curr));
916 th->set_creation(curr);
917 /* Promises can be satisfied by children */
918 for (unsigned int i = 0; i < promises.size(); i++) {
919 Promise *promise = promises[i];
920 if (promise->thread_is_available(curr->get_tid()))
921 promise->add_thread(th->get_id());
926 Thread *blocking = curr->get_thread_operand();
927 ModelAction *act = get_last_action(blocking->get_id());
928 synchronize(act, curr);
929 updated = true; /* trigger rel-seq checks */
932 case THREAD_FINISH: {
933 Thread *th = get_thread(curr);
934 /* Wake up any joining threads */
935 for (unsigned int i = 0; i < get_num_threads(); i++) {
936 Thread *waiting = get_thread(int_to_id(i));
937 if (waiting->waiting_on() == th &&
938 waiting->get_pending()->is_thread_join())
939 scheduler->wake(waiting);
942 /* Completed thread can't satisfy promises */
943 for (unsigned int i = 0; i < promises.size(); i++) {
944 Promise *promise = promises[i];
945 if (promise->thread_is_available(th->get_id()))
946 if (promise->eliminate_thread(th->get_id()))
947 priv->failed_promise = true;
949 updated = true; /* trigger rel-seq checks */
953 check_promises(curr->get_tid(), NULL, curr->get_cv());
964 * @brief Process the current action for release sequence fixup activity
966 * Performs model-checker release sequence fixups for the current action,
967 * forcing a single pending release sequence to break (with a given, potential
968 * "loose" write) or to complete (i.e., synchronize). If a pending release
969 * sequence forms a complete release sequence, then we must perform the fixup
970 * synchronization, mo_graph additions, etc.
972 * @param curr The current action; must be a release sequence fixup action
973 * @param work_queue The work queue to which to add work items as they are
976 void ModelExecution::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
978 const ModelAction *write = curr->get_node()->get_relseq_break();
979 struct release_seq *sequence = pending_rel_seqs.back();
980 pending_rel_seqs.pop_back();
982 ModelAction *acquire = sequence->acquire;
983 const ModelAction *rf = sequence->rf;
984 const ModelAction *release = sequence->release;
988 ASSERT(release->same_thread(rf));
992 * @todo Forcing a synchronization requires that we set
993 * modification order constraints. For instance, we can't allow
994 * a fixup sequence in which two separate read-acquire
995 * operations read from the same sequence, where the first one
996 * synchronizes and the other doesn't. Essentially, we can't
997 * allow any writes to insert themselves between 'release' and
1001 /* Must synchronize */
1002 if (!synchronize(release, acquire))
1004 /* Re-check all pending release sequences */
1005 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1006 /* Re-check act for mo_graph edges */
1007 work_queue->push_back(MOEdgeWorkEntry(acquire));
1009 /* propagate synchronization to later actions */
1010 action_list_t::reverse_iterator rit = action_trace.rbegin();
1011 for (; (*rit) != acquire; rit++) {
1012 ModelAction *propagate = *rit;
1013 if (acquire->happens_before(propagate)) {
1014 synchronize(acquire, propagate);
1015 /* Re-check 'propagate' for mo_graph edges */
1016 work_queue->push_back(MOEdgeWorkEntry(propagate));
1020 /* Break release sequence with new edges:
1021 * release --mo--> write --mo--> rf */
1022 mo_graph->addEdge(release, write);
1023 mo_graph->addEdge(write, rf);
1026 /* See if we have realized a data race */
1031 * Initialize the current action by performing one or more of the following
1032 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
1033 * in the NodeStack, manipulating backtracking sets, allocating and
1034 * initializing clock vectors, and computing the promises to fulfill.
1036 * @param curr The current action, as passed from the user context; may be
1037 * freed/invalidated after the execution of this function, with a different
1038 * action "returned" its place (pass-by-reference)
1039 * @return True if curr is a newly-explored action; false otherwise
1041 bool ModelExecution::initialize_curr_action(ModelAction **curr)
1043 ModelAction *newcurr;
1045 if ((*curr)->is_rmwc() || (*curr)->is_rmw()) {
1046 newcurr = process_rmw(*curr);
1049 if (newcurr->is_rmw())
1050 compute_promises(newcurr);
1056 (*curr)->set_seq_number(get_next_seq_num());
1058 newcurr = node_stack->explore_action(*curr, scheduler->get_enabled_array());
1060 /* First restore type and order in case of RMW operation */
1061 if ((*curr)->is_rmwr())
1062 newcurr->copy_typeandorder(*curr);
1064 ASSERT((*curr)->get_location() == newcurr->get_location());
1065 newcurr->copy_from_new(*curr);
1067 /* Discard duplicate ModelAction; use action from NodeStack */
1070 /* Always compute new clock vector */
1071 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
1074 return false; /* Action was explored previously */
1078 /* Always compute new clock vector */
1079 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
1081 /* Assign most recent release fence */
1082 newcurr->set_last_fence_release(get_last_fence_release(newcurr->get_tid()));
1085 * Perform one-time actions when pushing new ModelAction onto
1088 if (newcurr->is_write())
1089 compute_promises(newcurr);
1090 else if (newcurr->is_relseq_fixup())
1091 compute_relseq_breakwrites(newcurr);
1092 else if (newcurr->is_wait())
1093 newcurr->get_node()->set_misc_max(2);
1094 else if (newcurr->is_notify_one()) {
1095 newcurr->get_node()->set_misc_max(get_safe_ptr_action(&condvar_waiters_map, newcurr->get_location())->size());
1097 return true; /* This was a new ModelAction */
1102 * @brief Establish reads-from relation between two actions
1104 * Perform basic operations involved with establishing a concrete rf relation,
1105 * including setting the ModelAction data and checking for release sequences.
1107 * @param act The action that is reading (must be a read)
1108 * @param rf The action from which we are reading (must be a write)
1110 * @return True if this read established synchronization
1112 bool ModelExecution::read_from(ModelAction *act, const ModelAction *rf)
1115 ASSERT(rf->is_write());
1117 act->set_read_from(rf);
1118 if (act->is_acquire()) {
1119 rel_heads_list_t release_heads;
1120 get_release_seq_heads(act, act, &release_heads);
1121 int num_heads = release_heads.size();
1122 for (unsigned int i = 0; i < release_heads.size(); i++)
1123 if (!synchronize(release_heads[i], act))
1125 return num_heads > 0;
1131 * @brief Synchronizes two actions
1133 * When A synchronizes with B (or A --sw-> B), B inherits A's clock vector.
1134 * This function performs the synchronization as well as providing other hooks
1135 * for other checks along with synchronization.
1137 * @param first The left-hand side of the synchronizes-with relation
1138 * @param second The right-hand side of the synchronizes-with relation
1139 * @return True if the synchronization was successful (i.e., was consistent
1140 * with the execution order); false otherwise
1142 bool ModelExecution::synchronize(const ModelAction *first, ModelAction *second)
1144 if (*second < *first) {
1145 set_bad_synchronization();
1148 check_promises(first->get_tid(), second->get_cv(), first->get_cv());
1149 return second->synchronize_with(first);
1153 * Check promises and eliminate potentially-satisfying threads when a thread is
1154 * blocked (e.g., join, lock). A thread which is waiting on another thread can
1155 * no longer satisfy a promise generated from that thread.
1157 * @param blocker The thread on which a thread is waiting
1158 * @param waiting The waiting thread
1160 void ModelExecution::thread_blocking_check_promises(Thread *blocker, Thread *waiting)
1162 for (unsigned int i = 0; i < promises.size(); i++) {
1163 Promise *promise = promises[i];
1164 if (!promise->thread_is_available(waiting->get_id()))
1166 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
1167 ModelAction *reader = promise->get_reader(j);
1168 if (reader->get_tid() != blocker->get_id())
1170 if (promise->eliminate_thread(waiting->get_id())) {
1171 /* Promise has failed */
1172 priv->failed_promise = true;
1174 /* Only eliminate the 'waiting' thread once */
1182 * @brief Check whether a model action is enabled.
1184 * Checks whether a lock or join operation would be successful (i.e., is the
1185 * lock already locked, or is the joined thread already complete). If not, put
1186 * the action in a waiter list.
1188 * @param curr is the ModelAction to check whether it is enabled.
1189 * @return a bool that indicates whether the action is enabled.
1191 bool ModelExecution::check_action_enabled(ModelAction *curr) {
1192 if (curr->is_lock()) {
1193 std::mutex *lock = curr->get_mutex();
1194 struct std::mutex_state *state = lock->get_state();
1197 } else if (curr->is_thread_join()) {
1198 Thread *blocking = curr->get_thread_operand();
1199 if (!blocking->is_complete()) {
1200 thread_blocking_check_promises(blocking, get_thread(curr));
1209 * This is the heart of the model checker routine. It performs model-checking
1210 * actions corresponding to a given "current action." Among other processes, it
1211 * calculates reads-from relationships, updates synchronization clock vectors,
1212 * forms a memory_order constraints graph, and handles replay/backtrack
1213 * execution when running permutations of previously-observed executions.
1215 * @param curr The current action to process
1216 * @return The ModelAction that is actually executed; may be different than
1219 ModelAction * ModelExecution::check_current_action(ModelAction *curr)
1222 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
1223 bool newly_explored = initialize_curr_action(&curr);
1227 wake_up_sleeping_actions(curr);
1229 /* Compute fairness information for CHESS yield algorithm */
1230 if (params->yieldon) {
1231 curr->get_node()->update_yield(scheduler);
1234 /* Add the action to lists before any other model-checking tasks */
1235 if (!second_part_of_rmw)
1236 add_action_to_lists(curr);
1238 /* Build may_read_from set for newly-created actions */
1239 if (newly_explored && curr->is_read())
1240 build_may_read_from(curr);
1242 /* Initialize work_queue with the "current action" work */
1243 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
1244 while (!work_queue.empty() && !has_asserted()) {
1245 WorkQueueEntry work = work_queue.front();
1246 work_queue.pop_front();
1248 switch (work.type) {
1249 case WORK_CHECK_CURR_ACTION: {
1250 ModelAction *act = work.action;
1251 bool update = false; /* update this location's release seq's */
1252 bool update_all = false; /* update all release seq's */
1254 if (process_thread_action(curr))
1257 if (act->is_read() && !second_part_of_rmw && process_read(act))
1260 if (act->is_write() && process_write(act))
1263 if (act->is_fence() && process_fence(act))
1266 if (act->is_mutex_op() && process_mutex(act))
1269 if (act->is_relseq_fixup())
1270 process_relseq_fixup(curr, &work_queue);
1273 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
1275 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
1278 case WORK_CHECK_RELEASE_SEQ:
1279 resolve_release_sequences(work.location, &work_queue);
1281 case WORK_CHECK_MO_EDGES: {
1282 /** @todo Complete verification of work_queue */
1283 ModelAction *act = work.action;
1284 bool updated = false;
1286 if (act->is_read()) {
1287 const ModelAction *rf = act->get_reads_from();
1288 const Promise *promise = act->get_reads_from_promise();
1290 if (r_modification_order(act, rf))
1292 } else if (promise) {
1293 if (r_modification_order(act, promise))
1297 if (act->is_write()) {
1298 if (w_modification_order(act, NULL))
1301 mo_graph->commitChanges();
1304 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
1313 check_curr_backtracking(curr);
1314 set_backtracking(curr);
1318 void ModelExecution::check_curr_backtracking(ModelAction *curr)
1320 Node *currnode = curr->get_node();
1321 Node *parnode = currnode->get_parent();
1323 if ((parnode && !parnode->backtrack_empty()) ||
1324 !currnode->misc_empty() ||
1325 !currnode->read_from_empty() ||
1326 !currnode->promise_empty() ||
1327 !currnode->relseq_break_empty()) {
1328 set_latest_backtrack(curr);
1332 bool ModelExecution::promises_expired() const
1334 for (unsigned int i = 0; i < promises.size(); i++) {
1335 Promise *promise = promises[i];
1336 if (promise->get_expiration() < priv->used_sequence_numbers)
1343 * This is the strongest feasibility check available.
1344 * @return whether the current trace (partial or complete) must be a prefix of
1347 bool ModelExecution::isfeasibleprefix() const
1349 return pending_rel_seqs.size() == 0 && is_feasible_prefix_ignore_relseq();
1353 * Print disagnostic information about an infeasible execution
1354 * @param prefix A string to prefix the output with; if NULL, then a default
1355 * message prefix will be provided
1357 void ModelExecution::print_infeasibility(const char *prefix) const
1361 if (mo_graph->checkForCycles())
1362 ptr += sprintf(ptr, "[mo cycle]");
1363 if (priv->failed_promise)
1364 ptr += sprintf(ptr, "[failed promise]");
1365 if (priv->too_many_reads)
1366 ptr += sprintf(ptr, "[too many reads]");
1367 if (priv->no_valid_reads)
1368 ptr += sprintf(ptr, "[no valid reads-from]");
1369 if (priv->bad_synchronization)
1370 ptr += sprintf(ptr, "[bad sw ordering]");
1371 if (promises_expired())
1372 ptr += sprintf(ptr, "[promise expired]");
1373 if (promises.size() != 0)
1374 ptr += sprintf(ptr, "[unresolved promise]");
1376 model_print("%s: %s\n", prefix ? prefix : "Infeasible", buf);
1380 * Returns whether the current completed trace is feasible, except for pending
1381 * release sequences.
1383 bool ModelExecution::is_feasible_prefix_ignore_relseq() const
1385 return !is_infeasible() && promises.size() == 0;
1389 * Check if the current partial trace is infeasible. Does not check any
1390 * end-of-execution flags, which might rule out the execution. Thus, this is
1391 * useful only for ruling an execution as infeasible.
1392 * @return whether the current partial trace is infeasible.
1394 bool ModelExecution::is_infeasible() const
1396 return mo_graph->checkForCycles() ||
1397 priv->no_valid_reads ||
1398 priv->failed_promise ||
1399 priv->too_many_reads ||
1400 priv->bad_synchronization ||
1404 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
1405 ModelAction * ModelExecution::process_rmw(ModelAction *act) {
1406 ModelAction *lastread = get_last_action(act->get_tid());
1407 lastread->process_rmw(act);
1408 if (act->is_rmw()) {
1409 if (lastread->get_reads_from())
1410 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
1412 mo_graph->addRMWEdge(lastread->get_reads_from_promise(), lastread);
1413 mo_graph->commitChanges();
1419 * A helper function for ModelExecution::check_recency, to check if the current
1420 * thread is able to read from a different write/promise for 'params.maxreads'
1421 * number of steps and if that write/promise should become visible (i.e., is
1422 * ordered later in the modification order). This helps model memory liveness.
1424 * @param curr The current action. Must be a read.
1425 * @param rf The write/promise from which we plan to read
1426 * @param other_rf The write/promise from which we may read
1427 * @return True if we were able to read from other_rf for params.maxreads steps
1429 template <typename T, typename U>
1430 bool ModelExecution::should_read_instead(const ModelAction *curr, const T *rf, const U *other_rf) const
1432 /* Need a different write/promise */
1433 if (other_rf->equals(rf))
1436 /* Only look for "newer" writes/promises */
1437 if (!mo_graph->checkReachable(rf, other_rf))
1440 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1441 action_list_t *list = &(*thrd_lists)[id_to_int(curr->get_tid())];
1442 action_list_t::reverse_iterator rit = list->rbegin();
1443 ASSERT((*rit) == curr);
1444 /* Skip past curr */
1447 /* Does this write/promise work for everyone? */
1448 for (int i = 0; i < params->maxreads; i++, rit++) {
1449 ModelAction *act = *rit;
1450 if (!act->may_read_from(other_rf))
1457 * Checks whether a thread has read from the same write or Promise for too many
1458 * times without seeing the effects of a later write/Promise.
1461 * 1) there must a different write/promise that we could read from,
1462 * 2) we must have read from the same write/promise in excess of maxreads times,
1463 * 3) that other write/promise must have been in the reads_from set for maxreads times, and
1464 * 4) that other write/promise must be mod-ordered after the write/promise we are reading.
1466 * If so, we decide that the execution is no longer feasible.
1468 * @param curr The current action. Must be a read.
1469 * @param rf The ModelAction/Promise from which we might read.
1470 * @return True if the read should succeed; false otherwise
1472 template <typename T>
1473 bool ModelExecution::check_recency(ModelAction *curr, const T *rf) const
1475 if (!params->maxreads)
1478 //NOTE: Next check is just optimization, not really necessary....
1479 if (curr->get_node()->get_read_from_past_size() +
1480 curr->get_node()->get_read_from_promise_size() <= 1)
1483 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1484 int tid = id_to_int(curr->get_tid());
1485 ASSERT(tid < (int)thrd_lists->size());
1486 action_list_t *list = &(*thrd_lists)[tid];
1487 action_list_t::reverse_iterator rit = list->rbegin();
1488 ASSERT((*rit) == curr);
1489 /* Skip past curr */
1492 action_list_t::reverse_iterator ritcopy = rit;
1493 /* See if we have enough reads from the same value */
1494 for (int count = 0; count < params->maxreads; ritcopy++, count++) {
1495 if (ritcopy == list->rend())
1497 ModelAction *act = *ritcopy;
1498 if (!act->is_read())
1500 if (act->get_reads_from_promise() && !act->get_reads_from_promise()->equals(rf))
1502 if (act->get_reads_from() && !act->get_reads_from()->equals(rf))
1504 if (act->get_node()->get_read_from_past_size() +
1505 act->get_node()->get_read_from_promise_size() <= 1)
1508 for (int i = 0; i < curr->get_node()->get_read_from_past_size(); i++) {
1509 const ModelAction *write = curr->get_node()->get_read_from_past(i);
1510 if (should_read_instead(curr, rf, write))
1511 return false; /* liveness failure */
1513 for (int i = 0; i < curr->get_node()->get_read_from_promise_size(); i++) {
1514 const Promise *promise = curr->get_node()->get_read_from_promise(i);
1515 if (should_read_instead(curr, rf, promise))
1516 return false; /* liveness failure */
1522 * @brief Updates the mo_graph with the constraints imposed from the current
1525 * Basic idea is the following: Go through each other thread and find
1526 * the last action that happened before our read. Two cases:
1528 * -# The action is a write: that write must either occur before
1529 * the write we read from or be the write we read from.
1530 * -# The action is a read: the write that that action read from
1531 * must occur before the write we read from or be the same write.
1533 * @param curr The current action. Must be a read.
1534 * @param rf The ModelAction or Promise that curr reads from. Must be a write.
1535 * @return True if modification order edges were added; false otherwise
1537 template <typename rf_type>
1538 bool ModelExecution::r_modification_order(ModelAction *curr, const rf_type *rf)
1540 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1543 ASSERT(curr->is_read());
1545 /* Last SC fence in the current thread */
1546 ModelAction *last_sc_fence_local = get_last_seq_cst_fence(curr->get_tid(), NULL);
1547 ModelAction *last_sc_write = NULL;
1548 if (curr->is_seqcst())
1549 last_sc_write = get_last_seq_cst_write(curr);
1551 /* Iterate over all threads */
1552 for (i = 0; i < thrd_lists->size(); i++) {
1553 /* Last SC fence in thread i */
1554 ModelAction *last_sc_fence_thread_local = NULL;
1555 if (int_to_id((int)i) != curr->get_tid())
1556 last_sc_fence_thread_local = get_last_seq_cst_fence(int_to_id(i), NULL);
1558 /* Last SC fence in thread i, before last SC fence in current thread */
1559 ModelAction *last_sc_fence_thread_before = NULL;
1560 if (last_sc_fence_local)
1561 last_sc_fence_thread_before = get_last_seq_cst_fence(int_to_id(i), last_sc_fence_local);
1563 /* Iterate over actions in thread, starting from most recent */
1564 action_list_t *list = &(*thrd_lists)[i];
1565 action_list_t::reverse_iterator rit;
1566 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1567 ModelAction *act = *rit;
1572 /* Don't want to add reflexive edges on 'rf' */
1573 if (act->equals(rf)) {
1574 if (act->happens_before(curr))
1580 if (act->is_write()) {
1581 /* C++, Section 29.3 statement 5 */
1582 if (curr->is_seqcst() && last_sc_fence_thread_local &&
1583 *act < *last_sc_fence_thread_local) {
1584 added = mo_graph->addEdge(act, rf) || added;
1587 /* C++, Section 29.3 statement 4 */
1588 else if (act->is_seqcst() && last_sc_fence_local &&
1589 *act < *last_sc_fence_local) {
1590 added = mo_graph->addEdge(act, rf) || added;
1593 /* C++, Section 29.3 statement 6 */
1594 else if (last_sc_fence_thread_before &&
1595 *act < *last_sc_fence_thread_before) {
1596 added = mo_graph->addEdge(act, rf) || added;
1601 /* C++, Section 29.3 statement 3 (second subpoint) */
1602 if (curr->is_seqcst() && last_sc_write && act == last_sc_write) {
1603 added = mo_graph->addEdge(act, rf) || added;
1608 * Include at most one act per-thread that "happens
1611 if (act->happens_before(curr)) {
1612 if (act->is_write()) {
1613 added = mo_graph->addEdge(act, rf) || added;
1615 const ModelAction *prevrf = act->get_reads_from();
1616 const Promise *prevrf_promise = act->get_reads_from_promise();
1618 if (!prevrf->equals(rf))
1619 added = mo_graph->addEdge(prevrf, rf) || added;
1620 } else if (!prevrf_promise->equals(rf)) {
1621 added = mo_graph->addEdge(prevrf_promise, rf) || added;
1630 * All compatible, thread-exclusive promises must be ordered after any
1631 * concrete loads from the same thread
1633 for (unsigned int i = 0; i < promises.size(); i++)
1634 if (promises[i]->is_compatible_exclusive(curr))
1635 added = mo_graph->addEdge(rf, promises[i]) || added;
1641 * Updates the mo_graph with the constraints imposed from the current write.
1643 * Basic idea is the following: Go through each other thread and find
1644 * the lastest action that happened before our write. Two cases:
1646 * (1) The action is a write => that write must occur before
1649 * (2) The action is a read => the write that that action read from
1650 * must occur before the current write.
1652 * This method also handles two other issues:
1654 * (I) Sequential Consistency: Making sure that if the current write is
1655 * seq_cst, that it occurs after the previous seq_cst write.
1657 * (II) Sending the write back to non-synchronizing reads.
1659 * @param curr The current action. Must be a write.
1660 * @param send_fv A vector for stashing reads to which we may pass our future
1661 * value. If NULL, then don't record any future values.
1662 * @return True if modification order edges were added; false otherwise
1664 bool ModelExecution::w_modification_order(ModelAction *curr, ModelVector<ModelAction *> *send_fv)
1666 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
1669 ASSERT(curr->is_write());
1671 if (curr->is_seqcst()) {
1672 /* We have to at least see the last sequentially consistent write,
1673 so we are initialized. */
1674 ModelAction *last_seq_cst = get_last_seq_cst_write(curr);
1675 if (last_seq_cst != NULL) {
1676 added = mo_graph->addEdge(last_seq_cst, curr) || added;
1680 /* Last SC fence in the current thread */
1681 ModelAction *last_sc_fence_local = get_last_seq_cst_fence(curr->get_tid(), NULL);
1683 /* Iterate over all threads */
1684 for (i = 0; i < thrd_lists->size(); i++) {
1685 /* Last SC fence in thread i, before last SC fence in current thread */
1686 ModelAction *last_sc_fence_thread_before = NULL;
1687 if (last_sc_fence_local && int_to_id((int)i) != curr->get_tid())
1688 last_sc_fence_thread_before = get_last_seq_cst_fence(int_to_id(i), last_sc_fence_local);
1690 /* Iterate over actions in thread, starting from most recent */
1691 action_list_t *list = &(*thrd_lists)[i];
1692 action_list_t::reverse_iterator rit;
1693 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1694 ModelAction *act = *rit;
1697 * 1) If RMW and it actually read from something, then we
1698 * already have all relevant edges, so just skip to next
1701 * 2) If RMW and it didn't read from anything, we should
1702 * whatever edge we can get to speed up convergence.
1704 * 3) If normal write, we need to look at earlier actions, so
1705 * continue processing list.
1707 if (curr->is_rmw()) {
1708 if (curr->get_reads_from() != NULL)
1716 /* C++, Section 29.3 statement 7 */
1717 if (last_sc_fence_thread_before && act->is_write() &&
1718 *act < *last_sc_fence_thread_before) {
1719 added = mo_graph->addEdge(act, curr) || added;
1724 * Include at most one act per-thread that "happens
1727 if (act->happens_before(curr)) {
1729 * Note: if act is RMW, just add edge:
1731 * The following edge should be handled elsewhere:
1732 * readfrom(act) --mo--> act
1734 if (act->is_write())
1735 added = mo_graph->addEdge(act, curr) || added;
1736 else if (act->is_read()) {
1737 //if previous read accessed a null, just keep going
1738 if (act->get_reads_from() == NULL)
1740 added = mo_graph->addEdge(act->get_reads_from(), curr) || added;
1743 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1744 !act->same_thread(curr)) {
1745 /* We have an action that:
1746 (1) did not happen before us
1747 (2) is a read and we are a write
1748 (3) cannot synchronize with us
1749 (4) is in a different thread
1751 that read could potentially read from our write. Note that
1752 these checks are overly conservative at this point, we'll
1753 do more checks before actually removing the
1757 if (send_fv && thin_air_constraint_may_allow(curr, act)) {
1758 if (!is_infeasible())
1759 send_fv->push_back(act);
1760 else if (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() && curr->get_reads_from() == act->get_reads_from())
1761 add_future_value(curr, act);
1768 * All compatible, thread-exclusive promises must be ordered after any
1769 * concrete stores to the same thread, or else they can be merged with
1772 for (unsigned int i = 0; i < promises.size(); i++)
1773 if (promises[i]->is_compatible_exclusive(curr))
1774 added = mo_graph->addEdge(curr, promises[i]) || added;
1779 /** Arbitrary reads from the future are not allowed. Section 29.3
1780 * part 9 places some constraints. This method checks one result of constraint
1781 * constraint. Others require compiler support. */
1782 bool ModelExecution::thin_air_constraint_may_allow(const ModelAction *writer, const ModelAction *reader) const
1784 if (!writer->is_rmw())
1787 if (!reader->is_rmw())
1790 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1791 if (search == reader)
1793 if (search->get_tid() == reader->get_tid() &&
1794 search->happens_before(reader))
1802 * Arbitrary reads from the future are not allowed. Section 29.3 part 9 places
1803 * some constraints. This method checks one the following constraint (others
1804 * require compiler support):
1806 * If X --hb-> Y --mo-> Z, then X should not read from Z.
1808 bool ModelExecution::mo_may_allow(const ModelAction *writer, const ModelAction *reader)
1810 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(reader->get_location());
1812 /* Iterate over all threads */
1813 for (i = 0; i < thrd_lists->size(); i++) {
1814 const ModelAction *write_after_read = NULL;
1816 /* Iterate over actions in thread, starting from most recent */
1817 action_list_t *list = &(*thrd_lists)[i];
1818 action_list_t::reverse_iterator rit;
1819 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1820 ModelAction *act = *rit;
1822 /* Don't disallow due to act == reader */
1823 if (!reader->happens_before(act) || reader == act)
1825 else if (act->is_write())
1826 write_after_read = act;
1827 else if (act->is_read() && act->get_reads_from() != NULL)
1828 write_after_read = act->get_reads_from();
1831 if (write_after_read && write_after_read != writer && mo_graph->checkReachable(write_after_read, writer))
1838 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1839 * The ModelAction under consideration is expected to be taking part in
1840 * release/acquire synchronization as an object of the "reads from" relation.
1841 * Note that this can only provide release sequence support for RMW chains
1842 * which do not read from the future, as those actions cannot be traced until
1843 * their "promise" is fulfilled. Similarly, we may not even establish the
1844 * presence of a release sequence with certainty, as some modification order
1845 * constraints may be decided further in the future. Thus, this function
1846 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1847 * and a boolean representing certainty.
1849 * @param rf The action that might be part of a release sequence. Must be a
1851 * @param release_heads A pass-by-reference style return parameter. After
1852 * execution of this function, release_heads will contain the heads of all the
1853 * relevant release sequences, if any exists with certainty
1854 * @param pending A pass-by-reference style return parameter which is only used
1855 * when returning false (i.e., uncertain). Returns most information regarding
1856 * an uncertain release sequence, including any write operations that might
1857 * break the sequence.
1858 * @return true, if the ModelExecution is certain that release_heads is complete;
1861 bool ModelExecution::release_seq_heads(const ModelAction *rf,
1862 rel_heads_list_t *release_heads,
1863 struct release_seq *pending) const
1865 /* Only check for release sequences if there are no cycles */
1866 if (mo_graph->checkForCycles())
1869 for ( ; rf != NULL; rf = rf->get_reads_from()) {
1870 ASSERT(rf->is_write());
1872 if (rf->is_release())
1873 release_heads->push_back(rf);
1874 else if (rf->get_last_fence_release())
1875 release_heads->push_back(rf->get_last_fence_release());
1877 break; /* End of RMW chain */
1879 /** @todo Need to be smarter here... In the linux lock
1880 * example, this will run to the beginning of the program for
1882 /** @todo The way to be smarter here is to keep going until 1
1883 * thread has a release preceded by an acquire and you've seen
1886 /* acq_rel RMW is a sufficient stopping condition */
1887 if (rf->is_acquire() && rf->is_release())
1888 return true; /* complete */
1891 /* read from future: need to settle this later */
1893 return false; /* incomplete */
1896 if (rf->is_release())
1897 return true; /* complete */
1899 /* else relaxed write
1900 * - check for fence-release in the same thread (29.8, stmt. 3)
1901 * - check modification order for contiguous subsequence
1902 * -> rf must be same thread as release */
1904 const ModelAction *fence_release = rf->get_last_fence_release();
1905 /* Synchronize with a fence-release unconditionally; we don't need to
1906 * find any more "contiguous subsequence..." for it */
1908 release_heads->push_back(fence_release);
1910 int tid = id_to_int(rf->get_tid());
1911 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(rf->get_location());
1912 action_list_t *list = &(*thrd_lists)[tid];
1913 action_list_t::const_reverse_iterator rit;
1915 /* Find rf in the thread list */
1916 rit = std::find(list->rbegin(), list->rend(), rf);
1917 ASSERT(rit != list->rend());
1919 /* Find the last {write,fence}-release */
1920 for (; rit != list->rend(); rit++) {
1921 if (fence_release && *(*rit) < *fence_release)
1923 if ((*rit)->is_release())
1926 if (rit == list->rend()) {
1927 /* No write-release in this thread */
1928 return true; /* complete */
1929 } else if (fence_release && *(*rit) < *fence_release) {
1930 /* The fence-release is more recent (and so, "stronger") than
1931 * the most recent write-release */
1932 return true; /* complete */
1933 } /* else, need to establish contiguous release sequence */
1934 ModelAction *release = *rit;
1936 ASSERT(rf->same_thread(release));
1938 pending->writes.clear();
1940 bool certain = true;
1941 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1942 if (id_to_int(rf->get_tid()) == (int)i)
1944 list = &(*thrd_lists)[i];
1946 /* Can we ensure no future writes from this thread may break
1947 * the release seq? */
1948 bool future_ordered = false;
1950 ModelAction *last = get_last_action(int_to_id(i));
1951 Thread *th = get_thread(int_to_id(i));
1952 if ((last && rf->happens_before(last)) ||
1955 future_ordered = true;
1957 ASSERT(!th->is_model_thread() || future_ordered);
1959 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1960 const ModelAction *act = *rit;
1961 /* Reach synchronization -> this thread is complete */
1962 if (act->happens_before(release))
1964 if (rf->happens_before(act)) {
1965 future_ordered = true;
1969 /* Only non-RMW writes can break release sequences */
1970 if (!act->is_write() || act->is_rmw())
1973 /* Check modification order */
1974 if (mo_graph->checkReachable(rf, act)) {
1975 /* rf --mo--> act */
1976 future_ordered = true;
1979 if (mo_graph->checkReachable(act, release))
1980 /* act --mo--> release */
1982 if (mo_graph->checkReachable(release, act) &&
1983 mo_graph->checkReachable(act, rf)) {
1984 /* release --mo-> act --mo--> rf */
1985 return true; /* complete */
1987 /* act may break release sequence */
1988 pending->writes.push_back(act);
1991 if (!future_ordered)
1992 certain = false; /* This thread is uncertain */
1996 release_heads->push_back(release);
1997 pending->writes.clear();
1999 pending->release = release;
2006 * An interface for getting the release sequence head(s) with which a
2007 * given ModelAction must synchronize. This function only returns a non-empty
2008 * result when it can locate a release sequence head with certainty. Otherwise,
2009 * it may mark the internal state of the ModelExecution so that it will handle
2010 * the release sequence at a later time, causing @a acquire to update its
2011 * synchronization at some later point in execution.
2013 * @param acquire The 'acquire' action that may synchronize with a release
2015 * @param read The read action that may read from a release sequence; this may
2016 * be the same as acquire, or else an earlier action in the same thread (i.e.,
2017 * when 'acquire' is a fence-acquire)
2018 * @param release_heads A pass-by-reference return parameter. Will be filled
2019 * with the head(s) of the release sequence(s), if they exists with certainty.
2020 * @see ModelExecution::release_seq_heads
2022 void ModelExecution::get_release_seq_heads(ModelAction *acquire,
2023 ModelAction *read, rel_heads_list_t *release_heads)
2025 const ModelAction *rf = read->get_reads_from();
2026 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
2027 sequence->acquire = acquire;
2028 sequence->read = read;
2030 if (!release_seq_heads(rf, release_heads, sequence)) {
2031 /* add act to 'lazy checking' list */
2032 pending_rel_seqs.push_back(sequence);
2034 snapshot_free(sequence);
2039 * Attempt to resolve all stashed operations that might synchronize with a
2040 * release sequence for a given location. This implements the "lazy" portion of
2041 * determining whether or not a release sequence was contiguous, since not all
2042 * modification order information is present at the time an action occurs.
2044 * @param location The location/object that should be checked for release
2045 * sequence resolutions. A NULL value means to check all locations.
2046 * @param work_queue The work queue to which to add work items as they are
2048 * @return True if any updates occurred (new synchronization, new mo_graph
2051 bool ModelExecution::resolve_release_sequences(void *location, work_queue_t *work_queue)
2053 bool updated = false;
2054 SnapVector<struct release_seq *>::iterator it = pending_rel_seqs.begin();
2055 while (it != pending_rel_seqs.end()) {
2056 struct release_seq *pending = *it;
2057 ModelAction *acquire = pending->acquire;
2058 const ModelAction *read = pending->read;
2060 /* Only resolve sequences on the given location, if provided */
2061 if (location && read->get_location() != location) {
2066 const ModelAction *rf = read->get_reads_from();
2067 rel_heads_list_t release_heads;
2069 complete = release_seq_heads(rf, &release_heads, pending);
2070 for (unsigned int i = 0; i < release_heads.size(); i++)
2071 if (!acquire->has_synchronized_with(release_heads[i]))
2072 if (synchronize(release_heads[i], acquire))
2076 /* Re-check all pending release sequences */
2077 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
2078 /* Re-check read-acquire for mo_graph edges */
2079 if (acquire->is_read())
2080 work_queue->push_back(MOEdgeWorkEntry(acquire));
2082 /* propagate synchronization to later actions */
2083 action_list_t::reverse_iterator rit = action_trace.rbegin();
2084 for (; (*rit) != acquire; rit++) {
2085 ModelAction *propagate = *rit;
2086 if (acquire->happens_before(propagate)) {
2087 synchronize(acquire, propagate);
2088 /* Re-check 'propagate' for mo_graph edges */
2089 work_queue->push_back(MOEdgeWorkEntry(propagate));
2094 it = pending_rel_seqs.erase(it);
2095 snapshot_free(pending);
2101 // If we resolved promises or data races, see if we have realized a data race.
2108 * Performs various bookkeeping operations for the current ModelAction. For
2109 * instance, adds action to the per-object, per-thread action vector and to the
2110 * action trace list of all thread actions.
2112 * @param act is the ModelAction to add.
2114 void ModelExecution::add_action_to_lists(ModelAction *act)
2116 int tid = id_to_int(act->get_tid());
2117 ModelAction *uninit = NULL;
2119 action_list_t *list = get_safe_ptr_action(&obj_map, act->get_location());
2120 if (list->empty() && act->is_atomic_var()) {
2121 uninit = get_uninitialized_action(act);
2122 uninit_id = id_to_int(uninit->get_tid());
2123 list->push_front(uninit);
2125 list->push_back(act);
2127 action_trace.push_back(act);
2129 action_trace.push_front(uninit);
2131 SnapVector<action_list_t> *vec = get_safe_ptr_vect_action(&obj_thrd_map, act->get_location());
2132 if (tid >= (int)vec->size())
2133 vec->resize(priv->next_thread_id);
2134 (*vec)[tid].push_back(act);
2136 (*vec)[uninit_id].push_front(uninit);
2138 if ((int)thrd_last_action.size() <= tid)
2139 thrd_last_action.resize(get_num_threads());
2140 thrd_last_action[tid] = act;
2142 thrd_last_action[uninit_id] = uninit;
2144 if (act->is_fence() && act->is_release()) {
2145 if ((int)thrd_last_fence_release.size() <= tid)
2146 thrd_last_fence_release.resize(get_num_threads());
2147 thrd_last_fence_release[tid] = act;
2150 if (act->is_wait()) {
2151 void *mutex_loc = (void *) act->get_value();
2152 get_safe_ptr_action(&obj_map, mutex_loc)->push_back(act);
2154 SnapVector<action_list_t> *vec = get_safe_ptr_vect_action(&obj_thrd_map, mutex_loc);
2155 if (tid >= (int)vec->size())
2156 vec->resize(priv->next_thread_id);
2157 (*vec)[tid].push_back(act);
2162 * @brief Get the last action performed by a particular Thread
2163 * @param tid The thread ID of the Thread in question
2164 * @return The last action in the thread
2166 ModelAction * ModelExecution::get_last_action(thread_id_t tid) const
2168 int threadid = id_to_int(tid);
2169 if (threadid < (int)thrd_last_action.size())
2170 return thrd_last_action[id_to_int(tid)];
2176 * @brief Get the last fence release performed by a particular Thread
2177 * @param tid The thread ID of the Thread in question
2178 * @return The last fence release in the thread, if one exists; NULL otherwise
2180 ModelAction * ModelExecution::get_last_fence_release(thread_id_t tid) const
2182 int threadid = id_to_int(tid);
2183 if (threadid < (int)thrd_last_fence_release.size())
2184 return thrd_last_fence_release[id_to_int(tid)];
2190 * Gets the last memory_order_seq_cst write (in the total global sequence)
2191 * performed on a particular object (i.e., memory location), not including the
2193 * @param curr The current ModelAction; also denotes the object location to
2195 * @return The last seq_cst write
2197 ModelAction * ModelExecution::get_last_seq_cst_write(ModelAction *curr) const
2199 void *location = curr->get_location();
2200 action_list_t *list = obj_map.get(location);
2201 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
2202 action_list_t::reverse_iterator rit;
2203 for (rit = list->rbegin(); (*rit) != curr; rit++)
2205 rit++; /* Skip past curr */
2206 for ( ; rit != list->rend(); rit++)
2207 if ((*rit)->is_write() && (*rit)->is_seqcst())
2213 * Gets the last memory_order_seq_cst fence (in the total global sequence)
2214 * performed in a particular thread, prior to a particular fence.
2215 * @param tid The ID of the thread to check
2216 * @param before_fence The fence from which to begin the search; if NULL, then
2217 * search for the most recent fence in the thread.
2218 * @return The last prior seq_cst fence in the thread, if exists; otherwise, NULL
2220 ModelAction * ModelExecution::get_last_seq_cst_fence(thread_id_t tid, const ModelAction *before_fence) const
2222 /* All fences should have location FENCE_LOCATION */
2223 action_list_t *list = obj_map.get(FENCE_LOCATION);
2228 action_list_t::reverse_iterator rit = list->rbegin();
2231 for (; rit != list->rend(); rit++)
2232 if (*rit == before_fence)
2235 ASSERT(*rit == before_fence);
2239 for (; rit != list->rend(); rit++)
2240 if ((*rit)->is_fence() && (tid == (*rit)->get_tid()) && (*rit)->is_seqcst())
2246 * Gets the last unlock operation performed on a particular mutex (i.e., memory
2247 * location). This function identifies the mutex according to the current
2248 * action, which is presumed to perform on the same mutex.
2249 * @param curr The current ModelAction; also denotes the object location to
2251 * @return The last unlock operation
2253 ModelAction * ModelExecution::get_last_unlock(ModelAction *curr) const
2255 void *location = curr->get_location();
2256 action_list_t *list = obj_map.get(location);
2257 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
2258 action_list_t::reverse_iterator rit;
2259 for (rit = list->rbegin(); rit != list->rend(); rit++)
2260 if ((*rit)->is_unlock() || (*rit)->is_wait())
2265 ModelAction * ModelExecution::get_parent_action(thread_id_t tid) const
2267 ModelAction *parent = get_last_action(tid);
2269 parent = get_thread(tid)->get_creation();
2274 * Returns the clock vector for a given thread.
2275 * @param tid The thread whose clock vector we want
2276 * @return Desired clock vector
2278 ClockVector * ModelExecution::get_cv(thread_id_t tid) const
2280 return get_parent_action(tid)->get_cv();
2284 * @brief Find the promise (if any) to resolve for the current action and
2285 * remove it from the pending promise vector
2286 * @param curr The current ModelAction. Should be a write.
2287 * @return The Promise to resolve, if any; otherwise NULL
2289 Promise * ModelExecution::pop_promise_to_resolve(const ModelAction *curr)
2291 for (unsigned int i = 0; i < promises.size(); i++)
2292 if (curr->get_node()->get_promise(i)) {
2293 Promise *ret = promises[i];
2294 promises.erase(promises.begin() + i);
2301 * Resolve a Promise with a current write.
2302 * @param write The ModelAction that is fulfilling Promises
2303 * @param promise The Promise to resolve
2304 * @return True if the Promise was successfully resolved; false otherwise
2306 bool ModelExecution::resolve_promise(ModelAction *write, Promise *promise)
2308 ModelVector<ModelAction *> actions_to_check;
2310 for (unsigned int i = 0; i < promise->get_num_readers(); i++) {
2311 ModelAction *read = promise->get_reader(i);
2312 read_from(read, write);
2313 actions_to_check.push_back(read);
2315 /* Make sure the promise's value matches the write's value */
2316 ASSERT(promise->is_compatible(write) && promise->same_value(write));
2317 if (!mo_graph->resolvePromise(promise, write))
2318 priv->failed_promise = true;
2321 * @todo It is possible to end up in an inconsistent state, where a
2322 * "resolved" promise may still be referenced if
2323 * CycleGraph::resolvePromise() failed, so don't delete 'promise'.
2325 * Note that the inconsistency only matters when dumping mo_graph to
2331 //Check whether reading these writes has made threads unable to
2333 for (unsigned int i = 0; i < actions_to_check.size(); i++) {
2334 ModelAction *read = actions_to_check[i];
2335 mo_check_promises(read, true);
2342 * Compute the set of promises that could potentially be satisfied by this
2343 * action. Note that the set computation actually appears in the Node, not in
2345 * @param curr The ModelAction that may satisfy promises
2347 void ModelExecution::compute_promises(ModelAction *curr)
2349 for (unsigned int i = 0; i < promises.size(); i++) {
2350 Promise *promise = promises[i];
2351 if (!promise->is_compatible(curr) || !promise->same_value(curr))
2354 bool satisfy = true;
2355 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2356 const ModelAction *act = promise->get_reader(j);
2357 if (act->happens_before(curr) ||
2358 act->could_synchronize_with(curr)) {
2364 curr->get_node()->set_promise(i);
2368 /** Checks promises in response to change in ClockVector Threads. */
2369 void ModelExecution::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
2371 for (unsigned int i = 0; i < promises.size(); i++) {
2372 Promise *promise = promises[i];
2373 if (!promise->thread_is_available(tid))
2375 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2376 const ModelAction *act = promise->get_reader(j);
2377 if ((!old_cv || !old_cv->synchronized_since(act)) &&
2378 merge_cv->synchronized_since(act)) {
2379 if (promise->eliminate_thread(tid)) {
2380 /* Promise has failed */
2381 priv->failed_promise = true;
2389 void ModelExecution::check_promises_thread_disabled()
2391 for (unsigned int i = 0; i < promises.size(); i++) {
2392 Promise *promise = promises[i];
2393 if (promise->has_failed()) {
2394 priv->failed_promise = true;
2401 * @brief Checks promises in response to addition to modification order for
2404 * We test whether threads are still available for satisfying promises after an
2405 * addition to our modification order constraints. Those that are unavailable
2406 * are "eliminated". Once all threads are eliminated from satisfying a promise,
2407 * that promise has failed.
2409 * @param act The ModelAction which updated the modification order
2410 * @param is_read_check Should be true if act is a read and we must check for
2411 * updates to the store from which it read (there is a distinction here for
2412 * RMW's, which are both a load and a store)
2414 void ModelExecution::mo_check_promises(const ModelAction *act, bool is_read_check)
2416 const ModelAction *write = is_read_check ? act->get_reads_from() : act;
2418 for (unsigned int i = 0; i < promises.size(); i++) {
2419 Promise *promise = promises[i];
2421 // Is this promise on the same location?
2422 if (!promise->same_location(write))
2425 for (unsigned int j = 0; j < promise->get_num_readers(); j++) {
2426 const ModelAction *pread = promise->get_reader(j);
2427 if (!pread->happens_before(act))
2429 if (mo_graph->checkPromise(write, promise)) {
2430 priv->failed_promise = true;
2436 // Don't do any lookups twice for the same thread
2437 if (!promise->thread_is_available(act->get_tid()))
2440 if (mo_graph->checkReachable(promise, write)) {
2441 if (mo_graph->checkPromise(write, promise)) {
2442 priv->failed_promise = true;
2450 * Compute the set of writes that may break the current pending release
2451 * sequence. This information is extracted from previou release sequence
2454 * @param curr The current ModelAction. Must be a release sequence fixup
2457 void ModelExecution::compute_relseq_breakwrites(ModelAction *curr)
2459 if (pending_rel_seqs.empty())
2462 struct release_seq *pending = pending_rel_seqs.back();
2463 for (unsigned int i = 0; i < pending->writes.size(); i++) {
2464 const ModelAction *write = pending->writes[i];
2465 curr->get_node()->add_relseq_break(write);
2468 /* NULL means don't break the sequence; just synchronize */
2469 curr->get_node()->add_relseq_break(NULL);
2473 * Build up an initial set of all past writes that this 'read' action may read
2474 * from, as well as any previously-observed future values that must still be valid.
2476 * @param curr is the current ModelAction that we are exploring; it must be a
2479 void ModelExecution::build_may_read_from(ModelAction *curr)
2481 SnapVector<action_list_t> *thrd_lists = obj_thrd_map.get(curr->get_location());
2483 ASSERT(curr->is_read());
2485 ModelAction *last_sc_write = NULL;
2487 if (curr->is_seqcst())
2488 last_sc_write = get_last_seq_cst_write(curr);
2490 /* Iterate over all threads */
2491 for (i = 0; i < thrd_lists->size(); i++) {
2492 /* Iterate over actions in thread, starting from most recent */
2493 action_list_t *list = &(*thrd_lists)[i];
2494 action_list_t::reverse_iterator rit;
2495 for (rit = list->rbegin(); rit != list->rend(); rit++) {
2496 ModelAction *act = *rit;
2498 /* Only consider 'write' actions */
2499 if (!act->is_write() || act == curr)
2502 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
2503 bool allow_read = true;
2505 if (curr->is_seqcst() && (act->is_seqcst() || (last_sc_write != NULL && act->happens_before(last_sc_write))) && act != last_sc_write)
2507 else if (curr->get_sleep_flag() && !curr->is_seqcst() && !sleep_can_read_from(curr, act))
2511 /* Only add feasible reads */
2512 mo_graph->startChanges();
2513 r_modification_order(curr, act);
2514 if (!is_infeasible())
2515 curr->get_node()->add_read_from_past(act);
2516 mo_graph->rollbackChanges();
2519 /* Include at most one act per-thread that "happens before" curr */
2520 if (act->happens_before(curr))
2525 /* Inherit existing, promised future values */
2526 for (i = 0; i < promises.size(); i++) {
2527 const Promise *promise = promises[i];
2528 const ModelAction *promise_read = promise->get_reader(0);
2529 if (promise_read->same_var(curr)) {
2530 /* Only add feasible future-values */
2531 mo_graph->startChanges();
2532 r_modification_order(curr, promise);
2533 if (!is_infeasible())
2534 curr->get_node()->add_read_from_promise(promise_read);
2535 mo_graph->rollbackChanges();
2539 /* We may find no valid may-read-from only if the execution is doomed */
2540 if (!curr->get_node()->read_from_size()) {
2541 priv->no_valid_reads = true;
2545 if (DBG_ENABLED()) {
2546 model_print("Reached read action:\n");
2548 model_print("Printing read_from_past\n");
2549 curr->get_node()->print_read_from_past();
2550 model_print("End printing read_from_past\n");
2554 bool ModelExecution::sleep_can_read_from(ModelAction *curr, const ModelAction *write)
2556 for ( ; write != NULL; write = write->get_reads_from()) {
2557 /* UNINIT actions don't have a Node, and they never sleep */
2558 if (write->is_uninitialized())
2560 Node *prevnode = write->get_node()->get_parent();
2562 bool thread_sleep = prevnode->enabled_status(curr->get_tid()) == THREAD_SLEEP_SET;
2563 if (write->is_release() && thread_sleep)
2565 if (!write->is_rmw())
2572 * @brief Get an action representing an uninitialized atomic
2574 * This function may create a new one or try to retrieve one from the NodeStack
2576 * @param curr The current action, which prompts the creation of an UNINIT action
2577 * @return A pointer to the UNINIT ModelAction
2579 ModelAction * ModelExecution::get_uninitialized_action(const ModelAction *curr) const
2581 Node *node = curr->get_node();
2582 ModelAction *act = node->get_uninit_action();
2584 act = new ModelAction(ATOMIC_UNINIT, std::memory_order_relaxed, curr->get_location(), params->uninitvalue, model_thread);
2585 node->set_uninit_action(act);
2587 act->create_cv(NULL);
2591 static void print_list(const action_list_t *list)
2593 action_list_t::const_iterator it;
2595 model_print("---------------------------------------------------------------------\n");
2597 unsigned int hash = 0;
2599 for (it = list->begin(); it != list->end(); it++) {
2600 const ModelAction *act = *it;
2601 if (act->get_seq_number() > 0)
2603 hash = hash^(hash<<3)^((*it)->hash());
2605 model_print("HASH %u\n", hash);
2606 model_print("---------------------------------------------------------------------\n");
2609 #if SUPPORT_MOD_ORDER_DUMP
2610 void ModelExecution::dumpGraph(char *filename) const
2613 sprintf(buffer, "%s.dot", filename);
2614 FILE *file = fopen(buffer, "w");
2615 fprintf(file, "digraph %s {\n", filename);
2616 mo_graph->dumpNodes(file);
2617 ModelAction **thread_array = (ModelAction **)model_calloc(1, sizeof(ModelAction *) * get_num_threads());
2619 for (action_list_t::iterator it = action_trace.begin(); it != action_trace.end(); it++) {
2620 ModelAction *act = *it;
2621 if (act->is_read()) {
2622 mo_graph->dot_print_node(file, act);
2623 if (act->get_reads_from())
2624 mo_graph->dot_print_edge(file,
2625 act->get_reads_from(),
2627 "label=\"rf\", color=red, weight=2");
2629 mo_graph->dot_print_edge(file,
2630 act->get_reads_from_promise(),
2632 "label=\"rf\", color=red");
2634 if (thread_array[act->get_tid()]) {
2635 mo_graph->dot_print_edge(file,
2636 thread_array[id_to_int(act->get_tid())],
2638 "label=\"sb\", color=blue, weight=400");
2641 thread_array[act->get_tid()] = act;
2643 fprintf(file, "}\n");
2644 model_free(thread_array);
2649 /** @brief Prints an execution trace summary. */
2650 void ModelExecution::print_summary() const
2652 #if SUPPORT_MOD_ORDER_DUMP
2653 char buffername[100];
2654 sprintf(buffername, "exec%04u", get_execution_number());
2655 mo_graph->dumpGraphToFile(buffername);
2656 sprintf(buffername, "graph%04u", get_execution_number());
2657 dumpGraph(buffername);
2660 model_print("Execution %d:", get_execution_number());
2661 if (isfeasibleprefix()) {
2662 if (scheduler->all_threads_sleeping())
2663 model_print(" SLEEP-SET REDUNDANT");
2666 print_infeasibility(" INFEASIBLE");
2667 print_list(&action_trace);
2669 if (!promises.empty()) {
2670 model_print("Pending promises:\n");
2671 for (unsigned int i = 0; i < promises.size(); i++) {
2672 model_print(" [P%u] ", i);
2673 promises[i]->print();
2680 * Add a Thread to the system for the first time. Should only be called once
2682 * @param t The Thread to add
2684 void ModelExecution::add_thread(Thread *t)
2686 unsigned int i = id_to_int(t->get_id());
2687 if (i >= thread_map.size())
2688 thread_map.resize(i + 1);
2690 if (!t->is_model_thread())
2691 scheduler->add_thread(t);
2695 * @brief Get a Thread reference by its ID
2696 * @param tid The Thread's ID
2697 * @return A Thread reference
2699 Thread * ModelExecution::get_thread(thread_id_t tid) const
2701 unsigned int i = id_to_int(tid);
2702 if (i < thread_map.size())
2703 return thread_map[i];
2708 * @brief Get a reference to the Thread in which a ModelAction was executed
2709 * @param act The ModelAction
2710 * @return A Thread reference
2712 Thread * ModelExecution::get_thread(const ModelAction *act) const
2714 return get_thread(act->get_tid());
2718 * @brief Get a Promise's "promise number"
2720 * A "promise number" is an index number that is unique to a promise, valid
2721 * only for a specific snapshot of an execution trace. Promises may come and go
2722 * as they are generated an resolved, so an index only retains meaning for the
2725 * @param promise The Promise to check
2726 * @return The promise index, if the promise still is valid; otherwise -1
2728 int ModelExecution::get_promise_number(const Promise *promise) const
2730 for (unsigned int i = 0; i < promises.size(); i++)
2731 if (promises[i] == promise)
2738 * @brief Check if a Thread is currently enabled
2739 * @param t The Thread to check
2740 * @return True if the Thread is currently enabled
2742 bool ModelExecution::is_enabled(Thread *t) const
2744 return scheduler->is_enabled(t);
2748 * @brief Check if a Thread is currently enabled
2749 * @param tid The ID of the Thread to check
2750 * @return True if the Thread is currently enabled
2752 bool ModelExecution::is_enabled(thread_id_t tid) const
2754 return scheduler->is_enabled(tid);
2758 * @brief Select the next thread to execute based on the curren action
2760 * RMW actions occur in two parts, and we cannot split them. And THREAD_CREATE
2761 * actions should be followed by the execution of their child thread. In either
2762 * case, the current action should determine the next thread schedule.
2764 * @param curr The current action
2765 * @return The next thread to run, if the current action will determine this
2766 * selection; otherwise NULL
2768 Thread * ModelExecution::action_select_next_thread(const ModelAction *curr) const
2770 /* Do not split atomic RMW */
2771 if (curr->is_rmwr())
2772 return get_thread(curr);
2773 /* Follow CREATE with the created thread */
2774 if (curr->get_type() == THREAD_CREATE)
2775 return curr->get_thread_operand();
2779 /** @return True if the execution has taken too many steps */
2780 bool ModelExecution::too_many_steps() const
2782 return params->bound != 0 && priv->used_sequence_numbers > params->bound;
2786 * Takes the next step in the execution, if possible.
2787 * @param curr The current step to take
2788 * @return Returns the next Thread to run, if any; NULL if this execution
2791 Thread * ModelExecution::take_step(ModelAction *curr)
2793 Thread *curr_thrd = get_thread(curr);
2794 ASSERT(curr_thrd->get_state() == THREAD_READY);
2796 ASSERT(check_action_enabled(curr)); /* May have side effects? */
2797 curr = check_current_action(curr);
2800 if (curr_thrd->is_blocked() || curr_thrd->is_complete())
2801 scheduler->remove_thread(curr_thrd);
2803 return action_select_next_thread(curr);
2807 * Launch end-of-execution release sequence fixups only when
2808 * the execution is otherwise feasible AND there are:
2810 * (1) pending release sequences
2811 * (2) pending assertions that could be invalidated by a change
2812 * in clock vectors (i.e., data races)
2813 * (3) no pending promises
2815 void ModelExecution::fixup_release_sequences()
2817 while (!pending_rel_seqs.empty() &&
2818 is_feasible_prefix_ignore_relseq() &&
2819 haveUnrealizedRaces()) {
2820 model_print("*** WARNING: release sequence fixup action "
2821 "(%zu pending release seuqence(s)) ***\n",
2822 pending_rel_seqs.size());
2823 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2824 std::memory_order_seq_cst, NULL, VALUE_NONE,