8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.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 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
35 promises(new std::vector<Promise *>()),
36 futurevalues(new std::vector<struct PendingFutureValue>()),
37 pending_rel_seqs(new std::vector<struct release_seq *>()),
38 thrd_last_action(new std::vector<ModelAction *>(1)),
39 node_stack(new NodeStack()),
40 mo_graph(new CycleGraph()),
41 failed_promise(false),
42 too_many_reads(false),
44 bad_synchronization(false)
46 /* Allocate this "size" on the snapshotting heap */
47 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
48 /* First thread created will have id INITIAL_THREAD_ID */
49 priv->next_thread_id = INITIAL_THREAD_ID;
51 /* Initialize a model-checker thread, for special ModelActions */
52 model_thread = new Thread(get_next_id());
53 thread_map->put(id_to_int(model_thread->get_id()), model_thread);
56 /** @brief Destructor */
57 ModelChecker::~ModelChecker()
59 for (unsigned int i = 0; i < get_num_threads(); i++)
60 delete thread_map->get(i);
65 delete lock_waiters_map;
68 for (unsigned int i = 0; i < promises->size(); i++)
69 delete (*promises)[i];
72 delete pending_rel_seqs;
74 delete thrd_last_action;
81 * Restores user program to initial state and resets all model-checker data
84 void ModelChecker::reset_to_initial_state()
86 DEBUG("+++ Resetting to initial state +++\n");
87 node_stack->reset_execution();
88 failed_promise = false;
89 too_many_reads = false;
90 bad_synchronization = false;
92 snapshotObject->backTrackBeforeStep(0);
95 /** @return a thread ID for a new Thread */
96 thread_id_t ModelChecker::get_next_id()
98 return priv->next_thread_id++;
101 /** @return the number of user threads created during this execution */
102 unsigned int ModelChecker::get_num_threads()
104 return priv->next_thread_id;
107 /** @return The currently executing Thread. */
108 Thread * ModelChecker::get_current_thread()
110 return scheduler->get_current_thread();
113 /** @return a sequence number for a new ModelAction */
114 modelclock_t ModelChecker::get_next_seq_num()
116 return ++priv->used_sequence_numbers;
120 * @brief Choose the next thread to execute.
122 * This function chooses the next thread that should execute. It can force the
123 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
124 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
125 * The model-checker may have no preference regarding the next thread (i.e.,
126 * when exploring a new execution ordering), in which case this will return
128 * @param curr The current ModelAction. This action might guide the choice of
130 * @return The next thread to run. If the model-checker has no preference, NULL.
132 Thread * ModelChecker::get_next_thread(ModelAction *curr)
137 /* Do not split atomic actions. */
139 return thread_current();
140 /* The THREAD_CREATE action points to the created Thread */
141 else if (curr->get_type() == THREAD_CREATE)
142 return (Thread *)curr->get_location();
145 /* Have we completed exploring the preselected path? */
149 /* Else, we are trying to replay an execution */
150 ModelAction *next = node_stack->get_next()->get_action();
152 if (next == diverge) {
153 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
154 earliest_diverge=diverge;
156 Node *nextnode = next->get_node();
157 /* Reached divergence point */
158 if (nextnode->increment_promise()) {
159 /* The next node will try to satisfy a different set of promises. */
160 tid = next->get_tid();
161 node_stack->pop_restofstack(2);
162 } else if (nextnode->increment_read_from()) {
163 /* The next node will read from a different value. */
164 tid = next->get_tid();
165 node_stack->pop_restofstack(2);
166 } else if (nextnode->increment_future_value()) {
167 /* The next node will try to read from a different future value. */
168 tid = next->get_tid();
169 node_stack->pop_restofstack(2);
170 } else if (nextnode->increment_relseq_break()) {
171 /* The next node will try to resolve a release sequence differently */
172 tid = next->get_tid();
173 node_stack->pop_restofstack(2);
175 /* Make a different thread execute for next step */
176 Node *node = nextnode->get_parent();
177 tid = node->get_next_backtrack();
178 node_stack->pop_restofstack(1);
179 if (diverge==earliest_diverge) {
180 earliest_diverge=node->get_action();
183 DEBUG("*** Divergence point ***\n");
187 tid = next->get_tid();
189 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
190 ASSERT(tid != THREAD_ID_T_NONE);
191 return thread_map->get(id_to_int(tid));
195 * Queries the model-checker for more executions to explore and, if one
196 * exists, resets the model-checker state to execute a new execution.
198 * @return If there are more executions to explore, return true. Otherwise,
201 bool ModelChecker::next_execution()
207 if (isfinalfeasible()) {
208 printf("Earliest divergence point since last feasible execution:\n");
209 if (earliest_diverge)
210 earliest_diverge->print();
212 printf("(Not set)\n");
214 earliest_diverge = NULL;
215 num_feasible_executions++;
218 DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
219 pending_rel_seqs->size());
221 if (isfinalfeasible() || DBG_ENABLED())
224 if ((diverge = get_next_backtrack()) == NULL)
228 printf("Next execution will diverge at:\n");
232 reset_to_initial_state();
236 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
238 switch (act->get_type()) {
242 /* linear search: from most recent to oldest */
243 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
244 action_list_t::reverse_iterator rit;
245 for (rit = list->rbegin(); rit != list->rend(); rit++) {
246 ModelAction *prev = *rit;
247 if (prev->could_synchronize_with(act))
253 case ATOMIC_TRYLOCK: {
254 /* linear search: from most recent to oldest */
255 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
256 action_list_t::reverse_iterator rit;
257 for (rit = list->rbegin(); rit != list->rend(); rit++) {
258 ModelAction *prev = *rit;
259 if (act->is_conflicting_lock(prev))
264 case ATOMIC_UNLOCK: {
265 /* linear search: from most recent to oldest */
266 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
267 action_list_t::reverse_iterator rit;
268 for (rit = list->rbegin(); rit != list->rend(); rit++) {
269 ModelAction *prev = *rit;
270 if (!act->same_thread(prev)&&prev->is_failed_trylock())
281 /** This method find backtracking points where we should try to
282 * reorder the parameter ModelAction against.
284 * @param the ModelAction to find backtracking points for.
286 void ModelChecker::set_backtracking(ModelAction *act)
288 Thread *t = get_thread(act);
289 ModelAction * prev = get_last_conflict(act);
293 Node * node = prev->get_node()->get_parent();
295 int low_tid, high_tid;
296 if (node->is_enabled(t)) {
297 low_tid = id_to_int(act->get_tid());
298 high_tid = low_tid+1;
301 high_tid = get_num_threads();
304 for(int i = low_tid; i < high_tid; i++) {
305 thread_id_t tid = int_to_id(i);
306 if (!node->is_enabled(tid))
309 /* Check if this has been explored already */
310 if (node->has_been_explored(tid))
313 /* See if fairness allows */
314 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
316 for(int t=0;t<node->get_num_threads();t++) {
317 thread_id_t tother=int_to_id(t);
318 if (node->is_enabled(tother) && node->has_priority(tother)) {
327 /* Cache the latest backtracking point */
328 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
329 priv->next_backtrack = prev;
331 /* If this is a new backtracking point, mark the tree */
332 if (!node->set_backtrack(tid))
334 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
335 id_to_int(prev->get_tid()),
336 id_to_int(t->get_id()));
345 * Returns last backtracking point. The model checker will explore a different
346 * path for this point in the next execution.
347 * @return The ModelAction at which the next execution should diverge.
349 ModelAction * ModelChecker::get_next_backtrack()
351 ModelAction *next = priv->next_backtrack;
352 priv->next_backtrack = NULL;
357 * Processes a read or rmw model action.
358 * @param curr is the read model action to process.
359 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
360 * @return True if processing this read updates the mo_graph.
362 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
365 bool updated = false;
367 const ModelAction *reads_from = curr->get_node()->get_read_from();
368 if (reads_from != NULL) {
369 mo_graph->startChanges();
371 value = reads_from->get_value();
372 bool r_status = false;
374 if (!second_part_of_rmw) {
375 check_recency(curr, reads_from);
376 r_status = r_modification_order(curr, reads_from);
380 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
381 mo_graph->rollbackChanges();
382 too_many_reads = false;
386 curr->read_from(reads_from);
387 mo_graph->commitChanges();
388 mo_check_promises(curr->get_tid(), reads_from);
391 } else if (!second_part_of_rmw) {
392 /* Read from future value */
393 value = curr->get_node()->get_future_value();
394 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
395 curr->read_from(NULL);
396 Promise *valuepromise = new Promise(curr, value, expiration);
397 promises->push_back(valuepromise);
399 get_thread(curr)->set_return_value(value);
405 * Processes a lock, trylock, or unlock model action. @param curr is
406 * the read model action to process.
408 * The try lock operation checks whether the lock is taken. If not,
409 * it falls to the normal lock operation case. If so, it returns
412 * The lock operation has already been checked that it is enabled, so
413 * it just grabs the lock and synchronizes with the previous unlock.
415 * The unlock operation has to re-enable all of the threads that are
416 * waiting on the lock.
418 * @return True if synchronization was updated; false otherwise
420 bool ModelChecker::process_mutex(ModelAction *curr) {
421 std::mutex *mutex = (std::mutex *)curr->get_location();
422 struct std::mutex_state *state = mutex->get_state();
423 switch (curr->get_type()) {
424 case ATOMIC_TRYLOCK: {
425 bool success = !state->islocked;
426 curr->set_try_lock(success);
428 get_thread(curr)->set_return_value(0);
431 get_thread(curr)->set_return_value(1);
433 //otherwise fall into the lock case
435 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
436 printf("Lock access before initialization\n");
439 state->islocked = true;
440 ModelAction *unlock = get_last_unlock(curr);
441 //synchronize with the previous unlock statement
442 if (unlock != NULL) {
443 curr->synchronize_with(unlock);
448 case ATOMIC_UNLOCK: {
450 state->islocked = false;
451 //wake up the other threads
452 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
453 //activate all the waiting threads
454 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
455 scheduler->wake(get_thread(*rit));
467 * Process a write ModelAction
468 * @param curr The ModelAction to process
469 * @return True if the mo_graph was updated or promises were resolved
471 bool ModelChecker::process_write(ModelAction *curr)
473 bool updated_mod_order = w_modification_order(curr);
474 bool updated_promises = resolve_promises(curr);
476 if (promises->size() == 0) {
477 for (unsigned int i = 0; i < futurevalues->size(); i++) {
478 struct PendingFutureValue pfv = (*futurevalues)[i];
479 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
480 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
481 priv->next_backtrack = pfv.act;
483 futurevalues->resize(0);
486 mo_graph->commitChanges();
487 mo_check_promises(curr->get_tid(), curr);
489 get_thread(curr)->set_return_value(VALUE_NONE);
490 return updated_mod_order || updated_promises;
494 * @brief Process the current action for thread-related activity
496 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
497 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
498 * synchronization, etc. This function is a no-op for non-THREAD actions
499 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
501 * @param curr The current action
502 * @return True if synchronization was updated or a thread completed
504 bool ModelChecker::process_thread_action(ModelAction *curr)
506 bool updated = false;
508 switch (curr->get_type()) {
509 case THREAD_CREATE: {
510 Thread *th = (Thread *)curr->get_location();
511 th->set_creation(curr);
515 Thread *waiting, *blocking;
516 waiting = get_thread(curr);
517 blocking = (Thread *)curr->get_location();
518 if (!blocking->is_complete()) {
519 blocking->push_wait_list(curr);
520 scheduler->sleep(waiting);
522 do_complete_join(curr);
523 updated = true; /* trigger rel-seq checks */
527 case THREAD_FINISH: {
528 Thread *th = get_thread(curr);
529 while (!th->wait_list_empty()) {
530 ModelAction *act = th->pop_wait_list();
531 Thread *wake = get_thread(act);
532 scheduler->wake(wake);
533 do_complete_join(act);
534 updated = true; /* trigger rel-seq checks */
537 updated = true; /* trigger rel-seq checks */
541 check_promises(curr->get_tid(), NULL, curr->get_cv());
552 * @brief Process the current action for release sequence fixup activity
554 * Performs model-checker release sequence fixups for the current action,
555 * forcing a single pending release sequence to break (with a given, potential
556 * "loose" write) or to complete (i.e., synchronize). If a pending release
557 * sequence forms a complete release sequence, then we must perform the fixup
558 * synchronization, mo_graph additions, etc.
560 * @param curr The current action; must be a release sequence fixup action
561 * @param work_queue The work queue to which to add work items as they are
564 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
566 const ModelAction *write = curr->get_node()->get_relseq_break();
567 struct release_seq *sequence = pending_rel_seqs->back();
568 pending_rel_seqs->pop_back();
570 ModelAction *acquire = sequence->acquire;
571 const ModelAction *rf = sequence->rf;
572 const ModelAction *release = sequence->release;
576 ASSERT(release->same_thread(rf));
580 * @todo Forcing a synchronization requires that we set
581 * modification order constraints. For instance, we can't allow
582 * a fixup sequence in which two separate read-acquire
583 * operations read from the same sequence, where the first one
584 * synchronizes and the other doesn't. Essentially, we can't
585 * allow any writes to insert themselves between 'release' and
589 /* Must synchronize */
590 if (!acquire->synchronize_with(release)) {
591 set_bad_synchronization();
594 /* Re-check all pending release sequences */
595 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
596 /* Re-check act for mo_graph edges */
597 work_queue->push_back(MOEdgeWorkEntry(acquire));
599 /* propagate synchronization to later actions */
600 action_list_t::reverse_iterator rit = action_trace->rbegin();
601 for (; (*rit) != acquire; rit++) {
602 ModelAction *propagate = *rit;
603 if (acquire->happens_before(propagate)) {
604 propagate->synchronize_with(acquire);
605 /* Re-check 'propagate' for mo_graph edges */
606 work_queue->push_back(MOEdgeWorkEntry(propagate));
610 /* Break release sequence with new edges:
611 * release --mo--> write --mo--> rf */
612 mo_graph->addEdge(release, write);
613 mo_graph->addEdge(write, rf);
616 /* See if we have realized a data race */
617 if (checkDataRaces())
622 * Initialize the current action by performing one or more of the following
623 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
624 * in the NodeStack, manipulating backtracking sets, allocating and
625 * initializing clock vectors, and computing the promises to fulfill.
627 * @param curr The current action, as passed from the user context; may be
628 * freed/invalidated after the execution of this function
629 * @return The current action, as processed by the ModelChecker. Is only the
630 * same as the parameter @a curr if this is a newly-explored action.
632 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
634 ModelAction *newcurr;
636 if (curr->is_rmwc() || curr->is_rmw()) {
637 newcurr = process_rmw(curr);
640 if (newcurr->is_rmw())
641 compute_promises(newcurr);
645 curr->set_seq_number(get_next_seq_num());
647 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
649 /* First restore type and order in case of RMW operation */
651 newcurr->copy_typeandorder(curr);
653 ASSERT(curr->get_location() == newcurr->get_location());
654 newcurr->copy_from_new(curr);
656 /* Discard duplicate ModelAction; use action from NodeStack */
659 /* Always compute new clock vector */
660 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
664 /* Always compute new clock vector */
665 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
667 * Perform one-time actions when pushing new ModelAction onto
670 if (newcurr->is_write())
671 compute_promises(newcurr);
672 else if (newcurr->is_relseq_fixup())
673 compute_relseq_breakwrites(newcurr);
679 * This method checks whether a model action is enabled at the given point.
680 * At this point, it checks whether a lock operation would be successful at this point.
681 * If not, it puts the thread in a waiter list.
682 * @param curr is the ModelAction to check whether it is enabled.
683 * @return a bool that indicates whether the action is enabled.
685 bool ModelChecker::check_action_enabled(ModelAction *curr) {
686 if (curr->is_lock()) {
687 std::mutex * lock = (std::mutex *)curr->get_location();
688 struct std::mutex_state * state = lock->get_state();
689 if (state->islocked) {
690 //Stick the action in the appropriate waiting queue
691 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
700 * This is the heart of the model checker routine. It performs model-checking
701 * actions corresponding to a given "current action." Among other processes, it
702 * calculates reads-from relationships, updates synchronization clock vectors,
703 * forms a memory_order constraints graph, and handles replay/backtrack
704 * execution when running permutations of previously-observed executions.
706 * @param curr The current action to process
707 * @return The next Thread that must be executed. May be NULL if ModelChecker
708 * makes no choice (e.g., according to replay execution, combining RMW actions,
711 Thread * ModelChecker::check_current_action(ModelAction *curr)
715 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
717 if (!check_action_enabled(curr)) {
718 /* Make the execution look like we chose to run this action
719 * much later, when a lock is actually available to release */
720 get_current_thread()->set_pending(curr);
721 scheduler->sleep(get_current_thread());
722 return get_next_thread(NULL);
725 ModelAction *newcurr = initialize_curr_action(curr);
727 /* Add the action to lists before any other model-checking tasks */
728 if (!second_part_of_rmw)
729 add_action_to_lists(newcurr);
731 /* Build may_read_from set for newly-created actions */
732 if (curr == newcurr && curr->is_read())
733 build_reads_from_past(curr);
736 /* Initialize work_queue with the "current action" work */
737 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
739 while (!work_queue.empty()) {
740 WorkQueueEntry work = work_queue.front();
741 work_queue.pop_front();
744 case WORK_CHECK_CURR_ACTION: {
745 ModelAction *act = work.action;
746 bool update = false; /* update this location's release seq's */
747 bool update_all = false; /* update all release seq's */
749 if (process_thread_action(curr))
752 if (act->is_read() && process_read(act, second_part_of_rmw))
755 if (act->is_write() && process_write(act))
758 if (act->is_mutex_op() && process_mutex(act))
761 if (act->is_relseq_fixup())
762 process_relseq_fixup(curr, &work_queue);
765 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
767 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
770 case WORK_CHECK_RELEASE_SEQ:
771 resolve_release_sequences(work.location, &work_queue);
773 case WORK_CHECK_MO_EDGES: {
774 /** @todo Complete verification of work_queue */
775 ModelAction *act = work.action;
776 bool updated = false;
778 if (act->is_read()) {
779 const ModelAction *rf = act->get_reads_from();
780 if (rf != NULL && r_modification_order(act, rf))
783 if (act->is_write()) {
784 if (w_modification_order(act))
787 mo_graph->commitChanges();
790 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
799 check_curr_backtracking(curr);
801 set_backtracking(curr);
803 return get_next_thread(curr);
807 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
808 * operation from the Thread it is joining with. Must be called after the
809 * completion of the Thread in question.
810 * @param join The THREAD_JOIN action
812 void ModelChecker::do_complete_join(ModelAction *join)
814 Thread *blocking = (Thread *)join->get_location();
815 ModelAction *act = get_last_action(blocking->get_id());
816 join->synchronize_with(act);
819 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
820 Node *currnode = curr->get_node();
821 Node *parnode = currnode->get_parent();
823 if ((!parnode->backtrack_empty() ||
824 !currnode->read_from_empty() ||
825 !currnode->future_value_empty() ||
826 !currnode->promise_empty() ||
827 !currnode->relseq_break_empty())
828 && (!priv->next_backtrack ||
829 *curr > *priv->next_backtrack)) {
830 priv->next_backtrack = curr;
834 bool ModelChecker::promises_expired() {
835 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
836 Promise *promise = (*promises)[promise_index];
837 if (promise->get_expiration()<priv->used_sequence_numbers) {
844 /** @return whether the current partial trace must be a prefix of a
846 bool ModelChecker::isfeasibleprefix() {
847 return promises->size() == 0 && pending_rel_seqs->size() == 0;
850 /** @return whether the current partial trace is feasible. */
851 bool ModelChecker::isfeasible() {
852 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
853 DEBUG("Infeasible: RMW violation\n");
855 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
858 /** @return whether the current partial trace is feasible other than
859 * multiple RMW reading from the same store. */
860 bool ModelChecker::isfeasibleotherthanRMW() {
862 if (mo_graph->checkForCycles())
863 DEBUG("Infeasible: modification order cycles\n");
865 DEBUG("Infeasible: failed promise\n");
867 DEBUG("Infeasible: too many reads\n");
868 if (bad_synchronization)
869 DEBUG("Infeasible: bad synchronization ordering\n");
870 if (promises_expired())
871 DEBUG("Infeasible: promises expired\n");
873 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
876 /** Returns whether the current completed trace is feasible. */
877 bool ModelChecker::isfinalfeasible() {
878 if (DBG_ENABLED() && promises->size() != 0)
879 DEBUG("Infeasible: unrevolved promises\n");
881 return isfeasible() && promises->size() == 0;
884 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
885 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
886 ModelAction *lastread = get_last_action(act->get_tid());
887 lastread->process_rmw(act);
888 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
889 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
890 mo_graph->commitChanges();
896 * Checks whether a thread has read from the same write for too many times
897 * without seeing the effects of a later write.
900 * 1) there must a different write that we could read from that would satisfy the modification order,
901 * 2) we must have read from the same value in excess of maxreads times, and
902 * 3) that other write must have been in the reads_from set for maxreads times.
904 * If so, we decide that the execution is no longer feasible.
906 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
907 if (params.maxreads != 0) {
909 if (curr->get_node()->get_read_from_size() <= 1)
911 //Must make sure that execution is currently feasible... We could
912 //accidentally clear by rolling back
915 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
916 int tid = id_to_int(curr->get_tid());
919 if ((int)thrd_lists->size() <= tid)
921 action_list_t *list = &(*thrd_lists)[tid];
923 action_list_t::reverse_iterator rit = list->rbegin();
925 for (; (*rit) != curr; rit++)
927 /* go past curr now */
930 action_list_t::reverse_iterator ritcopy = rit;
931 //See if we have enough reads from the same value
933 for (; count < params.maxreads; rit++,count++) {
934 if (rit==list->rend())
936 ModelAction *act = *rit;
940 if (act->get_reads_from() != rf)
942 if (act->get_node()->get_read_from_size() <= 1)
945 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
947 const ModelAction * write = curr->get_node()->get_read_from_at(i);
949 //Need a different write
953 /* Test to see whether this is a feasible write to read from*/
954 mo_graph->startChanges();
955 r_modification_order(curr, write);
956 bool feasiblereadfrom = isfeasible();
957 mo_graph->rollbackChanges();
959 if (!feasiblereadfrom)
963 bool feasiblewrite = true;
964 //new we need to see if this write works for everyone
966 for (int loop = count; loop>0; loop--,rit++) {
967 ModelAction *act=*rit;
968 bool foundvalue = false;
969 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
970 if (act->get_node()->get_read_from_at(i)==write) {
976 feasiblewrite = false;
981 too_many_reads = true;
989 * Updates the mo_graph with the constraints imposed from the current
992 * Basic idea is the following: Go through each other thread and find
993 * the lastest action that happened before our read. Two cases:
995 * (1) The action is a write => that write must either occur before
996 * the write we read from or be the write we read from.
998 * (2) The action is a read => the write that that action read from
999 * must occur before the write we read from or be the same write.
1001 * @param curr The current action. Must be a read.
1002 * @param rf The action that curr reads from. Must be a write.
1003 * @return True if modification order edges were added; false otherwise
1005 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
1007 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1010 ASSERT(curr->is_read());
1012 /* Iterate over all threads */
1013 for (i = 0; i < thrd_lists->size(); i++) {
1014 /* Iterate over actions in thread, starting from most recent */
1015 action_list_t *list = &(*thrd_lists)[i];
1016 action_list_t::reverse_iterator rit;
1017 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1018 ModelAction *act = *rit;
1021 * Include at most one act per-thread that "happens
1022 * before" curr. Don't consider reflexively.
1024 if (act->happens_before(curr) && act != curr) {
1025 if (act->is_write()) {
1027 mo_graph->addEdge(act, rf);
1031 const ModelAction *prevreadfrom = act->get_reads_from();
1032 //if the previous read is unresolved, keep going...
1033 if (prevreadfrom == NULL)
1036 if (rf != prevreadfrom) {
1037 mo_graph->addEdge(prevreadfrom, rf);
1049 /** This method fixes up the modification order when we resolve a
1050 * promises. The basic problem is that actions that occur after the
1051 * read curr could not property add items to the modification order
1054 * So for each thread, we find the earliest item that happens after
1055 * the read curr. This is the item we have to fix up with additional
1056 * constraints. If that action is write, we add a MO edge between
1057 * the Action rf and that action. If the action is a read, we add a
1058 * MO edge between the Action rf, and whatever the read accessed.
1060 * @param curr is the read ModelAction that we are fixing up MO edges for.
1061 * @param rf is the write ModelAction that curr reads from.
1064 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1066 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1068 ASSERT(curr->is_read());
1070 /* Iterate over all threads */
1071 for (i = 0; i < thrd_lists->size(); i++) {
1072 /* Iterate over actions in thread, starting from most recent */
1073 action_list_t *list = &(*thrd_lists)[i];
1074 action_list_t::reverse_iterator rit;
1075 ModelAction *lastact = NULL;
1077 /* Find last action that happens after curr that is either not curr or a rmw */
1078 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1079 ModelAction *act = *rit;
1080 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1086 /* Include at most one act per-thread that "happens before" curr */
1087 if (lastact != NULL) {
1088 if (lastact==curr) {
1089 //Case 1: The resolved read is a RMW, and we need to make sure
1090 //that the write portion of the RMW mod order after rf
1092 mo_graph->addEdge(rf, lastact);
1093 } else if (lastact->is_read()) {
1094 //Case 2: The resolved read is a normal read and the next
1095 //operation is a read, and we need to make sure the value read
1096 //is mod ordered after rf
1098 const ModelAction *postreadfrom = lastact->get_reads_from();
1099 if (postreadfrom != NULL&&rf != postreadfrom)
1100 mo_graph->addEdge(rf, postreadfrom);
1102 //Case 3: The resolved read is a normal read and the next
1103 //operation is a write, and we need to make sure that the
1104 //write is mod ordered after rf
1106 mo_graph->addEdge(rf, lastact);
1114 * Updates the mo_graph with the constraints imposed from the current write.
1116 * Basic idea is the following: Go through each other thread and find
1117 * the lastest action that happened before our write. Two cases:
1119 * (1) The action is a write => that write must occur before
1122 * (2) The action is a read => the write that that action read from
1123 * must occur before the current write.
1125 * This method also handles two other issues:
1127 * (I) Sequential Consistency: Making sure that if the current write is
1128 * seq_cst, that it occurs after the previous seq_cst write.
1130 * (II) Sending the write back to non-synchronizing reads.
1132 * @param curr The current action. Must be a write.
1133 * @return True if modification order edges were added; false otherwise
1135 bool ModelChecker::w_modification_order(ModelAction *curr)
1137 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1140 ASSERT(curr->is_write());
1142 if (curr->is_seqcst()) {
1143 /* We have to at least see the last sequentially consistent write,
1144 so we are initialized. */
1145 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1146 if (last_seq_cst != NULL) {
1147 mo_graph->addEdge(last_seq_cst, curr);
1152 /* Iterate over all threads */
1153 for (i = 0; i < thrd_lists->size(); i++) {
1154 /* Iterate over actions in thread, starting from most recent */
1155 action_list_t *list = &(*thrd_lists)[i];
1156 action_list_t::reverse_iterator rit;
1157 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1158 ModelAction *act = *rit;
1161 * 1) If RMW and it actually read from something, then we
1162 * already have all relevant edges, so just skip to next
1165 * 2) If RMW and it didn't read from anything, we should
1166 * whatever edge we can get to speed up convergence.
1168 * 3) If normal write, we need to look at earlier actions, so
1169 * continue processing list.
1171 if (curr->is_rmw()) {
1172 if (curr->get_reads_from()!=NULL)
1181 * Include at most one act per-thread that "happens
1184 if (act->happens_before(curr)) {
1186 * Note: if act is RMW, just add edge:
1188 * The following edge should be handled elsewhere:
1189 * readfrom(act) --mo--> act
1191 if (act->is_write())
1192 mo_graph->addEdge(act, curr);
1193 else if (act->is_read()) {
1194 //if previous read accessed a null, just keep going
1195 if (act->get_reads_from() == NULL)
1197 mo_graph->addEdge(act->get_reads_from(), curr);
1201 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1202 !act->same_thread(curr)) {
1203 /* We have an action that:
1204 (1) did not happen before us
1205 (2) is a read and we are a write
1206 (3) cannot synchronize with us
1207 (4) is in a different thread
1209 that read could potentially read from our write.
1211 if (thin_air_constraint_may_allow(curr, act)) {
1213 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1214 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1215 futurevalues->push_back(pfv);
1225 /** Arbitrary reads from the future are not allowed. Section 29.3
1226 * part 9 places some constraints. This method checks one result of constraint
1227 * constraint. Others require compiler support. */
1228 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1229 if (!writer->is_rmw())
1232 if (!reader->is_rmw())
1235 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1236 if (search == reader)
1238 if (search->get_tid() == reader->get_tid() &&
1239 search->happens_before(reader))
1247 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1248 * The ModelAction under consideration is expected to be taking part in
1249 * release/acquire synchronization as an object of the "reads from" relation.
1250 * Note that this can only provide release sequence support for RMW chains
1251 * which do not read from the future, as those actions cannot be traced until
1252 * their "promise" is fulfilled. Similarly, we may not even establish the
1253 * presence of a release sequence with certainty, as some modification order
1254 * constraints may be decided further in the future. Thus, this function
1255 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1256 * and a boolean representing certainty.
1258 * @todo Finish lazy updating, when promises are fulfilled in the future
1259 * @param rf The action that might be part of a release sequence. Must be a
1261 * @param release_heads A pass-by-reference style return parameter. After
1262 * execution of this function, release_heads will contain the heads of all the
1263 * relevant release sequences, if any exists with certainty
1264 * @param pending A pass-by-reference style return parameter which is only used
1265 * when returning false (i.e., uncertain). Returns most information regarding
1266 * an uncertain release sequence, including any write operations that might
1267 * break the sequence.
1268 * @return true, if the ModelChecker is certain that release_heads is complete;
1271 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1272 rel_heads_list_t *release_heads,
1273 struct release_seq *pending) const
1275 /* Only check for release sequences if there are no cycles */
1276 if (mo_graph->checkForCycles())
1280 ASSERT(rf->is_write());
1282 if (rf->is_release())
1283 release_heads->push_back(rf);
1285 break; /* End of RMW chain */
1287 /** @todo Need to be smarter here... In the linux lock
1288 * example, this will run to the beginning of the program for
1290 /** @todo The way to be smarter here is to keep going until 1
1291 * thread has a release preceded by an acquire and you've seen
1294 /* acq_rel RMW is a sufficient stopping condition */
1295 if (rf->is_acquire() && rf->is_release())
1296 return true; /* complete */
1298 rf = rf->get_reads_from();
1301 /* read from future: need to settle this later */
1303 return false; /* incomplete */
1306 if (rf->is_release())
1307 return true; /* complete */
1309 /* else relaxed write; check modification order for contiguous subsequence
1310 * -> rf must be same thread as release */
1311 int tid = id_to_int(rf->get_tid());
1312 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1313 action_list_t *list = &(*thrd_lists)[tid];
1314 action_list_t::const_reverse_iterator rit;
1316 /* Find rf in the thread list */
1317 rit = std::find(list->rbegin(), list->rend(), rf);
1318 ASSERT(rit != list->rend());
1320 /* Find the last write/release */
1321 for (; rit != list->rend(); rit++)
1322 if ((*rit)->is_release())
1324 if (rit == list->rend()) {
1325 /* No write-release in this thread */
1326 return true; /* complete */
1328 ModelAction *release = *rit;
1330 ASSERT(rf->same_thread(release));
1332 pending->writes.clear();
1334 bool certain = true;
1335 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1336 if (id_to_int(rf->get_tid()) == (int)i)
1338 list = &(*thrd_lists)[i];
1340 /* Can we ensure no future writes from this thread may break
1341 * the release seq? */
1342 bool future_ordered = false;
1344 ModelAction *last = get_last_action(int_to_id(i));
1345 Thread *th = get_thread(int_to_id(i));
1346 if ((last && rf->happens_before(last)) ||
1347 !scheduler->is_enabled(th) ||
1349 future_ordered = true;
1351 ASSERT(!th->is_model_thread() || future_ordered);
1353 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1354 const ModelAction *act = *rit;
1355 /* Reach synchronization -> this thread is complete */
1356 if (act->happens_before(release))
1358 if (rf->happens_before(act)) {
1359 future_ordered = true;
1363 /* Only writes can break release sequences */
1364 if (!act->is_write())
1367 /* Check modification order */
1368 if (mo_graph->checkReachable(rf, act)) {
1369 /* rf --mo--> act */
1370 future_ordered = true;
1373 if (mo_graph->checkReachable(act, release))
1374 /* act --mo--> release */
1376 if (mo_graph->checkReachable(release, act) &&
1377 mo_graph->checkReachable(act, rf)) {
1378 /* release --mo-> act --mo--> rf */
1379 return true; /* complete */
1381 /* act may break release sequence */
1382 pending->writes.push_back(act);
1385 if (!future_ordered)
1386 certain = false; /* This thread is uncertain */
1390 release_heads->push_back(release);
1391 pending->writes.clear();
1393 pending->release = release;
1400 * A public interface for getting the release sequence head(s) with which a
1401 * given ModelAction must synchronize. This function only returns a non-empty
1402 * result when it can locate a release sequence head with certainty. Otherwise,
1403 * it may mark the internal state of the ModelChecker so that it will handle
1404 * the release sequence at a later time, causing @a act to update its
1405 * synchronization at some later point in execution.
1406 * @param act The 'acquire' action that may read from a release sequence
1407 * @param release_heads A pass-by-reference return parameter. Will be filled
1408 * with the head(s) of the release sequence(s), if they exists with certainty.
1409 * @see ModelChecker::release_seq_heads
1411 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1413 const ModelAction *rf = act->get_reads_from();
1414 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1415 sequence->acquire = act;
1417 if (!release_seq_heads(rf, release_heads, sequence)) {
1418 /* add act to 'lazy checking' list */
1419 pending_rel_seqs->push_back(sequence);
1421 snapshot_free(sequence);
1426 * Attempt to resolve all stashed operations that might synchronize with a
1427 * release sequence for a given location. This implements the "lazy" portion of
1428 * determining whether or not a release sequence was contiguous, since not all
1429 * modification order information is present at the time an action occurs.
1431 * @param location The location/object that should be checked for release
1432 * sequence resolutions. A NULL value means to check all locations.
1433 * @param work_queue The work queue to which to add work items as they are
1435 * @return True if any updates occurred (new synchronization, new mo_graph
1438 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1440 bool updated = false;
1441 std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1442 while (it != pending_rel_seqs->end()) {
1443 struct release_seq *pending = *it;
1444 ModelAction *act = pending->acquire;
1446 /* Only resolve sequences on the given location, if provided */
1447 if (location && act->get_location() != location) {
1452 const ModelAction *rf = act->get_reads_from();
1453 rel_heads_list_t release_heads;
1455 complete = release_seq_heads(rf, &release_heads, pending);
1456 for (unsigned int i = 0; i < release_heads.size(); i++) {
1457 if (!act->has_synchronized_with(release_heads[i])) {
1458 if (act->synchronize_with(release_heads[i]))
1461 set_bad_synchronization();
1466 /* Re-check all pending release sequences */
1467 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1468 /* Re-check act for mo_graph edges */
1469 work_queue->push_back(MOEdgeWorkEntry(act));
1471 /* propagate synchronization to later actions */
1472 action_list_t::reverse_iterator rit = action_trace->rbegin();
1473 for (; (*rit) != act; rit++) {
1474 ModelAction *propagate = *rit;
1475 if (act->happens_before(propagate)) {
1476 propagate->synchronize_with(act);
1477 /* Re-check 'propagate' for mo_graph edges */
1478 work_queue->push_back(MOEdgeWorkEntry(propagate));
1483 it = pending_rel_seqs->erase(it);
1484 snapshot_free(pending);
1490 // If we resolved promises or data races, see if we have realized a data race.
1491 if (checkDataRaces()) {
1499 * Performs various bookkeeping operations for the current ModelAction. For
1500 * instance, adds action to the per-object, per-thread action vector and to the
1501 * action trace list of all thread actions.
1503 * @param act is the ModelAction to add.
1505 void ModelChecker::add_action_to_lists(ModelAction *act)
1507 int tid = id_to_int(act->get_tid());
1508 action_trace->push_back(act);
1510 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1512 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1513 if (tid >= (int)vec->size())
1514 vec->resize(priv->next_thread_id);
1515 (*vec)[tid].push_back(act);
1517 if ((int)thrd_last_action->size() <= tid)
1518 thrd_last_action->resize(get_num_threads());
1519 (*thrd_last_action)[tid] = act;
1523 * @brief Get the last action performed by a particular Thread
1524 * @param tid The thread ID of the Thread in question
1525 * @return The last action in the thread
1527 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1529 int threadid = id_to_int(tid);
1530 if (threadid < (int)thrd_last_action->size())
1531 return (*thrd_last_action)[id_to_int(tid)];
1537 * Gets the last memory_order_seq_cst write (in the total global sequence)
1538 * performed on a particular object (i.e., memory location), not including the
1540 * @param curr The current ModelAction; also denotes the object location to
1542 * @return The last seq_cst write
1544 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1546 void *location = curr->get_location();
1547 action_list_t *list = obj_map->get_safe_ptr(location);
1548 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1549 action_list_t::reverse_iterator rit;
1550 for (rit = list->rbegin(); rit != list->rend(); rit++)
1551 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1557 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1558 * location). This function identifies the mutex according to the current
1559 * action, which is presumed to perform on the same mutex.
1560 * @param curr The current ModelAction; also denotes the object location to
1562 * @return The last unlock operation
1564 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1566 void *location = curr->get_location();
1567 action_list_t *list = obj_map->get_safe_ptr(location);
1568 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1569 action_list_t::reverse_iterator rit;
1570 for (rit = list->rbegin(); rit != list->rend(); rit++)
1571 if ((*rit)->is_unlock())
1576 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1578 ModelAction *parent = get_last_action(tid);
1580 parent = get_thread(tid)->get_creation();
1585 * Returns the clock vector for a given thread.
1586 * @param tid The thread whose clock vector we want
1587 * @return Desired clock vector
1589 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1591 return get_parent_action(tid)->get_cv();
1595 * Resolve a set of Promises with a current write. The set is provided in the
1596 * Node corresponding to @a write.
1597 * @param write The ModelAction that is fulfilling Promises
1598 * @return True if promises were resolved; false otherwise
1600 bool ModelChecker::resolve_promises(ModelAction *write)
1602 bool resolved = false;
1603 std::vector<thread_id_t> threads_to_check;
1605 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1606 Promise *promise = (*promises)[promise_index];
1607 if (write->get_node()->get_promise(i)) {
1608 ModelAction *read = promise->get_action();
1609 if (read->is_rmw()) {
1610 mo_graph->addRMWEdge(write, read);
1612 read->read_from(write);
1613 //First fix up the modification order for actions that happened
1615 r_modification_order(read, write);
1616 //Next fix up the modification order for actions that happened
1618 post_r_modification_order(read, write);
1619 //Make sure the promise's value matches the write's value
1620 ASSERT(promise->get_value() == write->get_value());
1623 promises->erase(promises->begin() + promise_index);
1624 threads_to_check.push_back(read->get_tid());
1631 //Check whether reading these writes has made threads unable to
1634 for(unsigned int i=0;i<threads_to_check.size();i++)
1635 mo_check_promises(threads_to_check[i], write);
1641 * Compute the set of promises that could potentially be satisfied by this
1642 * action. Note that the set computation actually appears in the Node, not in
1644 * @param curr The ModelAction that may satisfy promises
1646 void ModelChecker::compute_promises(ModelAction *curr)
1648 for (unsigned int i = 0; i < promises->size(); i++) {
1649 Promise *promise = (*promises)[i];
1650 const ModelAction *act = promise->get_action();
1651 if (!act->happens_before(curr) &&
1653 !act->could_synchronize_with(curr) &&
1654 !act->same_thread(curr) &&
1655 promise->get_value() == curr->get_value()) {
1656 curr->get_node()->set_promise(i);
1661 /** Checks promises in response to change in ClockVector Threads. */
1662 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1664 for (unsigned int i = 0; i < promises->size(); i++) {
1665 Promise *promise = (*promises)[i];
1666 const ModelAction *act = promise->get_action();
1667 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1668 merge_cv->synchronized_since(act)) {
1669 if (promise->increment_threads(tid)) {
1670 //Promise has failed
1671 failed_promise = true;
1678 /** Checks promises in response to addition to modification order for threads.
1680 * pthread is the thread that performed the read that created the promise
1682 * pread is the read that created the promise
1684 * pwrite is either the first write to same location as pread by
1685 * pthread that is sequenced after pread or the value read by the
1686 * first read to the same lcoation as pread by pthread that is
1687 * sequenced after pread..
1689 * 1. If tid=pthread, then we check what other threads are reachable
1690 * through the mode order starting with pwrite. Those threads cannot
1691 * perform a write that will resolve the promise due to modification
1692 * order constraints.
1694 * 2. If the tid is not pthread, we check whether pwrite can reach the
1695 * action write through the modification order. If so, that thread
1696 * cannot perform a future write that will resolve the promise due to
1697 * modificatin order constraints.
1699 * @parem tid The thread that either read from the model action
1700 * write, or actually did the model action write.
1702 * @parem write The ModelAction representing the relevant write.
1705 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1706 void * location = write->get_location();
1707 for (unsigned int i = 0; i < promises->size(); i++) {
1708 Promise *promise = (*promises)[i];
1709 const ModelAction *act = promise->get_action();
1711 //Is this promise on the same location?
1712 if ( act->get_location() != location )
1715 //same thread as the promise
1716 if ( act->get_tid()==tid ) {
1718 //do we have a pwrite for the promise, if not, set it
1719 if (promise->get_write() == NULL ) {
1720 promise->set_write(write);
1722 if (mo_graph->checkPromise(write, promise)) {
1723 failed_promise = true;
1728 //Don't do any lookups twice for the same thread
1729 if (promise->has_sync_thread(tid))
1732 if (mo_graph->checkReachable(promise->get_write(), write)) {
1733 if (promise->increment_threads(tid)) {
1734 failed_promise = true;
1742 * Compute the set of writes that may break the current pending release
1743 * sequence. This information is extracted from previou release sequence
1746 * @param curr The current ModelAction. Must be a release sequence fixup
1749 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1751 if (pending_rel_seqs->empty())
1754 struct release_seq *pending = pending_rel_seqs->back();
1755 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1756 const ModelAction *write = pending->writes[i];
1757 curr->get_node()->add_relseq_break(write);
1760 /* NULL means don't break the sequence; just synchronize */
1761 curr->get_node()->add_relseq_break(NULL);
1765 * Build up an initial set of all past writes that this 'read' action may read
1766 * from. This set is determined by the clock vector's "happens before"
1768 * @param curr is the current ModelAction that we are exploring; it must be a
1771 void ModelChecker::build_reads_from_past(ModelAction *curr)
1773 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1775 ASSERT(curr->is_read());
1777 ModelAction *last_seq_cst = NULL;
1779 /* Track whether this object has been initialized */
1780 bool initialized = false;
1782 if (curr->is_seqcst()) {
1783 last_seq_cst = get_last_seq_cst(curr);
1784 /* We have to at least see the last sequentially consistent write,
1785 so we are initialized. */
1786 if (last_seq_cst != NULL)
1790 /* Iterate over all threads */
1791 for (i = 0; i < thrd_lists->size(); i++) {
1792 /* Iterate over actions in thread, starting from most recent */
1793 action_list_t *list = &(*thrd_lists)[i];
1794 action_list_t::reverse_iterator rit;
1795 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1796 ModelAction *act = *rit;
1798 /* Only consider 'write' actions */
1799 if (!act->is_write() || act == curr)
1802 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1803 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1804 DEBUG("Adding action to may_read_from:\n");
1805 if (DBG_ENABLED()) {
1809 curr->get_node()->add_read_from(act);
1812 /* Include at most one act per-thread that "happens before" curr */
1813 if (act->happens_before(curr)) {
1821 /** @todo Need a more informative way of reporting errors. */
1822 printf("ERROR: may read from uninitialized atomic\n");
1825 if (DBG_ENABLED() || !initialized) {
1826 printf("Reached read action:\n");
1828 printf("Printing may_read_from\n");
1829 curr->get_node()->print_may_read_from();
1830 printf("End printing may_read_from\n");
1833 ASSERT(initialized);
1836 static void print_list(action_list_t *list)
1838 action_list_t::iterator it;
1840 printf("---------------------------------------------------------------------\n");
1843 for (it = list->begin(); it != list->end(); it++) {
1846 printf("---------------------------------------------------------------------\n");
1849 #if SUPPORT_MOD_ORDER_DUMP
1850 void ModelChecker::dumpGraph(char *filename) {
1852 sprintf(buffer, "%s.dot",filename);
1853 FILE *file=fopen(buffer, "w");
1854 fprintf(file, "digraph %s {\n",filename);
1855 mo_graph->dumpNodes(file);
1856 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1858 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1859 ModelAction *action=*it;
1860 if (action->is_read()) {
1861 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1862 if (action->get_reads_from()!=NULL)
1863 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1865 if (thread_array[action->get_tid()] != NULL) {
1866 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1869 thread_array[action->get_tid()]=action;
1871 fprintf(file,"}\n");
1872 model_free(thread_array);
1877 void ModelChecker::print_summary()
1880 printf("Number of executions: %d\n", num_executions);
1881 printf("Number of feasible executions: %d\n", num_feasible_executions);
1882 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1884 #if SUPPORT_MOD_ORDER_DUMP
1886 char buffername[100];
1887 sprintf(buffername, "exec%04u", num_executions);
1888 mo_graph->dumpGraphToFile(buffername);
1889 sprintf(buffername, "graph%04u", num_executions);
1890 dumpGraph(buffername);
1893 if (!isfinalfeasible())
1894 printf("INFEASIBLE EXECUTION!\n");
1895 print_list(action_trace);
1900 * Add a Thread to the system for the first time. Should only be called once
1902 * @param t The Thread to add
1904 void ModelChecker::add_thread(Thread *t)
1906 thread_map->put(id_to_int(t->get_id()), t);
1907 scheduler->add_thread(t);
1911 * Removes a thread from the scheduler.
1912 * @param the thread to remove.
1914 void ModelChecker::remove_thread(Thread *t)
1916 scheduler->remove_thread(t);
1920 * @brief Get a Thread reference by its ID
1921 * @param tid The Thread's ID
1922 * @return A Thread reference
1924 Thread * ModelChecker::get_thread(thread_id_t tid) const
1926 return thread_map->get(id_to_int(tid));
1930 * @brief Get a reference to the Thread in which a ModelAction was executed
1931 * @param act The ModelAction
1932 * @return A Thread reference
1934 Thread * ModelChecker::get_thread(ModelAction *act) const
1936 return get_thread(act->get_tid());
1940 * Switch from a user-context to the "master thread" context (a.k.a. system
1941 * context). This switch is made with the intention of exploring a particular
1942 * model-checking action (described by a ModelAction object). Must be called
1943 * from a user-thread context.
1945 * @param act The current action that will be explored. May be NULL only if
1946 * trace is exiting via an assertion (see ModelChecker::set_assert and
1947 * ModelChecker::has_asserted).
1948 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1950 int ModelChecker::switch_to_master(ModelAction *act)
1953 Thread *old = thread_current();
1954 set_current_action(act);
1955 old->set_state(THREAD_READY);
1956 return Thread::swap(old, &system_context);
1960 * Takes the next step in the execution, if possible.
1961 * @return Returns true (success) if a step was taken and false otherwise.
1963 bool ModelChecker::take_step() {
1967 Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1969 if (curr->get_state() == THREAD_READY) {
1970 ASSERT(priv->current_action);
1972 priv->nextThread = check_current_action(priv->current_action);
1973 priv->current_action = NULL;
1975 if (curr->is_blocked() || curr->is_complete())
1976 scheduler->remove_thread(curr);
1981 Thread *next = scheduler->next_thread(priv->nextThread);
1983 /* Infeasible -> don't take any more steps */
1987 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1988 next ? id_to_int(next->get_id()) : -1);
1991 * Launch end-of-execution release sequence fixups only when there are:
1993 * (1) no more user threads to run (or when execution replay chooses
1994 * the 'model_thread')
1995 * (2) pending release sequences
1996 * (3) pending assertions (i.e., data races)
1997 * (4) no pending promises
1999 if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
2000 isfinalfeasible() && !unrealizedraces.empty()) {
2001 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
2002 pending_rel_seqs->size());
2003 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2004 std::memory_order_seq_cst, NULL, VALUE_NONE,
2006 set_current_action(fixup);
2010 /* next == NULL -> don't take any more steps */
2014 next->set_state(THREAD_RUNNING);
2016 if (next->get_pending() != NULL) {
2017 /* restart a pending action */
2018 set_current_action(next->get_pending());
2019 next->set_pending(NULL);
2020 next->set_state(THREAD_READY);
2024 /* Return false only if swap fails with an error */
2025 return (Thread::swap(&system_context, next) == 0);
2028 /** Runs the current execution until threre are no more steps to take. */
2029 void ModelChecker::finish_execution() {
2032 while (take_step());