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 ((!curr->is_rmwr())&&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 /* Make sure this thread can be enabled here. */
387 if (i >= node->get_num_threads())
390 /* Don't backtrack into a point where the thread is disabled or sleeping. */
391 if (node->get_enabled_array()[i]!=THREAD_ENABLED)
394 /* Check if this has been explored already */
395 if (node->has_been_explored(tid))
398 /* See if fairness allows */
399 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
401 for(int t=0;t<node->get_num_threads();t++) {
402 thread_id_t tother=int_to_id(t);
403 if (node->is_enabled(tother) && node->has_priority(tother)) {
411 /* Cache the latest backtracking point */
412 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
413 priv->next_backtrack = prev;
415 /* If this is a new backtracking point, mark the tree */
416 if (!node->set_backtrack(tid))
418 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
419 id_to_int(prev->get_tid()),
420 id_to_int(t->get_id()));
429 * Returns last backtracking point. The model checker will explore a different
430 * path for this point in the next execution.
431 * @return The ModelAction at which the next execution should diverge.
433 ModelAction * ModelChecker::get_next_backtrack()
435 ModelAction *next = priv->next_backtrack;
436 priv->next_backtrack = NULL;
441 * Processes a read or rmw model action.
442 * @param curr is the read model action to process.
443 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
444 * @return True if processing this read updates the mo_graph.
446 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
448 uint64_t value = VALUE_NONE;
449 bool updated = false;
451 const ModelAction *reads_from = curr->get_node()->get_read_from();
452 if (reads_from != NULL) {
453 mo_graph->startChanges();
455 value = reads_from->get_value();
456 bool r_status = false;
458 if (!second_part_of_rmw) {
459 check_recency(curr, reads_from);
460 r_status = r_modification_order(curr, reads_from);
464 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
465 mo_graph->rollbackChanges();
466 too_many_reads = false;
470 curr->read_from(reads_from);
471 mo_graph->commitChanges();
472 mo_check_promises(curr->get_tid(), reads_from);
475 } else if (!second_part_of_rmw) {
476 /* Read from future value */
477 value = curr->get_node()->get_future_value();
478 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
479 curr->read_from(NULL);
480 Promise *valuepromise = new Promise(curr, value, expiration);
481 promises->push_back(valuepromise);
483 get_thread(curr)->set_return_value(value);
489 * Processes a lock, trylock, or unlock model action. @param curr is
490 * the read model action to process.
492 * The try lock operation checks whether the lock is taken. If not,
493 * it falls to the normal lock operation case. If so, it returns
496 * The lock operation has already been checked that it is enabled, so
497 * it just grabs the lock and synchronizes with the previous unlock.
499 * The unlock operation has to re-enable all of the threads that are
500 * waiting on the lock.
502 * @return True if synchronization was updated; false otherwise
504 bool ModelChecker::process_mutex(ModelAction *curr) {
505 std::mutex *mutex=NULL;
506 struct std::mutex_state *state=NULL;
508 if (curr->is_trylock() || curr->is_lock() || curr->is_unlock()) {
509 mutex = (std::mutex *)curr->get_location();
510 state = mutex->get_state();
511 } else if(curr->is_wait()) {
512 mutex = (std::mutex *)curr->get_value();
513 state = mutex->get_state();
516 switch (curr->get_type()) {
517 case ATOMIC_TRYLOCK: {
518 bool success = !state->islocked;
519 curr->set_try_lock(success);
521 get_thread(curr)->set_return_value(0);
524 get_thread(curr)->set_return_value(1);
526 //otherwise fall into the lock case
528 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
529 printf("Lock access before initialization\n");
532 state->islocked = true;
533 ModelAction *unlock = get_last_unlock(curr);
534 //synchronize with the previous unlock statement
535 if (unlock != NULL) {
536 curr->synchronize_with(unlock);
541 case ATOMIC_UNLOCK: {
543 state->islocked = false;
544 //wake up the other threads
545 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
546 //activate all the waiting threads
547 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
548 scheduler->wake(get_thread(*rit));
555 state->islocked = false;
556 //wake up the other threads
557 action_list_t *waiters = lock_waiters_map->get_safe_ptr((void *) curr->get_value());
558 //activate all the waiting threads
559 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
560 scheduler->wake(get_thread(*rit));
563 //check whether we should go to sleep or not...simulate spurious failures
564 if (curr->get_node()->get_misc()==0) {
565 condvar_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
567 scheduler->sleep(get_current_thread());
571 case ATOMIC_NOTIFY_ALL: {
572 action_list_t *waiters = condvar_waiters_map->get_safe_ptr(curr->get_location());
573 //activate all the waiting threads
574 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
575 scheduler->wake(get_thread(*rit));
580 case ATOMIC_NOTIFY_ONE: {
581 action_list_t *waiters = condvar_waiters_map->get_safe_ptr(curr->get_location());
582 int wakeupthread=curr->get_node()->get_misc();
583 action_list_t::iterator it = waiters->begin();
584 advance(it, wakeupthread);
585 scheduler->wake(get_thread(*it));
597 * Process a write ModelAction
598 * @param curr The ModelAction to process
599 * @return True if the mo_graph was updated or promises were resolved
601 bool ModelChecker::process_write(ModelAction *curr)
603 bool updated_mod_order = w_modification_order(curr);
604 bool updated_promises = resolve_promises(curr);
606 if (promises->size() == 0) {
607 for (unsigned int i = 0; i < futurevalues->size(); i++) {
608 struct PendingFutureValue pfv = (*futurevalues)[i];
609 //Do more ambitious checks now that mo is more complete
610 if (mo_may_allow(pfv.writer, pfv.act)&&
611 pfv.act->get_node()->add_future_value(pfv.writer->get_value(), pfv.writer->get_seq_number()+params.maxfuturedelay) &&
612 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
613 priv->next_backtrack = pfv.act;
615 futurevalues->resize(0);
618 mo_graph->commitChanges();
619 mo_check_promises(curr->get_tid(), curr);
621 get_thread(curr)->set_return_value(VALUE_NONE);
622 return updated_mod_order || updated_promises;
626 * @brief Process the current action for thread-related activity
628 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
629 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
630 * synchronization, etc. This function is a no-op for non-THREAD actions
631 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
633 * @param curr The current action
634 * @return True if synchronization was updated or a thread completed
636 bool ModelChecker::process_thread_action(ModelAction *curr)
638 bool updated = false;
640 switch (curr->get_type()) {
641 case THREAD_CREATE: {
642 Thread *th = (Thread *)curr->get_location();
643 th->set_creation(curr);
647 Thread *blocking = (Thread *)curr->get_location();
648 ModelAction *act = get_last_action(blocking->get_id());
649 curr->synchronize_with(act);
650 updated = true; /* trigger rel-seq checks */
653 case THREAD_FINISH: {
654 Thread *th = get_thread(curr);
655 while (!th->wait_list_empty()) {
656 ModelAction *act = th->pop_wait_list();
657 scheduler->wake(get_thread(act));
660 updated = true; /* trigger rel-seq checks */
664 check_promises(curr->get_tid(), NULL, curr->get_cv());
675 * @brief Process the current action for release sequence fixup activity
677 * Performs model-checker release sequence fixups for the current action,
678 * forcing a single pending release sequence to break (with a given, potential
679 * "loose" write) or to complete (i.e., synchronize). If a pending release
680 * sequence forms a complete release sequence, then we must perform the fixup
681 * synchronization, mo_graph additions, etc.
683 * @param curr The current action; must be a release sequence fixup action
684 * @param work_queue The work queue to which to add work items as they are
687 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
689 const ModelAction *write = curr->get_node()->get_relseq_break();
690 struct release_seq *sequence = pending_rel_seqs->back();
691 pending_rel_seqs->pop_back();
693 ModelAction *acquire = sequence->acquire;
694 const ModelAction *rf = sequence->rf;
695 const ModelAction *release = sequence->release;
699 ASSERT(release->same_thread(rf));
703 * @todo Forcing a synchronization requires that we set
704 * modification order constraints. For instance, we can't allow
705 * a fixup sequence in which two separate read-acquire
706 * operations read from the same sequence, where the first one
707 * synchronizes and the other doesn't. Essentially, we can't
708 * allow any writes to insert themselves between 'release' and
712 /* Must synchronize */
713 if (!acquire->synchronize_with(release)) {
714 set_bad_synchronization();
717 /* Re-check all pending release sequences */
718 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
719 /* Re-check act for mo_graph edges */
720 work_queue->push_back(MOEdgeWorkEntry(acquire));
722 /* propagate synchronization to later actions */
723 action_list_t::reverse_iterator rit = action_trace->rbegin();
724 for (; (*rit) != acquire; rit++) {
725 ModelAction *propagate = *rit;
726 if (acquire->happens_before(propagate)) {
727 propagate->synchronize_with(acquire);
728 /* Re-check 'propagate' for mo_graph edges */
729 work_queue->push_back(MOEdgeWorkEntry(propagate));
733 /* Break release sequence with new edges:
734 * release --mo--> write --mo--> rf */
735 mo_graph->addEdge(release, write);
736 mo_graph->addEdge(write, rf);
739 /* See if we have realized a data race */
740 if (checkDataRaces())
745 * Initialize the current action by performing one or more of the following
746 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
747 * in the NodeStack, manipulating backtracking sets, allocating and
748 * initializing clock vectors, and computing the promises to fulfill.
750 * @param curr The current action, as passed from the user context; may be
751 * freed/invalidated after the execution of this function, with a different
752 * action "returned" its place (pass-by-reference)
753 * @return True if curr is a newly-explored action; false otherwise
755 bool ModelChecker::initialize_curr_action(ModelAction **curr)
757 ModelAction *newcurr;
759 if ((*curr)->is_rmwc() || (*curr)->is_rmw()) {
760 newcurr = process_rmw(*curr);
763 if (newcurr->is_rmw())
764 compute_promises(newcurr);
770 (*curr)->set_seq_number(get_next_seq_num());
772 newcurr = node_stack->explore_action(*curr, scheduler->get_enabled());
774 /* First restore type and order in case of RMW operation */
775 if ((*curr)->is_rmwr())
776 newcurr->copy_typeandorder(*curr);
778 ASSERT((*curr)->get_location() == newcurr->get_location());
779 newcurr->copy_from_new(*curr);
781 /* Discard duplicate ModelAction; use action from NodeStack */
784 /* Always compute new clock vector */
785 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
788 return false; /* Action was explored previously */
792 /* Always compute new clock vector */
793 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
795 * Perform one-time actions when pushing new ModelAction onto
798 if (newcurr->is_write())
799 compute_promises(newcurr);
800 else if (newcurr->is_relseq_fixup())
801 compute_relseq_breakwrites(newcurr);
802 else if (newcurr->is_wait())
803 newcurr->get_node()->set_misc_max(2);
804 else if (newcurr->is_notify_one()) {
805 newcurr->get_node()->set_misc_max(condvar_waiters_map->get_safe_ptr(newcurr->get_location())->size());
807 return true; /* This was a new ModelAction */
812 * @brief Check whether a model action is enabled.
814 * Checks whether a lock or join operation would be successful (i.e., is the
815 * lock already locked, or is the joined thread already complete). If not, put
816 * the action in a waiter list.
818 * @param curr is the ModelAction to check whether it is enabled.
819 * @return a bool that indicates whether the action is enabled.
821 bool ModelChecker::check_action_enabled(ModelAction *curr) {
822 if (curr->is_lock()) {
823 std::mutex * lock = (std::mutex *)curr->get_location();
824 struct std::mutex_state * state = lock->get_state();
825 if (state->islocked) {
826 //Stick the action in the appropriate waiting queue
827 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
830 } else if (curr->get_type() == THREAD_JOIN) {
831 Thread *blocking = (Thread *)curr->get_location();
832 if (!blocking->is_complete()) {
833 blocking->push_wait_list(curr);
842 * This is the heart of the model checker routine. It performs model-checking
843 * actions corresponding to a given "current action." Among other processes, it
844 * calculates reads-from relationships, updates synchronization clock vectors,
845 * forms a memory_order constraints graph, and handles replay/backtrack
846 * execution when running permutations of previously-observed executions.
848 * @param curr The current action to process
849 * @return The next Thread that must be executed. May be NULL if ModelChecker
850 * makes no choice (e.g., according to replay execution, combining RMW actions,
853 Thread * ModelChecker::check_current_action(ModelAction *curr)
856 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
858 if (!check_action_enabled(curr)) {
859 /* Make the execution look like we chose to run this action
860 * much later, when a lock/join can succeed */
861 get_current_thread()->set_pending(curr);
862 scheduler->sleep(get_current_thread());
863 return get_next_thread(NULL);
866 bool newly_explored = initialize_curr_action(&curr);
868 wake_up_sleeping_actions(curr);
870 /* Add the action to lists before any other model-checking tasks */
871 if (!second_part_of_rmw)
872 add_action_to_lists(curr);
874 /* Build may_read_from set for newly-created actions */
875 if (newly_explored && curr->is_read())
876 build_reads_from_past(curr);
878 /* Initialize work_queue with the "current action" work */
879 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
880 while (!work_queue.empty()) {
881 WorkQueueEntry work = work_queue.front();
882 work_queue.pop_front();
885 case WORK_CHECK_CURR_ACTION: {
886 ModelAction *act = work.action;
887 bool update = false; /* update this location's release seq's */
888 bool update_all = false; /* update all release seq's */
890 if (process_thread_action(curr))
893 if (act->is_read() && process_read(act, second_part_of_rmw))
896 if (act->is_write() && process_write(act))
899 if (act->is_mutex_op() && process_mutex(act))
902 if (act->is_relseq_fixup())
903 process_relseq_fixup(curr, &work_queue);
906 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
908 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
911 case WORK_CHECK_RELEASE_SEQ:
912 resolve_release_sequences(work.location, &work_queue);
914 case WORK_CHECK_MO_EDGES: {
915 /** @todo Complete verification of work_queue */
916 ModelAction *act = work.action;
917 bool updated = false;
919 if (act->is_read()) {
920 const ModelAction *rf = act->get_reads_from();
921 if (rf != NULL && r_modification_order(act, rf))
924 if (act->is_write()) {
925 if (w_modification_order(act))
928 mo_graph->commitChanges();
931 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
940 check_curr_backtracking(curr);
941 set_backtracking(curr);
942 return get_next_thread(curr);
945 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
946 Node *currnode = curr->get_node();
947 Node *parnode = currnode->get_parent();
949 if ((!parnode->backtrack_empty() ||
950 !currnode->misc_empty() ||
951 !currnode->read_from_empty() ||
952 !currnode->future_value_empty() ||
953 !currnode->promise_empty() ||
954 !currnode->relseq_break_empty())
955 && (!priv->next_backtrack ||
956 *curr > *priv->next_backtrack)) {
957 priv->next_backtrack = curr;
961 bool ModelChecker::promises_expired() {
962 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
963 Promise *promise = (*promises)[promise_index];
964 if (promise->get_expiration()<priv->used_sequence_numbers) {
971 /** @return whether the current partial trace must be a prefix of a
973 bool ModelChecker::isfeasibleprefix() {
974 return promises->size() == 0 && pending_rel_seqs->size() == 0;
977 /** @return whether the current partial trace is feasible. */
978 bool ModelChecker::isfeasible() {
979 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
980 DEBUG("Infeasible: RMW violation\n");
982 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
985 /** @return whether the current partial trace is feasible other than
986 * multiple RMW reading from the same store. */
987 bool ModelChecker::isfeasibleotherthanRMW() {
989 if (mo_graph->checkForCycles())
990 DEBUG("Infeasible: modification order cycles\n");
992 DEBUG("Infeasible: failed promise\n");
994 DEBUG("Infeasible: too many reads\n");
995 if (bad_synchronization)
996 DEBUG("Infeasible: bad synchronization ordering\n");
997 if (promises_expired())
998 DEBUG("Infeasible: promises expired\n");
1000 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
1003 /** Returns whether the current completed trace is feasible. */
1004 bool ModelChecker::isfinalfeasible() {
1005 if (DBG_ENABLED() && promises->size() != 0)
1006 DEBUG("Infeasible: unrevolved promises\n");
1008 return isfeasible() && promises->size() == 0;
1011 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
1012 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
1013 ModelAction *lastread = get_last_action(act->get_tid());
1014 lastread->process_rmw(act);
1015 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
1016 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
1017 mo_graph->commitChanges();
1023 * Checks whether a thread has read from the same write for too many times
1024 * without seeing the effects of a later write.
1027 * 1) there must a different write that we could read from that would satisfy the modification order,
1028 * 2) we must have read from the same value in excess of maxreads times, and
1029 * 3) that other write must have been in the reads_from set for maxreads times.
1031 * If so, we decide that the execution is no longer feasible.
1033 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
1034 if (params.maxreads != 0) {
1036 if (curr->get_node()->get_read_from_size() <= 1)
1038 //Must make sure that execution is currently feasible... We could
1039 //accidentally clear by rolling back
1042 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1043 int tid = id_to_int(curr->get_tid());
1046 if ((int)thrd_lists->size() <= tid)
1048 action_list_t *list = &(*thrd_lists)[tid];
1050 action_list_t::reverse_iterator rit = list->rbegin();
1051 /* Skip past curr */
1052 for (; (*rit) != curr; rit++)
1054 /* go past curr now */
1057 action_list_t::reverse_iterator ritcopy = rit;
1058 //See if we have enough reads from the same value
1060 for (; count < params.maxreads; rit++,count++) {
1061 if (rit==list->rend())
1063 ModelAction *act = *rit;
1064 if (!act->is_read())
1067 if (act->get_reads_from() != rf)
1069 if (act->get_node()->get_read_from_size() <= 1)
1072 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
1074 const ModelAction * write = curr->get_node()->get_read_from_at(i);
1076 //Need a different write
1080 /* Test to see whether this is a feasible write to read from*/
1081 mo_graph->startChanges();
1082 r_modification_order(curr, write);
1083 bool feasiblereadfrom = isfeasible();
1084 mo_graph->rollbackChanges();
1086 if (!feasiblereadfrom)
1090 bool feasiblewrite = true;
1091 //new we need to see if this write works for everyone
1093 for (int loop = count; loop>0; loop--,rit++) {
1094 ModelAction *act=*rit;
1095 bool foundvalue = false;
1096 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
1097 if (act->get_node()->get_read_from_at(i)==write) {
1103 feasiblewrite = false;
1107 if (feasiblewrite) {
1108 too_many_reads = true;
1116 * Updates the mo_graph with the constraints imposed from the current
1119 * Basic idea is the following: Go through each other thread and find
1120 * the lastest action that happened before our read. Two cases:
1122 * (1) The action is a write => that write must either occur before
1123 * the write we read from or be the write we read from.
1125 * (2) The action is a read => the write that that action read from
1126 * must occur before the write we read from or be the same write.
1128 * @param curr The current action. Must be a read.
1129 * @param rf The action that curr reads from. Must be a write.
1130 * @return True if modification order edges were added; false otherwise
1132 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
1134 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1137 ASSERT(curr->is_read());
1139 /* Iterate over all threads */
1140 for (i = 0; i < thrd_lists->size(); i++) {
1141 /* Iterate over actions in thread, starting from most recent */
1142 action_list_t *list = &(*thrd_lists)[i];
1143 action_list_t::reverse_iterator rit;
1144 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1145 ModelAction *act = *rit;
1148 * Include at most one act per-thread that "happens
1149 * before" curr. Don't consider reflexively.
1151 if (act->happens_before(curr) && act != curr) {
1152 if (act->is_write()) {
1154 mo_graph->addEdge(act, rf);
1158 const ModelAction *prevreadfrom = act->get_reads_from();
1159 //if the previous read is unresolved, keep going...
1160 if (prevreadfrom == NULL)
1163 if (rf != prevreadfrom) {
1164 mo_graph->addEdge(prevreadfrom, rf);
1176 /** This method fixes up the modification order when we resolve a
1177 * promises. The basic problem is that actions that occur after the
1178 * read curr could not property add items to the modification order
1181 * So for each thread, we find the earliest item that happens after
1182 * the read curr. This is the item we have to fix up with additional
1183 * constraints. If that action is write, we add a MO edge between
1184 * the Action rf and that action. If the action is a read, we add a
1185 * MO edge between the Action rf, and whatever the read accessed.
1187 * @param curr is the read ModelAction that we are fixing up MO edges for.
1188 * @param rf is the write ModelAction that curr reads from.
1191 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1193 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1195 ASSERT(curr->is_read());
1197 /* Iterate over all threads */
1198 for (i = 0; i < thrd_lists->size(); i++) {
1199 /* Iterate over actions in thread, starting from most recent */
1200 action_list_t *list = &(*thrd_lists)[i];
1201 action_list_t::reverse_iterator rit;
1202 ModelAction *lastact = NULL;
1204 /* Find last action that happens after curr that is either not curr or a rmw */
1205 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1206 ModelAction *act = *rit;
1207 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1213 /* Include at most one act per-thread that "happens before" curr */
1214 if (lastact != NULL) {
1215 if (lastact==curr) {
1216 //Case 1: The resolved read is a RMW, and we need to make sure
1217 //that the write portion of the RMW mod order after rf
1219 mo_graph->addEdge(rf, lastact);
1220 } else if (lastact->is_read()) {
1221 //Case 2: The resolved read is a normal read and the next
1222 //operation is a read, and we need to make sure the value read
1223 //is mod ordered after rf
1225 const ModelAction *postreadfrom = lastact->get_reads_from();
1226 if (postreadfrom != NULL&&rf != postreadfrom)
1227 mo_graph->addEdge(rf, postreadfrom);
1229 //Case 3: The resolved read is a normal read and the next
1230 //operation is a write, and we need to make sure that the
1231 //write is mod ordered after rf
1233 mo_graph->addEdge(rf, lastact);
1241 * Updates the mo_graph with the constraints imposed from the current write.
1243 * Basic idea is the following: Go through each other thread and find
1244 * the lastest action that happened before our write. Two cases:
1246 * (1) The action is a write => that write must occur before
1249 * (2) The action is a read => the write that that action read from
1250 * must occur before the current write.
1252 * This method also handles two other issues:
1254 * (I) Sequential Consistency: Making sure that if the current write is
1255 * seq_cst, that it occurs after the previous seq_cst write.
1257 * (II) Sending the write back to non-synchronizing reads.
1259 * @param curr The current action. Must be a write.
1260 * @return True if modification order edges were added; false otherwise
1262 bool ModelChecker::w_modification_order(ModelAction *curr)
1264 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1267 ASSERT(curr->is_write());
1269 if (curr->is_seqcst()) {
1270 /* We have to at least see the last sequentially consistent write,
1271 so we are initialized. */
1272 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1273 if (last_seq_cst != NULL) {
1274 mo_graph->addEdge(last_seq_cst, curr);
1279 /* Iterate over all threads */
1280 for (i = 0; i < thrd_lists->size(); i++) {
1281 /* Iterate over actions in thread, starting from most recent */
1282 action_list_t *list = &(*thrd_lists)[i];
1283 action_list_t::reverse_iterator rit;
1284 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1285 ModelAction *act = *rit;
1288 * 1) If RMW and it actually read from something, then we
1289 * already have all relevant edges, so just skip to next
1292 * 2) If RMW and it didn't read from anything, we should
1293 * whatever edge we can get to speed up convergence.
1295 * 3) If normal write, we need to look at earlier actions, so
1296 * continue processing list.
1298 if (curr->is_rmw()) {
1299 if (curr->get_reads_from()!=NULL)
1308 * Include at most one act per-thread that "happens
1311 if (act->happens_before(curr)) {
1313 * Note: if act is RMW, just add edge:
1315 * The following edge should be handled elsewhere:
1316 * readfrom(act) --mo--> act
1318 if (act->is_write())
1319 mo_graph->addEdge(act, curr);
1320 else if (act->is_read()) {
1321 //if previous read accessed a null, just keep going
1322 if (act->get_reads_from() == NULL)
1324 mo_graph->addEdge(act->get_reads_from(), curr);
1328 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1329 !act->same_thread(curr)) {
1330 /* We have an action that:
1331 (1) did not happen before us
1332 (2) is a read and we are a write
1333 (3) cannot synchronize with us
1334 (4) is in a different thread
1336 that read could potentially read from our write. Note that
1337 these checks are overly conservative at this point, we'll
1338 do more checks before actually removing the
1342 if (thin_air_constraint_may_allow(curr, act)) {
1344 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1345 struct PendingFutureValue pfv = {curr,act};
1346 futurevalues->push_back(pfv);
1356 /** Arbitrary reads from the future are not allowed. Section 29.3
1357 * part 9 places some constraints. This method checks one result of constraint
1358 * constraint. Others require compiler support. */
1359 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1360 if (!writer->is_rmw())
1363 if (!reader->is_rmw())
1366 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1367 if (search == reader)
1369 if (search->get_tid() == reader->get_tid() &&
1370 search->happens_before(reader))
1378 * Arbitrary reads from the future are not allowed. Section 29.3 part 9 places
1379 * some constraints. This method checks one the following constraint (others
1380 * require compiler support):
1382 * If X --hb-> Y --mo-> Z, then X should not read from Z.
1384 bool ModelChecker::mo_may_allow(const ModelAction *writer, const ModelAction *reader)
1386 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(reader->get_location());
1389 /* Iterate over all threads */
1390 for (i = 0; i < thrd_lists->size(); i++) {
1391 ModelAction *write_after_read = NULL;
1393 /* Iterate over actions in thread, starting from most recent */
1394 action_list_t *list = &(*thrd_lists)[i];
1395 action_list_t::reverse_iterator rit;
1396 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1397 ModelAction *act = *rit;
1399 if (!reader->happens_before(act))
1401 else if (act->is_write())
1402 write_after_read = act;
1405 if (write_after_read && mo_graph->checkReachable(write_after_read, writer))
1413 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1414 * The ModelAction under consideration is expected to be taking part in
1415 * release/acquire synchronization as an object of the "reads from" relation.
1416 * Note that this can only provide release sequence support for RMW chains
1417 * which do not read from the future, as those actions cannot be traced until
1418 * their "promise" is fulfilled. Similarly, we may not even establish the
1419 * presence of a release sequence with certainty, as some modification order
1420 * constraints may be decided further in the future. Thus, this function
1421 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1422 * and a boolean representing certainty.
1424 * @param rf The action that might be part of a release sequence. Must be a
1426 * @param release_heads A pass-by-reference style return parameter. After
1427 * execution of this function, release_heads will contain the heads of all the
1428 * relevant release sequences, if any exists with certainty
1429 * @param pending A pass-by-reference style return parameter which is only used
1430 * when returning false (i.e., uncertain). Returns most information regarding
1431 * an uncertain release sequence, including any write operations that might
1432 * break the sequence.
1433 * @return true, if the ModelChecker is certain that release_heads is complete;
1436 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1437 rel_heads_list_t *release_heads,
1438 struct release_seq *pending) const
1440 /* Only check for release sequences if there are no cycles */
1441 if (mo_graph->checkForCycles())
1445 ASSERT(rf->is_write());
1447 if (rf->is_release())
1448 release_heads->push_back(rf);
1450 break; /* End of RMW chain */
1452 /** @todo Need to be smarter here... In the linux lock
1453 * example, this will run to the beginning of the program for
1455 /** @todo The way to be smarter here is to keep going until 1
1456 * thread has a release preceded by an acquire and you've seen
1459 /* acq_rel RMW is a sufficient stopping condition */
1460 if (rf->is_acquire() && rf->is_release())
1461 return true; /* complete */
1463 rf = rf->get_reads_from();
1466 /* read from future: need to settle this later */
1468 return false; /* incomplete */
1471 if (rf->is_release())
1472 return true; /* complete */
1474 /* else relaxed write; check modification order for contiguous subsequence
1475 * -> rf must be same thread as release */
1476 int tid = id_to_int(rf->get_tid());
1477 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1478 action_list_t *list = &(*thrd_lists)[tid];
1479 action_list_t::const_reverse_iterator rit;
1481 /* Find rf in the thread list */
1482 rit = std::find(list->rbegin(), list->rend(), rf);
1483 ASSERT(rit != list->rend());
1485 /* Find the last write/release */
1486 for (; rit != list->rend(); rit++)
1487 if ((*rit)->is_release())
1489 if (rit == list->rend()) {
1490 /* No write-release in this thread */
1491 return true; /* complete */
1493 ModelAction *release = *rit;
1495 ASSERT(rf->same_thread(release));
1497 pending->writes.clear();
1499 bool certain = true;
1500 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1501 if (id_to_int(rf->get_tid()) == (int)i)
1503 list = &(*thrd_lists)[i];
1505 /* Can we ensure no future writes from this thread may break
1506 * the release seq? */
1507 bool future_ordered = false;
1509 ModelAction *last = get_last_action(int_to_id(i));
1510 Thread *th = get_thread(int_to_id(i));
1511 if ((last && rf->happens_before(last)) ||
1512 !scheduler->is_enabled(th) ||
1514 future_ordered = true;
1516 ASSERT(!th->is_model_thread() || future_ordered);
1518 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1519 const ModelAction *act = *rit;
1520 /* Reach synchronization -> this thread is complete */
1521 if (act->happens_before(release))
1523 if (rf->happens_before(act)) {
1524 future_ordered = true;
1528 /* Only non-RMW writes can break release sequences */
1529 if (!act->is_write() || act->is_rmw())
1532 /* Check modification order */
1533 if (mo_graph->checkReachable(rf, act)) {
1534 /* rf --mo--> act */
1535 future_ordered = true;
1538 if (mo_graph->checkReachable(act, release))
1539 /* act --mo--> release */
1541 if (mo_graph->checkReachable(release, act) &&
1542 mo_graph->checkReachable(act, rf)) {
1543 /* release --mo-> act --mo--> rf */
1544 return true; /* complete */
1546 /* act may break release sequence */
1547 pending->writes.push_back(act);
1550 if (!future_ordered)
1551 certain = false; /* This thread is uncertain */
1555 release_heads->push_back(release);
1556 pending->writes.clear();
1558 pending->release = release;
1565 * A public interface for getting the release sequence head(s) with which a
1566 * given ModelAction must synchronize. This function only returns a non-empty
1567 * result when it can locate a release sequence head with certainty. Otherwise,
1568 * it may mark the internal state of the ModelChecker so that it will handle
1569 * the release sequence at a later time, causing @a act to update its
1570 * synchronization at some later point in execution.
1571 * @param act The 'acquire' action that may read from a release sequence
1572 * @param release_heads A pass-by-reference return parameter. Will be filled
1573 * with the head(s) of the release sequence(s), if they exists with certainty.
1574 * @see ModelChecker::release_seq_heads
1576 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1578 const ModelAction *rf = act->get_reads_from();
1579 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1580 sequence->acquire = act;
1582 if (!release_seq_heads(rf, release_heads, sequence)) {
1583 /* add act to 'lazy checking' list */
1584 pending_rel_seqs->push_back(sequence);
1586 snapshot_free(sequence);
1591 * Attempt to resolve all stashed operations that might synchronize with a
1592 * release sequence for a given location. This implements the "lazy" portion of
1593 * determining whether or not a release sequence was contiguous, since not all
1594 * modification order information is present at the time an action occurs.
1596 * @param location The location/object that should be checked for release
1597 * sequence resolutions. A NULL value means to check all locations.
1598 * @param work_queue The work queue to which to add work items as they are
1600 * @return True if any updates occurred (new synchronization, new mo_graph
1603 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1605 bool updated = false;
1606 std::vector< struct release_seq *, SnapshotAlloc<struct release_seq *> >::iterator it = pending_rel_seqs->begin();
1607 while (it != pending_rel_seqs->end()) {
1608 struct release_seq *pending = *it;
1609 ModelAction *act = pending->acquire;
1611 /* Only resolve sequences on the given location, if provided */
1612 if (location && act->get_location() != location) {
1617 const ModelAction *rf = act->get_reads_from();
1618 rel_heads_list_t release_heads;
1620 complete = release_seq_heads(rf, &release_heads, pending);
1621 for (unsigned int i = 0; i < release_heads.size(); i++) {
1622 if (!act->has_synchronized_with(release_heads[i])) {
1623 if (act->synchronize_with(release_heads[i]))
1626 set_bad_synchronization();
1631 /* Re-check all pending release sequences */
1632 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1633 /* Re-check act for mo_graph edges */
1634 work_queue->push_back(MOEdgeWorkEntry(act));
1636 /* propagate synchronization to later actions */
1637 action_list_t::reverse_iterator rit = action_trace->rbegin();
1638 for (; (*rit) != act; rit++) {
1639 ModelAction *propagate = *rit;
1640 if (act->happens_before(propagate)) {
1641 propagate->synchronize_with(act);
1642 /* Re-check 'propagate' for mo_graph edges */
1643 work_queue->push_back(MOEdgeWorkEntry(propagate));
1648 it = pending_rel_seqs->erase(it);
1649 snapshot_free(pending);
1655 // If we resolved promises or data races, see if we have realized a data race.
1656 if (checkDataRaces()) {
1664 * Performs various bookkeeping operations for the current ModelAction. For
1665 * instance, adds action to the per-object, per-thread action vector and to the
1666 * action trace list of all thread actions.
1668 * @param act is the ModelAction to add.
1670 void ModelChecker::add_action_to_lists(ModelAction *act)
1672 int tid = id_to_int(act->get_tid());
1673 action_trace->push_back(act);
1675 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1677 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1678 if (tid >= (int)vec->size())
1679 vec->resize(priv->next_thread_id);
1680 (*vec)[tid].push_back(act);
1682 if ((int)thrd_last_action->size() <= tid)
1683 thrd_last_action->resize(get_num_threads());
1684 (*thrd_last_action)[tid] = act;
1686 if (act->is_wait()) {
1687 void *mutex_loc=(void *) act->get_value();
1688 obj_map->get_safe_ptr(mutex_loc)->push_back(act);
1690 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(mutex_loc);
1691 if (tid >= (int)vec->size())
1692 vec->resize(priv->next_thread_id);
1693 (*vec)[tid].push_back(act);
1695 if ((int)thrd_last_action->size() <= tid)
1696 thrd_last_action->resize(get_num_threads());
1697 (*thrd_last_action)[tid] = act;
1702 * @brief Get the last action performed by a particular Thread
1703 * @param tid The thread ID of the Thread in question
1704 * @return The last action in the thread
1706 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1708 int threadid = id_to_int(tid);
1709 if (threadid < (int)thrd_last_action->size())
1710 return (*thrd_last_action)[id_to_int(tid)];
1716 * Gets the last memory_order_seq_cst write (in the total global sequence)
1717 * performed on a particular object (i.e., memory location), not including the
1719 * @param curr The current ModelAction; also denotes the object location to
1721 * @return The last seq_cst write
1723 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1725 void *location = curr->get_location();
1726 action_list_t *list = obj_map->get_safe_ptr(location);
1727 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1728 action_list_t::reverse_iterator rit;
1729 for (rit = list->rbegin(); rit != list->rend(); rit++)
1730 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1736 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1737 * location). This function identifies the mutex according to the current
1738 * action, which is presumed to perform on the same mutex.
1739 * @param curr The current ModelAction; also denotes the object location to
1741 * @return The last unlock operation
1743 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1745 void *location = curr->get_location();
1746 action_list_t *list = obj_map->get_safe_ptr(location);
1747 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1748 action_list_t::reverse_iterator rit;
1749 for (rit = list->rbegin(); rit != list->rend(); rit++)
1750 if ((*rit)->is_unlock() || (*rit)->is_wait())
1755 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1757 ModelAction *parent = get_last_action(tid);
1759 parent = get_thread(tid)->get_creation();
1764 * Returns the clock vector for a given thread.
1765 * @param tid The thread whose clock vector we want
1766 * @return Desired clock vector
1768 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1770 return get_parent_action(tid)->get_cv();
1774 * Resolve a set of Promises with a current write. The set is provided in the
1775 * Node corresponding to @a write.
1776 * @param write The ModelAction that is fulfilling Promises
1777 * @return True if promises were resolved; false otherwise
1779 bool ModelChecker::resolve_promises(ModelAction *write)
1781 bool resolved = false;
1782 std::vector< thread_id_t, ModelAlloc<thread_id_t> > threads_to_check;
1784 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1785 Promise *promise = (*promises)[promise_index];
1786 if (write->get_node()->get_promise(i)) {
1787 ModelAction *read = promise->get_action();
1788 if (read->is_rmw()) {
1789 mo_graph->addRMWEdge(write, read);
1791 read->read_from(write);
1792 //First fix up the modification order for actions that happened
1794 r_modification_order(read, write);
1795 //Next fix up the modification order for actions that happened
1797 post_r_modification_order(read, write);
1798 //Make sure the promise's value matches the write's value
1799 ASSERT(promise->get_value() == write->get_value());
1802 promises->erase(promises->begin() + promise_index);
1803 threads_to_check.push_back(read->get_tid());
1810 //Check whether reading these writes has made threads unable to
1813 for(unsigned int i=0;i<threads_to_check.size();i++)
1814 mo_check_promises(threads_to_check[i], write);
1820 * Compute the set of promises that could potentially be satisfied by this
1821 * action. Note that the set computation actually appears in the Node, not in
1823 * @param curr The ModelAction that may satisfy promises
1825 void ModelChecker::compute_promises(ModelAction *curr)
1827 for (unsigned int i = 0; i < promises->size(); i++) {
1828 Promise *promise = (*promises)[i];
1829 const ModelAction *act = promise->get_action();
1830 if (!act->happens_before(curr) &&
1832 !act->could_synchronize_with(curr) &&
1833 !act->same_thread(curr) &&
1834 act->get_location() == curr->get_location() &&
1835 promise->get_value() == curr->get_value()) {
1836 curr->get_node()->set_promise(i);
1841 /** Checks promises in response to change in ClockVector Threads. */
1842 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1844 for (unsigned int i = 0; i < promises->size(); i++) {
1845 Promise *promise = (*promises)[i];
1846 const ModelAction *act = promise->get_action();
1847 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1848 merge_cv->synchronized_since(act)) {
1849 if (promise->increment_threads(tid)) {
1850 //Promise has failed
1851 failed_promise = true;
1858 /** Checks promises in response to addition to modification order for threads.
1860 * pthread is the thread that performed the read that created the promise
1862 * pread is the read that created the promise
1864 * pwrite is either the first write to same location as pread by
1865 * pthread that is sequenced after pread or the value read by the
1866 * first read to the same lcoation as pread by pthread that is
1867 * sequenced after pread..
1869 * 1. If tid=pthread, then we check what other threads are reachable
1870 * through the mode order starting with pwrite. Those threads cannot
1871 * perform a write that will resolve the promise due to modification
1872 * order constraints.
1874 * 2. If the tid is not pthread, we check whether pwrite can reach the
1875 * action write through the modification order. If so, that thread
1876 * cannot perform a future write that will resolve the promise due to
1877 * modificatin order constraints.
1879 * @parem tid The thread that either read from the model action
1880 * write, or actually did the model action write.
1882 * @parem write The ModelAction representing the relevant write.
1885 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1886 void * location = write->get_location();
1887 for (unsigned int i = 0; i < promises->size(); i++) {
1888 Promise *promise = (*promises)[i];
1889 const ModelAction *act = promise->get_action();
1891 //Is this promise on the same location?
1892 if ( act->get_location() != location )
1895 //same thread as the promise
1896 if ( act->get_tid()==tid ) {
1898 //do we have a pwrite for the promise, if not, set it
1899 if (promise->get_write() == NULL ) {
1900 promise->set_write(write);
1901 //The pwrite cannot happen before the promise
1902 if (write->happens_before(act) && (write != act)) {
1903 failed_promise = true;
1907 if (mo_graph->checkPromise(write, promise)) {
1908 failed_promise = true;
1913 //Don't do any lookups twice for the same thread
1914 if (promise->has_sync_thread(tid))
1917 if (mo_graph->checkReachable(promise->get_write(), write)) {
1918 if (promise->increment_threads(tid)) {
1919 failed_promise = true;
1927 * Compute the set of writes that may break the current pending release
1928 * sequence. This information is extracted from previou release sequence
1931 * @param curr The current ModelAction. Must be a release sequence fixup
1934 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1936 if (pending_rel_seqs->empty())
1939 struct release_seq *pending = pending_rel_seqs->back();
1940 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1941 const ModelAction *write = pending->writes[i];
1942 curr->get_node()->add_relseq_break(write);
1945 /* NULL means don't break the sequence; just synchronize */
1946 curr->get_node()->add_relseq_break(NULL);
1950 * Build up an initial set of all past writes that this 'read' action may read
1951 * from. This set is determined by the clock vector's "happens before"
1953 * @param curr is the current ModelAction that we are exploring; it must be a
1956 void ModelChecker::build_reads_from_past(ModelAction *curr)
1958 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1960 ASSERT(curr->is_read());
1962 ModelAction *last_seq_cst = NULL;
1964 /* Track whether this object has been initialized */
1965 bool initialized = false;
1967 if (curr->is_seqcst()) {
1968 last_seq_cst = get_last_seq_cst(curr);
1969 /* We have to at least see the last sequentially consistent write,
1970 so we are initialized. */
1971 if (last_seq_cst != NULL)
1975 /* Iterate over all threads */
1976 for (i = 0; i < thrd_lists->size(); i++) {
1977 /* Iterate over actions in thread, starting from most recent */
1978 action_list_t *list = &(*thrd_lists)[i];
1979 action_list_t::reverse_iterator rit;
1980 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1981 ModelAction *act = *rit;
1983 /* Only consider 'write' actions */
1984 if (!act->is_write() || act == curr)
1987 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1988 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1989 DEBUG("Adding action to may_read_from:\n");
1990 if (DBG_ENABLED()) {
1995 if (curr->get_sleep_flag() && ! curr->is_seqcst()) {
1996 if (sleep_can_read_from(curr, act))
1997 curr->get_node()->add_read_from(act);
1999 curr->get_node()->add_read_from(act);
2002 /* Include at most one act per-thread that "happens before" curr */
2003 if (act->happens_before(curr)) {
2011 /** @todo Need a more informative way of reporting errors. */
2012 printf("ERROR: may read from uninitialized atomic\n");
2016 if (DBG_ENABLED() || !initialized) {
2017 printf("Reached read action:\n");
2019 printf("Printing may_read_from\n");
2020 curr->get_node()->print_may_read_from();
2021 printf("End printing may_read_from\n");
2025 bool ModelChecker::sleep_can_read_from(ModelAction * curr, const ModelAction *write) {
2027 Node *prevnode=write->get_node()->get_parent();
2028 bool thread_sleep=prevnode->get_enabled_array()[id_to_int(curr->get_tid())]==THREAD_SLEEP_SET;
2029 if (write->is_release()&&thread_sleep)
2031 if (!write->is_rmw()) {
2034 if (write->get_reads_from()==NULL)
2036 write=write->get_reads_from();
2040 static void print_list(action_list_t *list)
2042 action_list_t::iterator it;
2044 printf("---------------------------------------------------------------------\n");
2046 unsigned int hash=0;
2048 for (it = list->begin(); it != list->end(); it++) {
2050 hash=hash^(hash<<3)^((*it)->hash());
2052 printf("HASH %u\n", hash);
2053 printf("---------------------------------------------------------------------\n");
2056 #if SUPPORT_MOD_ORDER_DUMP
2057 void ModelChecker::dumpGraph(char *filename) {
2059 sprintf(buffer, "%s.dot",filename);
2060 FILE *file=fopen(buffer, "w");
2061 fprintf(file, "digraph %s {\n",filename);
2062 mo_graph->dumpNodes(file);
2063 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
2065 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
2066 ModelAction *action=*it;
2067 if (action->is_read()) {
2068 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
2069 if (action->get_reads_from()!=NULL)
2070 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
2072 if (thread_array[action->get_tid()] != NULL) {
2073 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
2076 thread_array[action->get_tid()]=action;
2078 fprintf(file,"}\n");
2079 model_free(thread_array);
2084 void ModelChecker::print_summary()
2087 printf("Number of executions: %d\n", num_executions);
2088 printf("Number of feasible executions: %d\n", num_feasible_executions);
2089 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
2091 #if SUPPORT_MOD_ORDER_DUMP
2093 char buffername[100];
2094 sprintf(buffername, "exec%04u", num_executions);
2095 mo_graph->dumpGraphToFile(buffername);
2096 sprintf(buffername, "graph%04u", num_executions);
2097 dumpGraph(buffername);
2100 if (!isfinalfeasible())
2101 printf("INFEASIBLE EXECUTION!\n");
2102 print_list(action_trace);
2107 * Add a Thread to the system for the first time. Should only be called once
2109 * @param t The Thread to add
2111 void ModelChecker::add_thread(Thread *t)
2113 thread_map->put(id_to_int(t->get_id()), t);
2114 scheduler->add_thread(t);
2118 * Removes a thread from the scheduler.
2119 * @param the thread to remove.
2121 void ModelChecker::remove_thread(Thread *t)
2123 scheduler->remove_thread(t);
2127 * @brief Get a Thread reference by its ID
2128 * @param tid The Thread's ID
2129 * @return A Thread reference
2131 Thread * ModelChecker::get_thread(thread_id_t tid) const
2133 return thread_map->get(id_to_int(tid));
2137 * @brief Get a reference to the Thread in which a ModelAction was executed
2138 * @param act The ModelAction
2139 * @return A Thread reference
2141 Thread * ModelChecker::get_thread(ModelAction *act) const
2143 return get_thread(act->get_tid());
2147 * Switch from a user-context to the "master thread" context (a.k.a. system
2148 * context). This switch is made with the intention of exploring a particular
2149 * model-checking action (described by a ModelAction object). Must be called
2150 * from a user-thread context.
2152 * @param act The current action that will be explored. May be NULL only if
2153 * trace is exiting via an assertion (see ModelChecker::set_assert and
2154 * ModelChecker::has_asserted).
2155 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
2157 int ModelChecker::switch_to_master(ModelAction *act)
2160 Thread *old = thread_current();
2161 set_current_action(act);
2162 old->set_state(THREAD_READY);
2163 return Thread::swap(old, &system_context);
2167 * Takes the next step in the execution, if possible.
2168 * @return Returns true (success) if a step was taken and false otherwise.
2170 bool ModelChecker::take_step() {
2174 Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
2176 if (curr->get_state() == THREAD_READY) {
2177 ASSERT(priv->current_action);
2179 priv->nextThread = check_current_action(priv->current_action);
2180 priv->current_action = NULL;
2182 if (curr->is_blocked() || curr->is_complete())
2183 scheduler->remove_thread(curr);
2188 Thread *next = scheduler->next_thread(priv->nextThread);
2190 /* Infeasible -> don't take any more steps */
2194 if (params.bound != 0) {
2195 if (priv->used_sequence_numbers > params.bound) {
2200 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
2201 next ? id_to_int(next->get_id()) : -1);
2204 * Launch end-of-execution release sequence fixups only when there are:
2206 * (1) no more user threads to run (or when execution replay chooses
2207 * the 'model_thread')
2208 * (2) pending release sequences
2209 * (3) pending assertions (i.e., data races)
2210 * (4) no pending promises
2212 if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
2213 isfinalfeasible() && !unrealizedraces.empty()) {
2214 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
2215 pending_rel_seqs->size());
2216 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2217 std::memory_order_seq_cst, NULL, VALUE_NONE,
2219 set_current_action(fixup);
2223 /* next == NULL -> don't take any more steps */
2227 next->set_state(THREAD_RUNNING);
2229 if (next->get_pending() != NULL) {
2230 /* restart a pending action */
2231 set_current_action(next->get_pending());
2232 next->set_pending(NULL);
2233 next->set_state(THREAD_READY);
2237 /* Return false only if swap fails with an error */
2238 return (Thread::swap(&system_context, next) == 0);
2241 /** Runs the current execution until threre are no more steps to take. */
2242 void ModelChecker::finish_execution() {
2245 while (take_step());