9 #include "snapshot-interface.h"
11 #include "clockvector.h"
12 #include "cyclegraph.h"
15 #include "threads-model.h"
17 #define INITIAL_THREAD_ID 0
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23 /* Initialize default scheduler */
25 scheduler(new Scheduler()),
27 num_feasible_executions(0),
29 earliest_diverge(NULL),
30 action_trace(new action_list_t()),
31 thread_map(new HashTable<int, Thread *, int>()),
32 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
34 condvar_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
35 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
36 promises(new std::vector< Promise *, SnapshotAlloc<Promise *> >()),
37 futurevalues(new std::vector< struct PendingFutureValue, SnapshotAlloc<struct PendingFutureValue> >()),
38 pending_rel_seqs(new std::vector< struct release_seq *, SnapshotAlloc<struct release_seq *> >()),
39 thrd_last_action(new std::vector< ModelAction *, SnapshotAlloc<ModelAction *> >(1)),
40 node_stack(new NodeStack()),
41 mo_graph(new CycleGraph()),
42 failed_promise(false),
43 too_many_reads(false),
45 bad_synchronization(false)
47 /* Allocate this "size" on the snapshotting heap */
48 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
49 /* First thread created will have id INITIAL_THREAD_ID */
50 priv->next_thread_id = INITIAL_THREAD_ID;
52 /* Initialize a model-checker thread, for special ModelActions */
53 model_thread = new Thread(get_next_id());
54 thread_map->put(id_to_int(model_thread->get_id()), model_thread);
57 /** @brief Destructor */
58 ModelChecker::~ModelChecker()
60 for (unsigned int i = 0; i < get_num_threads(); i++)
61 delete thread_map->get(i);
66 delete lock_waiters_map;
67 delete condvar_waiters_map;
70 for (unsigned int i = 0; i < promises->size(); i++)
71 delete (*promises)[i];
74 delete pending_rel_seqs;
76 delete thrd_last_action;
83 * Restores user program to initial state and resets all model-checker data
86 void ModelChecker::reset_to_initial_state()
88 DEBUG("+++ Resetting to initial state +++\n");
89 node_stack->reset_execution();
90 failed_promise = false;
91 too_many_reads = false;
92 bad_synchronization = false;
94 snapshotObject->backTrackBeforeStep(0);
97 /** @return a thread ID for a new Thread */
98 thread_id_t ModelChecker::get_next_id()
100 return priv->next_thread_id++;
103 /** @return the number of user threads created during this execution */
104 unsigned int ModelChecker::get_num_threads()
106 return priv->next_thread_id;
109 /** @return The currently executing Thread. */
110 Thread * ModelChecker::get_current_thread()
112 return scheduler->get_current_thread();
115 /** @return a sequence number for a new ModelAction */
116 modelclock_t ModelChecker::get_next_seq_num()
118 return ++priv->used_sequence_numbers;
121 Node * ModelChecker::get_curr_node() {
122 return node_stack->get_head();
126 * @brief Choose the next thread to execute.
128 * This function chooses the next thread that should execute. It can force the
129 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
130 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
131 * The model-checker may have no preference regarding the next thread (i.e.,
132 * when exploring a new execution ordering), in which case this will return
134 * @param curr The current ModelAction. This action might guide the choice of
136 * @return The next thread to run. If the model-checker has no preference, NULL.
138 Thread * ModelChecker::get_next_thread(ModelAction *curr)
143 /* Do not split atomic actions. */
145 return thread_current();
146 /* The THREAD_CREATE action points to the created Thread */
147 else if (curr->get_type() == THREAD_CREATE)
148 return (Thread *)curr->get_location();
151 /* Have we completed exploring the preselected path? */
155 /* Else, we are trying to replay an execution */
156 ModelAction *next = node_stack->get_next()->get_action();
158 if (next == diverge) {
159 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
160 earliest_diverge=diverge;
162 Node *nextnode = next->get_node();
163 Node *prevnode = nextnode->get_parent();
164 scheduler->update_sleep_set(prevnode);
166 /* Reached divergence point */
167 if (nextnode->increment_misc()) {
168 /* The next node will try to satisfy a different misc_index values. */
169 tid = next->get_tid();
170 node_stack->pop_restofstack(2);
171 } else if (nextnode->increment_promise()) {
172 /* The next node will try to satisfy a different set of promises. */
173 tid = next->get_tid();
174 node_stack->pop_restofstack(2);
175 } else if (nextnode->increment_read_from()) {
176 /* The next node will read from a different value. */
177 tid = next->get_tid();
178 node_stack->pop_restofstack(2);
179 } else if (nextnode->increment_future_value()) {
180 /* The next node will try to read from a different future value. */
181 tid = next->get_tid();
182 node_stack->pop_restofstack(2);
183 } else if (nextnode->increment_relseq_break()) {
184 /* The next node will try to resolve a release sequence differently */
185 tid = next->get_tid();
186 node_stack->pop_restofstack(2);
188 /* Make a different thread execute for next step */
189 scheduler->add_sleep(thread_map->get(id_to_int(next->get_tid())));
190 tid = prevnode->get_next_backtrack();
191 /* Make sure the backtracked thread isn't sleeping. */
192 node_stack->pop_restofstack(1);
193 if (diverge==earliest_diverge) {
194 earliest_diverge=prevnode->get_action();
197 /* The correct sleep set is in the parent node. */
200 DEBUG("*** Divergence point ***\n");
204 tid = next->get_tid();
206 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
207 ASSERT(tid != THREAD_ID_T_NONE);
208 return thread_map->get(id_to_int(tid));
212 * We need to know what the next actions of all threads in the sleep
213 * set will be. This method computes them and stores the actions at
214 * the corresponding thread object's pending action.
217 void ModelChecker::execute_sleep_set() {
218 for(unsigned int i=0;i<get_num_threads();i++) {
219 thread_id_t tid=int_to_id(i);
220 Thread *thr=get_thread(tid);
221 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
222 thr->set_state(THREAD_RUNNING);
223 scheduler->next_thread(thr);
224 Thread::swap(&system_context, thr);
225 priv->current_action->set_sleep_flag();
226 thr->set_pending(priv->current_action);
229 priv->current_action = NULL;
232 void ModelChecker::wake_up_sleeping_actions(ModelAction * curr) {
233 for(unsigned int i=0;i<get_num_threads();i++) {
234 thread_id_t tid=int_to_id(i);
235 Thread *thr=get_thread(tid);
236 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
237 ModelAction *pending_act=thr->get_pending();
238 if (pending_act->could_synchronize_with(curr)) {
239 //Remove this thread from sleep set
240 scheduler->remove_sleep(thr);
247 * Queries the model-checker for more executions to explore and, if one
248 * exists, resets the model-checker state to execute a new execution.
250 * @return If there are more executions to explore, return true. Otherwise,
253 bool ModelChecker::next_execution()
259 if (isfinalfeasible()) {
260 printf("Earliest divergence point since last feasible execution:\n");
261 if (earliest_diverge)
262 earliest_diverge->print();
264 printf("(Not set)\n");
266 earliest_diverge = NULL;
267 num_feasible_executions++;
270 DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
271 pending_rel_seqs->size());
274 if (isfinalfeasible() || (params.bound != 0 && priv->used_sequence_numbers > params.bound ) || DBG_ENABLED() )
277 if ((diverge = get_next_backtrack()) == NULL)
281 printf("Next execution will diverge at:\n");
285 reset_to_initial_state();
289 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
291 switch (act->get_type()) {
295 /* linear search: from most recent to oldest */
296 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
297 action_list_t::reverse_iterator rit;
298 for (rit = list->rbegin(); rit != list->rend(); rit++) {
299 ModelAction *prev = *rit;
300 if (prev->could_synchronize_with(act))
306 case ATOMIC_TRYLOCK: {
307 /* linear search: from most recent to oldest */
308 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
309 action_list_t::reverse_iterator rit;
310 for (rit = list->rbegin(); rit != list->rend(); rit++) {
311 ModelAction *prev = *rit;
312 if (act->is_conflicting_lock(prev))
317 case ATOMIC_UNLOCK: {
318 /* linear search: from most recent to oldest */
319 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
320 action_list_t::reverse_iterator rit;
321 for (rit = list->rbegin(); rit != list->rend(); rit++) {
322 ModelAction *prev = *rit;
323 if (!act->same_thread(prev)&&prev->is_failed_trylock())
329 /* linear search: from most recent to oldest */
330 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
331 action_list_t::reverse_iterator rit;
332 for (rit = list->rbegin(); rit != list->rend(); rit++) {
333 ModelAction *prev = *rit;
334 if (!act->same_thread(prev)&&prev->is_failed_trylock())
336 if (!act->same_thread(prev)&&prev->is_notify())
342 case ATOMIC_NOTIFY_ALL:
343 case ATOMIC_NOTIFY_ONE: {
344 /* linear search: from most recent to oldest */
345 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
346 action_list_t::reverse_iterator rit;
347 for (rit = list->rbegin(); rit != list->rend(); rit++) {
348 ModelAction *prev = *rit;
349 if (!act->same_thread(prev)&&prev->is_wait())
360 /** This method finds backtracking points where we should try to
361 * reorder the parameter ModelAction against.
363 * @param the ModelAction to find backtracking points for.
365 void ModelChecker::set_backtracking(ModelAction *act)
367 Thread *t = get_thread(act);
368 ModelAction * prev = get_last_conflict(act);
372 Node * node = prev->get_node()->get_parent();
374 int low_tid, high_tid;
375 if (node->is_enabled(t)) {
376 low_tid = id_to_int(act->get_tid());
377 high_tid = low_tid+1;
380 high_tid = get_num_threads();
383 for(int i = low_tid; i < high_tid; i++) {
384 thread_id_t tid = int_to_id(i);
386 /* Don't backtrack into a point where the thread is disabled or sleeping. */
387 if (node->get_enabled_array()[i]!=THREAD_ENABLED)
390 /* Check if this has been explored already */
391 if (node->has_been_explored(tid))
394 /* See if fairness allows */
395 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
397 for(int t=0;t<node->get_num_threads();t++) {
398 thread_id_t tother=int_to_id(t);
399 if (node->is_enabled(tother) && node->has_priority(tother)) {
407 /* Cache the latest backtracking point */
408 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
409 priv->next_backtrack = prev;
411 /* If this is a new backtracking point, mark the tree */
412 if (!node->set_backtrack(tid))
414 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
415 id_to_int(prev->get_tid()),
416 id_to_int(t->get_id()));
425 * Returns last backtracking point. The model checker will explore a different
426 * path for this point in the next execution.
427 * @return The ModelAction at which the next execution should diverge.
429 ModelAction * ModelChecker::get_next_backtrack()
431 ModelAction *next = priv->next_backtrack;
432 priv->next_backtrack = NULL;
437 * Processes a read or rmw model action.
438 * @param curr is the read model action to process.
439 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
440 * @return True if processing this read updates the mo_graph.
442 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
445 bool updated = false;
447 const ModelAction *reads_from = curr->get_node()->get_read_from();
448 if (reads_from != NULL) {
449 mo_graph->startChanges();
451 value = reads_from->get_value();
452 bool r_status = false;
454 if (!second_part_of_rmw) {
455 check_recency(curr, reads_from);
456 r_status = r_modification_order(curr, reads_from);
460 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
461 mo_graph->rollbackChanges();
462 too_many_reads = false;
466 curr->read_from(reads_from);
467 mo_graph->commitChanges();
468 mo_check_promises(curr->get_tid(), reads_from);
471 } else if (!second_part_of_rmw) {
472 /* Read from future value */
473 value = curr->get_node()->get_future_value();
474 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
475 curr->read_from(NULL);
476 Promise *valuepromise = new Promise(curr, value, expiration);
477 promises->push_back(valuepromise);
479 get_thread(curr)->set_return_value(value);
485 * Processes a lock, trylock, or unlock model action. @param curr is
486 * the read model action to process.
488 * The try lock operation checks whether the lock is taken. If not,
489 * it falls to the normal lock operation case. If so, it returns
492 * The lock operation has already been checked that it is enabled, so
493 * it just grabs the lock and synchronizes with the previous unlock.
495 * The unlock operation has to re-enable all of the threads that are
496 * waiting on the lock.
498 * @return True if synchronization was updated; false otherwise
500 bool ModelChecker::process_mutex(ModelAction *curr) {
501 std::mutex *mutex=NULL;
502 struct std::mutex_state *state=NULL;
504 if (curr->is_trylock() || curr->is_lock() || curr->is_unlock()) {
505 mutex = (std::mutex *)curr->get_location();
506 state = mutex->get_state();
507 } else if(curr->is_wait()) {
508 mutex = (std::mutex *)curr->get_value();
509 state = mutex->get_state();
512 switch (curr->get_type()) {
513 case ATOMIC_TRYLOCK: {
514 bool success = !state->islocked;
515 curr->set_try_lock(success);
517 get_thread(curr)->set_return_value(0);
520 get_thread(curr)->set_return_value(1);
522 //otherwise fall into the lock case
524 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
525 printf("Lock access before initialization\n");
528 state->islocked = true;
529 ModelAction *unlock = get_last_unlock(curr);
530 //synchronize with the previous unlock statement
531 if (unlock != NULL) {
532 curr->synchronize_with(unlock);
537 case ATOMIC_UNLOCK: {
539 state->islocked = false;
540 //wake up the other threads
541 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
542 //activate all the waiting threads
543 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
544 scheduler->wake(get_thread(*rit));
551 state->islocked = false;
552 //wake up the other threads
553 action_list_t *waiters = lock_waiters_map->get_safe_ptr((void *) curr->get_value());
554 //activate all the waiting threads
555 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
556 scheduler->wake(get_thread(*rit));
559 //check whether we should go to sleep or not...simulate spurious failures
560 if (curr->get_node()->get_misc()==0) {
561 condvar_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
563 scheduler->sleep(get_current_thread());
567 case ATOMIC_NOTIFY_ALL: {
568 action_list_t *waiters = condvar_waiters_map->get_safe_ptr(curr->get_location());
569 //activate all the waiting threads
570 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
571 scheduler->wake(get_thread(*rit));
576 case ATOMIC_NOTIFY_ONE: {
577 action_list_t *waiters = condvar_waiters_map->get_safe_ptr(curr->get_location());
578 int wakeupthread=curr->get_node()->get_misc();
579 action_list_t::iterator it = waiters->begin();
580 advance(it, wakeupthread);
581 scheduler->wake(get_thread(*it));
593 * Process a write ModelAction
594 * @param curr The ModelAction to process
595 * @return True if the mo_graph was updated or promises were resolved
597 bool ModelChecker::process_write(ModelAction *curr)
599 bool updated_mod_order = w_modification_order(curr);
600 bool updated_promises = resolve_promises(curr);
602 if (promises->size() == 0) {
603 for (unsigned int i = 0; i < futurevalues->size(); i++) {
604 struct PendingFutureValue pfv = (*futurevalues)[i];
605 //Do more ambitious checks now that mo is more complete
606 if (mo_may_allow(pfv.writer, pfv.act)&&
607 pfv.act->get_node()->add_future_value(pfv.writer->get_value(), pfv.writer->get_seq_number()+params.maxfuturedelay) &&
608 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
609 priv->next_backtrack = pfv.act;
611 futurevalues->resize(0);
614 mo_graph->commitChanges();
615 mo_check_promises(curr->get_tid(), curr);
617 get_thread(curr)->set_return_value(VALUE_NONE);
618 return updated_mod_order || updated_promises;
622 * @brief Process the current action for thread-related activity
624 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
625 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
626 * synchronization, etc. This function is a no-op for non-THREAD actions
627 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
629 * @param curr The current action
630 * @return True if synchronization was updated or a thread completed
632 bool ModelChecker::process_thread_action(ModelAction *curr)
634 bool updated = false;
636 switch (curr->get_type()) {
637 case THREAD_CREATE: {
638 Thread *th = (Thread *)curr->get_location();
639 th->set_creation(curr);
643 Thread *blocking = (Thread *)curr->get_location();
644 ModelAction *act = get_last_action(blocking->get_id());
645 curr->synchronize_with(act);
646 updated = true; /* trigger rel-seq checks */
649 case THREAD_FINISH: {
650 Thread *th = get_thread(curr);
651 while (!th->wait_list_empty()) {
652 ModelAction *act = th->pop_wait_list();
653 scheduler->wake(get_thread(act));
656 updated = true; /* trigger rel-seq checks */
660 check_promises(curr->get_tid(), NULL, curr->get_cv());
671 * @brief Process the current action for release sequence fixup activity
673 * Performs model-checker release sequence fixups for the current action,
674 * forcing a single pending release sequence to break (with a given, potential
675 * "loose" write) or to complete (i.e., synchronize). If a pending release
676 * sequence forms a complete release sequence, then we must perform the fixup
677 * synchronization, mo_graph additions, etc.
679 * @param curr The current action; must be a release sequence fixup action
680 * @param work_queue The work queue to which to add work items as they are
683 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
685 const ModelAction *write = curr->get_node()->get_relseq_break();
686 struct release_seq *sequence = pending_rel_seqs->back();
687 pending_rel_seqs->pop_back();
689 ModelAction *acquire = sequence->acquire;
690 const ModelAction *rf = sequence->rf;
691 const ModelAction *release = sequence->release;
695 ASSERT(release->same_thread(rf));
699 * @todo Forcing a synchronization requires that we set
700 * modification order constraints. For instance, we can't allow
701 * a fixup sequence in which two separate read-acquire
702 * operations read from the same sequence, where the first one
703 * synchronizes and the other doesn't. Essentially, we can't
704 * allow any writes to insert themselves between 'release' and
708 /* Must synchronize */
709 if (!acquire->synchronize_with(release)) {
710 set_bad_synchronization();
713 /* Re-check all pending release sequences */
714 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
715 /* Re-check act for mo_graph edges */
716 work_queue->push_back(MOEdgeWorkEntry(acquire));
718 /* propagate synchronization to later actions */
719 action_list_t::reverse_iterator rit = action_trace->rbegin();
720 for (; (*rit) != acquire; rit++) {
721 ModelAction *propagate = *rit;
722 if (acquire->happens_before(propagate)) {
723 propagate->synchronize_with(acquire);
724 /* Re-check 'propagate' for mo_graph edges */
725 work_queue->push_back(MOEdgeWorkEntry(propagate));
729 /* Break release sequence with new edges:
730 * release --mo--> write --mo--> rf */
731 mo_graph->addEdge(release, write);
732 mo_graph->addEdge(write, rf);
735 /* See if we have realized a data race */
736 if (checkDataRaces())
741 * Initialize the current action by performing one or more of the following
742 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
743 * in the NodeStack, manipulating backtracking sets, allocating and
744 * initializing clock vectors, and computing the promises to fulfill.
746 * @param curr The current action, as passed from the user context; may be
747 * freed/invalidated after the execution of this function
748 * @return The current action, as processed by the ModelChecker. Is only the
749 * same as the parameter @a curr if this is a newly-explored action.
751 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
753 ModelAction *newcurr;
755 if (curr->is_rmwc() || curr->is_rmw()) {
756 newcurr = process_rmw(curr);
759 if (newcurr->is_rmw())
760 compute_promises(newcurr);
764 curr->set_seq_number(get_next_seq_num());
766 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
768 /* First restore type and order in case of RMW operation */
770 newcurr->copy_typeandorder(curr);
772 ASSERT(curr->get_location() == newcurr->get_location());
773 newcurr->copy_from_new(curr);
775 /* Discard duplicate ModelAction; use action from NodeStack */
778 /* Always compute new clock vector */
779 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
783 /* Always compute new clock vector */
784 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
786 * Perform one-time actions when pushing new ModelAction onto
789 if (newcurr->is_write())
790 compute_promises(newcurr);
791 else if (newcurr->is_relseq_fixup())
792 compute_relseq_breakwrites(newcurr);
793 else if (newcurr->is_wait())
794 newcurr->get_node()->set_misc_max(2);
795 else if (newcurr->is_notify_one()) {
796 newcurr->get_node()->set_misc_max(condvar_waiters_map->get_safe_ptr(newcurr->get_location())->size());
803 * @brief Check whether a model action is enabled.
805 * Checks whether a lock or join operation would be successful (i.e., is the
806 * lock already locked, or is the joined thread already complete). If not, put
807 * the action in a waiter list.
809 * @param curr is the ModelAction to check whether it is enabled.
810 * @return a bool that indicates whether the action is enabled.
812 bool ModelChecker::check_action_enabled(ModelAction *curr) {
813 if (curr->is_lock()) {
814 std::mutex * lock = (std::mutex *)curr->get_location();
815 struct std::mutex_state * state = lock->get_state();
816 if (state->islocked) {
817 //Stick the action in the appropriate waiting queue
818 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
821 } else if (curr->get_type() == THREAD_JOIN) {
822 Thread *blocking = (Thread *)curr->get_location();
823 if (!blocking->is_complete()) {
824 blocking->push_wait_list(curr);
833 * This is the heart of the model checker routine. It performs model-checking
834 * actions corresponding to a given "current action." Among other processes, it
835 * calculates reads-from relationships, updates synchronization clock vectors,
836 * forms a memory_order constraints graph, and handles replay/backtrack
837 * execution when running permutations of previously-observed executions.
839 * @param curr The current action to process
840 * @return The next Thread that must be executed. May be NULL if ModelChecker
841 * makes no choice (e.g., according to replay execution, combining RMW actions,
844 Thread * ModelChecker::check_current_action(ModelAction *curr)
847 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
849 if (!check_action_enabled(curr)) {
850 /* Make the execution look like we chose to run this action
851 * much later, when a lock/join can succeed */
852 get_current_thread()->set_pending(curr);
853 scheduler->sleep(get_current_thread());
854 return get_next_thread(NULL);
857 ModelAction *newcurr = initialize_curr_action(curr);
859 wake_up_sleeping_actions(curr);
861 /* Add the action to lists before any other model-checking tasks */
862 if (!second_part_of_rmw)
863 add_action_to_lists(newcurr);
865 /* Build may_read_from set for newly-created actions */
866 if (curr == newcurr && curr->is_read())
867 build_reads_from_past(curr);
870 /* Initialize work_queue with the "current action" work */
871 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
872 while (!work_queue.empty()) {
873 WorkQueueEntry work = work_queue.front();
874 work_queue.pop_front();
877 case WORK_CHECK_CURR_ACTION: {
878 ModelAction *act = work.action;
879 bool update = false; /* update this location's release seq's */
880 bool update_all = false; /* update all release seq's */
882 if (process_thread_action(curr))
885 if (act->is_read() && process_read(act, second_part_of_rmw))
888 if (act->is_write() && process_write(act))
891 if (act->is_mutex_op() && process_mutex(act))
894 if (act->is_relseq_fixup())
895 process_relseq_fixup(curr, &work_queue);
898 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
900 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
903 case WORK_CHECK_RELEASE_SEQ:
904 resolve_release_sequences(work.location, &work_queue);
906 case WORK_CHECK_MO_EDGES: {
907 /** @todo Complete verification of work_queue */
908 ModelAction *act = work.action;
909 bool updated = false;
911 if (act->is_read()) {
912 const ModelAction *rf = act->get_reads_from();
913 if (rf != NULL && r_modification_order(act, rf))
916 if (act->is_write()) {
917 if (w_modification_order(act))
920 mo_graph->commitChanges();
923 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
932 check_curr_backtracking(curr);
933 set_backtracking(curr);
934 return get_next_thread(curr);
937 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
938 Node *currnode = curr->get_node();
939 Node *parnode = currnode->get_parent();
941 if ((!parnode->backtrack_empty() ||
942 !currnode->misc_empty() ||
943 !currnode->read_from_empty() ||
944 !currnode->future_value_empty() ||
945 !currnode->promise_empty() ||
946 !currnode->relseq_break_empty())
947 && (!priv->next_backtrack ||
948 *curr > *priv->next_backtrack)) {
949 priv->next_backtrack = curr;
953 bool ModelChecker::promises_expired() {
954 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
955 Promise *promise = (*promises)[promise_index];
956 if (promise->get_expiration()<priv->used_sequence_numbers) {
963 /** @return whether the current partial trace must be a prefix of a
965 bool ModelChecker::isfeasibleprefix() {
966 return promises->size() == 0 && pending_rel_seqs->size() == 0;
969 /** @return whether the current partial trace is feasible. */
970 bool ModelChecker::isfeasible() {
971 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
972 DEBUG("Infeasible: RMW violation\n");
974 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
977 /** @return whether the current partial trace is feasible other than
978 * multiple RMW reading from the same store. */
979 bool ModelChecker::isfeasibleotherthanRMW() {
981 if (mo_graph->checkForCycles())
982 DEBUG("Infeasible: modification order cycles\n");
984 DEBUG("Infeasible: failed promise\n");
986 DEBUG("Infeasible: too many reads\n");
987 if (bad_synchronization)
988 DEBUG("Infeasible: bad synchronization ordering\n");
989 if (promises_expired())
990 DEBUG("Infeasible: promises expired\n");
992 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
995 /** Returns whether the current completed trace is feasible. */
996 bool ModelChecker::isfinalfeasible() {
997 if (DBG_ENABLED() && promises->size() != 0)
998 DEBUG("Infeasible: unrevolved promises\n");
1000 return isfeasible() && promises->size() == 0;
1003 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
1004 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
1005 ModelAction *lastread = get_last_action(act->get_tid());
1006 lastread->process_rmw(act);
1007 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
1008 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
1009 mo_graph->commitChanges();
1015 * Checks whether a thread has read from the same write for too many times
1016 * without seeing the effects of a later write.
1019 * 1) there must a different write that we could read from that would satisfy the modification order,
1020 * 2) we must have read from the same value in excess of maxreads times, and
1021 * 3) that other write must have been in the reads_from set for maxreads times.
1023 * If so, we decide that the execution is no longer feasible.
1025 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
1026 if (params.maxreads != 0) {
1028 if (curr->get_node()->get_read_from_size() <= 1)
1030 //Must make sure that execution is currently feasible... We could
1031 //accidentally clear by rolling back
1034 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1035 int tid = id_to_int(curr->get_tid());
1038 if ((int)thrd_lists->size() <= tid)
1040 action_list_t *list = &(*thrd_lists)[tid];
1042 action_list_t::reverse_iterator rit = list->rbegin();
1043 /* Skip past curr */
1044 for (; (*rit) != curr; rit++)
1046 /* go past curr now */
1049 action_list_t::reverse_iterator ritcopy = rit;
1050 //See if we have enough reads from the same value
1052 for (; count < params.maxreads; rit++,count++) {
1053 if (rit==list->rend())
1055 ModelAction *act = *rit;
1056 if (!act->is_read())
1059 if (act->get_reads_from() != rf)
1061 if (act->get_node()->get_read_from_size() <= 1)
1064 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
1066 const ModelAction * write = curr->get_node()->get_read_from_at(i);
1068 //Need a different write
1072 /* Test to see whether this is a feasible write to read from*/
1073 mo_graph->startChanges();
1074 r_modification_order(curr, write);
1075 bool feasiblereadfrom = isfeasible();
1076 mo_graph->rollbackChanges();
1078 if (!feasiblereadfrom)
1082 bool feasiblewrite = true;
1083 //new we need to see if this write works for everyone
1085 for (int loop = count; loop>0; loop--,rit++) {
1086 ModelAction *act=*rit;
1087 bool foundvalue = false;
1088 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
1089 if (act->get_node()->get_read_from_at(i)==write) {
1095 feasiblewrite = false;
1099 if (feasiblewrite) {
1100 too_many_reads = true;
1108 * Updates the mo_graph with the constraints imposed from the current
1111 * Basic idea is the following: Go through each other thread and find
1112 * the lastest action that happened before our read. Two cases:
1114 * (1) The action is a write => that write must either occur before
1115 * the write we read from or be the write we read from.
1117 * (2) The action is a read => the write that that action read from
1118 * must occur before the write we read from or be the same write.
1120 * @param curr The current action. Must be a read.
1121 * @param rf The action that curr reads from. Must be a write.
1122 * @return True if modification order edges were added; false otherwise
1124 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
1126 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1129 ASSERT(curr->is_read());
1131 /* Iterate over all threads */
1132 for (i = 0; i < thrd_lists->size(); i++) {
1133 /* Iterate over actions in thread, starting from most recent */
1134 action_list_t *list = &(*thrd_lists)[i];
1135 action_list_t::reverse_iterator rit;
1136 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1137 ModelAction *act = *rit;
1140 * Include at most one act per-thread that "happens
1141 * before" curr. Don't consider reflexively.
1143 if (act->happens_before(curr) && act != curr) {
1144 if (act->is_write()) {
1146 mo_graph->addEdge(act, rf);
1150 const ModelAction *prevreadfrom = act->get_reads_from();
1151 //if the previous read is unresolved, keep going...
1152 if (prevreadfrom == NULL)
1155 if (rf != prevreadfrom) {
1156 mo_graph->addEdge(prevreadfrom, rf);
1168 /** This method fixes up the modification order when we resolve a
1169 * promises. The basic problem is that actions that occur after the
1170 * read curr could not property add items to the modification order
1173 * So for each thread, we find the earliest item that happens after
1174 * the read curr. This is the item we have to fix up with additional
1175 * constraints. If that action is write, we add a MO edge between
1176 * the Action rf and that action. If the action is a read, we add a
1177 * MO edge between the Action rf, and whatever the read accessed.
1179 * @param curr is the read ModelAction that we are fixing up MO edges for.
1180 * @param rf is the write ModelAction that curr reads from.
1183 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1185 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1187 ASSERT(curr->is_read());
1189 /* Iterate over all threads */
1190 for (i = 0; i < thrd_lists->size(); i++) {
1191 /* Iterate over actions in thread, starting from most recent */
1192 action_list_t *list = &(*thrd_lists)[i];
1193 action_list_t::reverse_iterator rit;
1194 ModelAction *lastact = NULL;
1196 /* Find last action that happens after curr that is either not curr or a rmw */
1197 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1198 ModelAction *act = *rit;
1199 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1205 /* Include at most one act per-thread that "happens before" curr */
1206 if (lastact != NULL) {
1207 if (lastact==curr) {
1208 //Case 1: The resolved read is a RMW, and we need to make sure
1209 //that the write portion of the RMW mod order after rf
1211 mo_graph->addEdge(rf, lastact);
1212 } else if (lastact->is_read()) {
1213 //Case 2: The resolved read is a normal read and the next
1214 //operation is a read, and we need to make sure the value read
1215 //is mod ordered after rf
1217 const ModelAction *postreadfrom = lastact->get_reads_from();
1218 if (postreadfrom != NULL&&rf != postreadfrom)
1219 mo_graph->addEdge(rf, postreadfrom);
1221 //Case 3: The resolved read is a normal read and the next
1222 //operation is a write, and we need to make sure that the
1223 //write is mod ordered after rf
1225 mo_graph->addEdge(rf, lastact);
1233 * Updates the mo_graph with the constraints imposed from the current write.
1235 * Basic idea is the following: Go through each other thread and find
1236 * the lastest action that happened before our write. Two cases:
1238 * (1) The action is a write => that write must occur before
1241 * (2) The action is a read => the write that that action read from
1242 * must occur before the current write.
1244 * This method also handles two other issues:
1246 * (I) Sequential Consistency: Making sure that if the current write is
1247 * seq_cst, that it occurs after the previous seq_cst write.
1249 * (II) Sending the write back to non-synchronizing reads.
1251 * @param curr The current action. Must be a write.
1252 * @return True if modification order edges were added; false otherwise
1254 bool ModelChecker::w_modification_order(ModelAction *curr)
1256 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1259 ASSERT(curr->is_write());
1261 if (curr->is_seqcst()) {
1262 /* We have to at least see the last sequentially consistent write,
1263 so we are initialized. */
1264 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1265 if (last_seq_cst != NULL) {
1266 mo_graph->addEdge(last_seq_cst, curr);
1271 /* Iterate over all threads */
1272 for (i = 0; i < thrd_lists->size(); i++) {
1273 /* Iterate over actions in thread, starting from most recent */
1274 action_list_t *list = &(*thrd_lists)[i];
1275 action_list_t::reverse_iterator rit;
1276 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1277 ModelAction *act = *rit;
1280 * 1) If RMW and it actually read from something, then we
1281 * already have all relevant edges, so just skip to next
1284 * 2) If RMW and it didn't read from anything, we should
1285 * whatever edge we can get to speed up convergence.
1287 * 3) If normal write, we need to look at earlier actions, so
1288 * continue processing list.
1290 if (curr->is_rmw()) {
1291 if (curr->get_reads_from()!=NULL)
1300 * Include at most one act per-thread that "happens
1303 if (act->happens_before(curr)) {
1305 * Note: if act is RMW, just add edge:
1307 * The following edge should be handled elsewhere:
1308 * readfrom(act) --mo--> act
1310 if (act->is_write())
1311 mo_graph->addEdge(act, curr);
1312 else if (act->is_read()) {
1313 //if previous read accessed a null, just keep going
1314 if (act->get_reads_from() == NULL)
1316 mo_graph->addEdge(act->get_reads_from(), curr);
1320 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1321 !act->same_thread(curr)) {
1322 /* We have an action that:
1323 (1) did not happen before us
1324 (2) is a read and we are a write
1325 (3) cannot synchronize with us
1326 (4) is in a different thread
1328 that read could potentially read from our write. Note that
1329 these checks are overly conservative at this point, we'll
1330 do more checks before actually removing the
1334 if (thin_air_constraint_may_allow(curr, act)) {
1336 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1337 struct PendingFutureValue pfv = {curr,act};
1338 futurevalues->push_back(pfv);
1348 /** Arbitrary reads from the future are not allowed. Section 29.3
1349 * part 9 places some constraints. This method checks one result of constraint
1350 * constraint. Others require compiler support. */
1351 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1352 if (!writer->is_rmw())
1355 if (!reader->is_rmw())
1358 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1359 if (search == reader)
1361 if (search->get_tid() == reader->get_tid() &&
1362 search->happens_before(reader))
1369 /** Arbitrary reads from the future are not allowed. Section 29.3
1370 * part 9 places some constraints. This method checks one result of constraint
1371 * constraint. Others require compiler support. */
1372 bool ModelChecker::mo_may_allow(const ModelAction * writer, const ModelAction *reader) {
1373 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(reader->get_location());
1375 //Get write that follows reader action
1376 action_list_t *list = &(*thrd_lists)[id_to_int(reader->get_tid())];
1377 action_list_t::reverse_iterator rit;
1378 ModelAction *first_write_after_read=NULL;
1380 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1381 ModelAction *act = *rit;
1384 if (act->is_write())
1385 first_write_after_read=act;
1388 if (first_write_after_read==NULL)
1391 return !mo_graph->checkReachable(first_write_after_read, writer);
1397 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1398 * The ModelAction under consideration is expected to be taking part in
1399 * release/acquire synchronization as an object of the "reads from" relation.
1400 * Note that this can only provide release sequence support for RMW chains
1401 * which do not read from the future, as those actions cannot be traced until
1402 * their "promise" is fulfilled. Similarly, we may not even establish the
1403 * presence of a release sequence with certainty, as some modification order
1404 * constraints may be decided further in the future. Thus, this function
1405 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1406 * and a boolean representing certainty.
1408 * @param rf The action that might be part of a release sequence. Must be a
1410 * @param release_heads A pass-by-reference style return parameter. After
1411 * execution of this function, release_heads will contain the heads of all the
1412 * relevant release sequences, if any exists with certainty
1413 * @param pending A pass-by-reference style return parameter which is only used
1414 * when returning false (i.e., uncertain). Returns most information regarding
1415 * an uncertain release sequence, including any write operations that might
1416 * break the sequence.
1417 * @return true, if the ModelChecker is certain that release_heads is complete;
1420 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1421 rel_heads_list_t *release_heads,
1422 struct release_seq *pending) const
1424 /* Only check for release sequences if there are no cycles */
1425 if (mo_graph->checkForCycles())
1429 ASSERT(rf->is_write());
1431 if (rf->is_release())
1432 release_heads->push_back(rf);
1434 break; /* End of RMW chain */
1436 /** @todo Need to be smarter here... In the linux lock
1437 * example, this will run to the beginning of the program for
1439 /** @todo The way to be smarter here is to keep going until 1
1440 * thread has a release preceded by an acquire and you've seen
1443 /* acq_rel RMW is a sufficient stopping condition */
1444 if (rf->is_acquire() && rf->is_release())
1445 return true; /* complete */
1447 rf = rf->get_reads_from();
1450 /* read from future: need to settle this later */
1452 return false; /* incomplete */
1455 if (rf->is_release())
1456 return true; /* complete */
1458 /* else relaxed write; check modification order for contiguous subsequence
1459 * -> rf must be same thread as release */
1460 int tid = id_to_int(rf->get_tid());
1461 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1462 action_list_t *list = &(*thrd_lists)[tid];
1463 action_list_t::const_reverse_iterator rit;
1465 /* Find rf in the thread list */
1466 rit = std::find(list->rbegin(), list->rend(), rf);
1467 ASSERT(rit != list->rend());
1469 /* Find the last write/release */
1470 for (; rit != list->rend(); rit++)
1471 if ((*rit)->is_release())
1473 if (rit == list->rend()) {
1474 /* No write-release in this thread */
1475 return true; /* complete */
1477 ModelAction *release = *rit;
1479 ASSERT(rf->same_thread(release));
1481 pending->writes.clear();
1483 bool certain = true;
1484 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1485 if (id_to_int(rf->get_tid()) == (int)i)
1487 list = &(*thrd_lists)[i];
1489 /* Can we ensure no future writes from this thread may break
1490 * the release seq? */
1491 bool future_ordered = false;
1493 ModelAction *last = get_last_action(int_to_id(i));
1494 Thread *th = get_thread(int_to_id(i));
1495 if ((last && rf->happens_before(last)) ||
1496 !scheduler->is_enabled(th) ||
1498 future_ordered = true;
1500 ASSERT(!th->is_model_thread() || future_ordered);
1502 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1503 const ModelAction *act = *rit;
1504 /* Reach synchronization -> this thread is complete */
1505 if (act->happens_before(release))
1507 if (rf->happens_before(act)) {
1508 future_ordered = true;
1512 /* Only non-RMW writes can break release sequences */
1513 if (!act->is_write() || act->is_rmw())
1516 /* Check modification order */
1517 if (mo_graph->checkReachable(rf, act)) {
1518 /* rf --mo--> act */
1519 future_ordered = true;
1522 if (mo_graph->checkReachable(act, release))
1523 /* act --mo--> release */
1525 if (mo_graph->checkReachable(release, act) &&
1526 mo_graph->checkReachable(act, rf)) {
1527 /* release --mo-> act --mo--> rf */
1528 return true; /* complete */
1530 /* act may break release sequence */
1531 pending->writes.push_back(act);
1534 if (!future_ordered)
1535 certain = false; /* This thread is uncertain */
1539 release_heads->push_back(release);
1540 pending->writes.clear();
1542 pending->release = release;
1549 * A public interface for getting the release sequence head(s) with which a
1550 * given ModelAction must synchronize. This function only returns a non-empty
1551 * result when it can locate a release sequence head with certainty. Otherwise,
1552 * it may mark the internal state of the ModelChecker so that it will handle
1553 * the release sequence at a later time, causing @a act to update its
1554 * synchronization at some later point in execution.
1555 * @param act The 'acquire' action that may read from a release sequence
1556 * @param release_heads A pass-by-reference return parameter. Will be filled
1557 * with the head(s) of the release sequence(s), if they exists with certainty.
1558 * @see ModelChecker::release_seq_heads
1560 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1562 const ModelAction *rf = act->get_reads_from();
1563 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1564 sequence->acquire = act;
1566 if (!release_seq_heads(rf, release_heads, sequence)) {
1567 /* add act to 'lazy checking' list */
1568 pending_rel_seqs->push_back(sequence);
1570 snapshot_free(sequence);
1575 * Attempt to resolve all stashed operations that might synchronize with a
1576 * release sequence for a given location. This implements the "lazy" portion of
1577 * determining whether or not a release sequence was contiguous, since not all
1578 * modification order information is present at the time an action occurs.
1580 * @param location The location/object that should be checked for release
1581 * sequence resolutions. A NULL value means to check all locations.
1582 * @param work_queue The work queue to which to add work items as they are
1584 * @return True if any updates occurred (new synchronization, new mo_graph
1587 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1589 bool updated = false;
1590 std::vector< struct release_seq *, SnapshotAlloc<struct release_seq *> >::iterator it = pending_rel_seqs->begin();
1591 while (it != pending_rel_seqs->end()) {
1592 struct release_seq *pending = *it;
1593 ModelAction *act = pending->acquire;
1595 /* Only resolve sequences on the given location, if provided */
1596 if (location && act->get_location() != location) {
1601 const ModelAction *rf = act->get_reads_from();
1602 rel_heads_list_t release_heads;
1604 complete = release_seq_heads(rf, &release_heads, pending);
1605 for (unsigned int i = 0; i < release_heads.size(); i++) {
1606 if (!act->has_synchronized_with(release_heads[i])) {
1607 if (act->synchronize_with(release_heads[i]))
1610 set_bad_synchronization();
1615 /* Re-check all pending release sequences */
1616 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1617 /* Re-check act for mo_graph edges */
1618 work_queue->push_back(MOEdgeWorkEntry(act));
1620 /* propagate synchronization to later actions */
1621 action_list_t::reverse_iterator rit = action_trace->rbegin();
1622 for (; (*rit) != act; rit++) {
1623 ModelAction *propagate = *rit;
1624 if (act->happens_before(propagate)) {
1625 propagate->synchronize_with(act);
1626 /* Re-check 'propagate' for mo_graph edges */
1627 work_queue->push_back(MOEdgeWorkEntry(propagate));
1632 it = pending_rel_seqs->erase(it);
1633 snapshot_free(pending);
1639 // If we resolved promises or data races, see if we have realized a data race.
1640 if (checkDataRaces()) {
1648 * Performs various bookkeeping operations for the current ModelAction. For
1649 * instance, adds action to the per-object, per-thread action vector and to the
1650 * action trace list of all thread actions.
1652 * @param act is the ModelAction to add.
1654 void ModelChecker::add_action_to_lists(ModelAction *act)
1656 int tid = id_to_int(act->get_tid());
1657 action_trace->push_back(act);
1659 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1661 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1662 if (tid >= (int)vec->size())
1663 vec->resize(priv->next_thread_id);
1664 (*vec)[tid].push_back(act);
1666 if ((int)thrd_last_action->size() <= tid)
1667 thrd_last_action->resize(get_num_threads());
1668 (*thrd_last_action)[tid] = act;
1670 if (act->is_wait()) {
1671 void *mutex_loc=(void *) act->get_value();
1672 obj_map->get_safe_ptr(mutex_loc)->push_back(act);
1674 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(mutex_loc);
1675 if (tid >= (int)vec->size())
1676 vec->resize(priv->next_thread_id);
1677 (*vec)[tid].push_back(act);
1679 if ((int)thrd_last_action->size() <= tid)
1680 thrd_last_action->resize(get_num_threads());
1681 (*thrd_last_action)[tid] = act;
1686 * @brief Get the last action performed by a particular Thread
1687 * @param tid The thread ID of the Thread in question
1688 * @return The last action in the thread
1690 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1692 int threadid = id_to_int(tid);
1693 if (threadid < (int)thrd_last_action->size())
1694 return (*thrd_last_action)[id_to_int(tid)];
1700 * Gets the last memory_order_seq_cst write (in the total global sequence)
1701 * performed on a particular object (i.e., memory location), not including the
1703 * @param curr The current ModelAction; also denotes the object location to
1705 * @return The last seq_cst write
1707 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1709 void *location = curr->get_location();
1710 action_list_t *list = obj_map->get_safe_ptr(location);
1711 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1712 action_list_t::reverse_iterator rit;
1713 for (rit = list->rbegin(); rit != list->rend(); rit++)
1714 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1720 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1721 * location). This function identifies the mutex according to the current
1722 * action, which is presumed to perform on the same mutex.
1723 * @param curr The current ModelAction; also denotes the object location to
1725 * @return The last unlock operation
1727 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1729 void *location = curr->get_location();
1730 action_list_t *list = obj_map->get_safe_ptr(location);
1731 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1732 action_list_t::reverse_iterator rit;
1733 for (rit = list->rbegin(); rit != list->rend(); rit++)
1734 if ((*rit)->is_unlock() || (*rit)->is_wait())
1739 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1741 ModelAction *parent = get_last_action(tid);
1743 parent = get_thread(tid)->get_creation();
1748 * Returns the clock vector for a given thread.
1749 * @param tid The thread whose clock vector we want
1750 * @return Desired clock vector
1752 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1754 return get_parent_action(tid)->get_cv();
1758 * Resolve a set of Promises with a current write. The set is provided in the
1759 * Node corresponding to @a write.
1760 * @param write The ModelAction that is fulfilling Promises
1761 * @return True if promises were resolved; false otherwise
1763 bool ModelChecker::resolve_promises(ModelAction *write)
1765 bool resolved = false;
1766 std::vector< thread_id_t, ModelAlloc<thread_id_t> > threads_to_check;
1768 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1769 Promise *promise = (*promises)[promise_index];
1770 if (write->get_node()->get_promise(i)) {
1771 ModelAction *read = promise->get_action();
1772 if (read->is_rmw()) {
1773 mo_graph->addRMWEdge(write, read);
1775 read->read_from(write);
1776 //First fix up the modification order for actions that happened
1778 r_modification_order(read, write);
1779 //Next fix up the modification order for actions that happened
1781 post_r_modification_order(read, write);
1782 //Make sure the promise's value matches the write's value
1783 ASSERT(promise->get_value() == write->get_value());
1786 promises->erase(promises->begin() + promise_index);
1787 threads_to_check.push_back(read->get_tid());
1794 //Check whether reading these writes has made threads unable to
1797 for(unsigned int i=0;i<threads_to_check.size();i++)
1798 mo_check_promises(threads_to_check[i], write);
1804 * Compute the set of promises that could potentially be satisfied by this
1805 * action. Note that the set computation actually appears in the Node, not in
1807 * @param curr The ModelAction that may satisfy promises
1809 void ModelChecker::compute_promises(ModelAction *curr)
1811 for (unsigned int i = 0; i < promises->size(); i++) {
1812 Promise *promise = (*promises)[i];
1813 const ModelAction *act = promise->get_action();
1814 if (!act->happens_before(curr) &&
1816 !act->could_synchronize_with(curr) &&
1817 !act->same_thread(curr) &&
1818 act->get_location() == curr->get_location() &&
1819 promise->get_value() == curr->get_value()) {
1820 curr->get_node()->set_promise(i);
1825 /** Checks promises in response to change in ClockVector Threads. */
1826 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1828 for (unsigned int i = 0; i < promises->size(); i++) {
1829 Promise *promise = (*promises)[i];
1830 const ModelAction *act = promise->get_action();
1831 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1832 merge_cv->synchronized_since(act)) {
1833 if (promise->increment_threads(tid)) {
1834 //Promise has failed
1835 failed_promise = true;
1842 /** Checks promises in response to addition to modification order for threads.
1844 * pthread is the thread that performed the read that created the promise
1846 * pread is the read that created the promise
1848 * pwrite is either the first write to same location as pread by
1849 * pthread that is sequenced after pread or the value read by the
1850 * first read to the same lcoation as pread by pthread that is
1851 * sequenced after pread..
1853 * 1. If tid=pthread, then we check what other threads are reachable
1854 * through the mode order starting with pwrite. Those threads cannot
1855 * perform a write that will resolve the promise due to modification
1856 * order constraints.
1858 * 2. If the tid is not pthread, we check whether pwrite can reach the
1859 * action write through the modification order. If so, that thread
1860 * cannot perform a future write that will resolve the promise due to
1861 * modificatin order constraints.
1863 * @parem tid The thread that either read from the model action
1864 * write, or actually did the model action write.
1866 * @parem write The ModelAction representing the relevant write.
1869 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1870 void * location = write->get_location();
1871 for (unsigned int i = 0; i < promises->size(); i++) {
1872 Promise *promise = (*promises)[i];
1873 const ModelAction *act = promise->get_action();
1875 //Is this promise on the same location?
1876 if ( act->get_location() != location )
1879 //same thread as the promise
1880 if ( act->get_tid()==tid ) {
1882 //do we have a pwrite for the promise, if not, set it
1883 if (promise->get_write() == NULL ) {
1884 promise->set_write(write);
1885 //The pwrite cannot happen before the promise
1886 if (write->happens_before(act) && (write != act)) {
1887 failed_promise = true;
1891 if (mo_graph->checkPromise(write, promise)) {
1892 failed_promise = true;
1897 //Don't do any lookups twice for the same thread
1898 if (promise->has_sync_thread(tid))
1901 if (mo_graph->checkReachable(promise->get_write(), write)) {
1902 if (promise->increment_threads(tid)) {
1903 failed_promise = true;
1911 * Compute the set of writes that may break the current pending release
1912 * sequence. This information is extracted from previou release sequence
1915 * @param curr The current ModelAction. Must be a release sequence fixup
1918 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1920 if (pending_rel_seqs->empty())
1923 struct release_seq *pending = pending_rel_seqs->back();
1924 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1925 const ModelAction *write = pending->writes[i];
1926 curr->get_node()->add_relseq_break(write);
1929 /* NULL means don't break the sequence; just synchronize */
1930 curr->get_node()->add_relseq_break(NULL);
1934 * Build up an initial set of all past writes that this 'read' action may read
1935 * from. This set is determined by the clock vector's "happens before"
1937 * @param curr is the current ModelAction that we are exploring; it must be a
1940 void ModelChecker::build_reads_from_past(ModelAction *curr)
1942 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1944 ASSERT(curr->is_read());
1946 ModelAction *last_seq_cst = NULL;
1948 /* Track whether this object has been initialized */
1949 bool initialized = false;
1951 if (curr->is_seqcst()) {
1952 last_seq_cst = get_last_seq_cst(curr);
1953 /* We have to at least see the last sequentially consistent write,
1954 so we are initialized. */
1955 if (last_seq_cst != NULL)
1959 /* Iterate over all threads */
1960 for (i = 0; i < thrd_lists->size(); i++) {
1961 /* Iterate over actions in thread, starting from most recent */
1962 action_list_t *list = &(*thrd_lists)[i];
1963 action_list_t::reverse_iterator rit;
1964 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1965 ModelAction *act = *rit;
1967 /* Only consider 'write' actions */
1968 if (!act->is_write() || act == curr)
1971 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1972 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1973 DEBUG("Adding action to may_read_from:\n");
1974 if (DBG_ENABLED()) {
1979 if (curr->get_sleep_flag() && ! curr->is_seqcst()) {
1980 if (sleep_can_read_from(curr, act))
1981 curr->get_node()->add_read_from(act);
1983 curr->get_node()->add_read_from(act);
1986 /* Include at most one act per-thread that "happens before" curr */
1987 if (act->happens_before(curr)) {
1995 /** @todo Need a more informative way of reporting errors. */
1996 printf("ERROR: may read from uninitialized atomic\n");
1999 if (DBG_ENABLED() || !initialized) {
2000 printf("Reached read action:\n");
2002 printf("Printing may_read_from\n");
2003 curr->get_node()->print_may_read_from();
2004 printf("End printing may_read_from\n");
2007 ASSERT(initialized);
2010 bool ModelChecker::sleep_can_read_from(ModelAction * curr, const ModelAction *write) {
2012 Node *prevnode=write->get_node()->get_parent();
2013 bool thread_sleep=prevnode->get_enabled_array()[id_to_int(curr->get_tid())]==THREAD_SLEEP_SET;
2014 if (write->is_release()&&thread_sleep)
2016 if (!write->is_rmw()) {
2019 if (write->get_reads_from()==NULL)
2021 write=write->get_reads_from();
2025 static void print_list(action_list_t *list)
2027 action_list_t::iterator it;
2029 printf("---------------------------------------------------------------------\n");
2031 unsigned int hash=0;
2033 for (it = list->begin(); it != list->end(); it++) {
2035 hash=hash^(hash<<3)^((*it)->hash());
2037 printf("HASH %u\n", hash);
2038 printf("---------------------------------------------------------------------\n");
2041 #if SUPPORT_MOD_ORDER_DUMP
2042 void ModelChecker::dumpGraph(char *filename) {
2044 sprintf(buffer, "%s.dot",filename);
2045 FILE *file=fopen(buffer, "w");
2046 fprintf(file, "digraph %s {\n",filename);
2047 mo_graph->dumpNodes(file);
2048 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
2050 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
2051 ModelAction *action=*it;
2052 if (action->is_read()) {
2053 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
2054 if (action->get_reads_from()!=NULL)
2055 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
2057 if (thread_array[action->get_tid()] != NULL) {
2058 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
2061 thread_array[action->get_tid()]=action;
2063 fprintf(file,"}\n");
2064 model_free(thread_array);
2069 void ModelChecker::print_summary()
2072 printf("Number of executions: %d\n", num_executions);
2073 printf("Number of feasible executions: %d\n", num_feasible_executions);
2074 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
2076 #if SUPPORT_MOD_ORDER_DUMP
2078 char buffername[100];
2079 sprintf(buffername, "exec%04u", num_executions);
2080 mo_graph->dumpGraphToFile(buffername);
2081 sprintf(buffername, "graph%04u", num_executions);
2082 dumpGraph(buffername);
2085 if (!isfinalfeasible())
2086 printf("INFEASIBLE EXECUTION!\n");
2087 print_list(action_trace);
2092 * Add a Thread to the system for the first time. Should only be called once
2094 * @param t The Thread to add
2096 void ModelChecker::add_thread(Thread *t)
2098 thread_map->put(id_to_int(t->get_id()), t);
2099 scheduler->add_thread(t);
2103 * Removes a thread from the scheduler.
2104 * @param the thread to remove.
2106 void ModelChecker::remove_thread(Thread *t)
2108 scheduler->remove_thread(t);
2112 * @brief Get a Thread reference by its ID
2113 * @param tid The Thread's ID
2114 * @return A Thread reference
2116 Thread * ModelChecker::get_thread(thread_id_t tid) const
2118 return thread_map->get(id_to_int(tid));
2122 * @brief Get a reference to the Thread in which a ModelAction was executed
2123 * @param act The ModelAction
2124 * @return A Thread reference
2126 Thread * ModelChecker::get_thread(ModelAction *act) const
2128 return get_thread(act->get_tid());
2132 * Switch from a user-context to the "master thread" context (a.k.a. system
2133 * context). This switch is made with the intention of exploring a particular
2134 * model-checking action (described by a ModelAction object). Must be called
2135 * from a user-thread context.
2137 * @param act The current action that will be explored. May be NULL only if
2138 * trace is exiting via an assertion (see ModelChecker::set_assert and
2139 * ModelChecker::has_asserted).
2140 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
2142 int ModelChecker::switch_to_master(ModelAction *act)
2145 Thread *old = thread_current();
2146 set_current_action(act);
2147 old->set_state(THREAD_READY);
2148 return Thread::swap(old, &system_context);
2152 * Takes the next step in the execution, if possible.
2153 * @return Returns true (success) if a step was taken and false otherwise.
2155 bool ModelChecker::take_step() {
2159 Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
2161 if (curr->get_state() == THREAD_READY) {
2162 ASSERT(priv->current_action);
2164 priv->nextThread = check_current_action(priv->current_action);
2165 priv->current_action = NULL;
2167 if (curr->is_blocked() || curr->is_complete())
2168 scheduler->remove_thread(curr);
2173 Thread *next = scheduler->next_thread(priv->nextThread);
2175 /* Infeasible -> don't take any more steps */
2179 if (params.bound != 0) {
2180 if (priv->used_sequence_numbers > params.bound) {
2185 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
2186 next ? id_to_int(next->get_id()) : -1);
2189 * Launch end-of-execution release sequence fixups only when there are:
2191 * (1) no more user threads to run (or when execution replay chooses
2192 * the 'model_thread')
2193 * (2) pending release sequences
2194 * (3) pending assertions (i.e., data races)
2195 * (4) no pending promises
2197 if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
2198 isfinalfeasible() && !unrealizedraces.empty()) {
2199 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
2200 pending_rel_seqs->size());
2201 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2202 std::memory_order_seq_cst, NULL, VALUE_NONE,
2204 set_current_action(fixup);
2208 /* next == NULL -> don't take any more steps */
2212 next->set_state(THREAD_RUNNING);
2214 if (next->get_pending() != NULL) {
2215 /* restart a pending action */
2216 set_current_action(next->get_pending());
2217 next->set_pending(NULL);
2218 next->set_state(THREAD_READY);
2222 /* Return false only if swap fails with an error */
2223 return (Thread::swap(&system_context, next) == 0);
2226 /** Runs the current execution until threre are no more steps to take. */
2227 void ModelChecker::finish_execution() {
2230 while (take_step());