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;
52 /** @brief Destructor */
53 ModelChecker::~ModelChecker()
55 for (unsigned int i = 0; i < get_num_threads(); i++)
56 delete thread_map->get(i);
61 delete lock_waiters_map;
64 for (unsigned int i = 0; i < promises->size(); i++)
65 delete (*promises)[i];
68 delete pending_rel_seqs;
70 delete thrd_last_action;
77 * Restores user program to initial state and resets all model-checker data
80 void ModelChecker::reset_to_initial_state()
82 DEBUG("+++ Resetting to initial state +++\n");
83 node_stack->reset_execution();
84 failed_promise = false;
85 too_many_reads = false;
86 bad_synchronization = false;
88 snapshotObject->backTrackBeforeStep(0);
91 /** @return a thread ID for a new Thread */
92 thread_id_t ModelChecker::get_next_id()
94 return priv->next_thread_id++;
97 /** @return the number of user threads created during this execution */
98 unsigned int ModelChecker::get_num_threads()
100 return priv->next_thread_id;
103 /** @return The currently executing Thread. */
104 Thread * ModelChecker::get_current_thread()
106 return scheduler->get_current_thread();
109 /** @return a sequence number for a new ModelAction */
110 modelclock_t ModelChecker::get_next_seq_num()
112 return ++priv->used_sequence_numbers;
116 * @brief Choose the next thread to execute.
118 * This function chooses the next thread that should execute. It can force the
119 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
120 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
121 * The model-checker may have no preference regarding the next thread (i.e.,
122 * when exploring a new execution ordering), in which case this will return
124 * @param curr The current ModelAction. This action might guide the choice of
126 * @return The next thread to run. If the model-checker has no preference, NULL.
128 Thread * ModelChecker::get_next_thread(ModelAction *curr)
133 /* Do not split atomic actions. */
135 return thread_current();
136 /* The THREAD_CREATE action points to the created Thread */
137 else if (curr->get_type() == THREAD_CREATE)
138 return (Thread *)curr->get_location();
141 /* Have we completed exploring the preselected path? */
145 /* Else, we are trying to replay an execution */
146 ModelAction *next = node_stack->get_next()->get_action();
148 if (next == diverge) {
149 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
150 earliest_diverge=diverge;
152 Node *nextnode = next->get_node();
153 /* Reached divergence point */
154 if (nextnode->increment_promise()) {
155 /* The next node will try to satisfy a different set of promises. */
156 tid = next->get_tid();
157 node_stack->pop_restofstack(2);
158 } else if (nextnode->increment_read_from()) {
159 /* The next node will read from a different value. */
160 tid = next->get_tid();
161 node_stack->pop_restofstack(2);
162 } else if (nextnode->increment_future_value()) {
163 /* The next node will try to read from a different future value. */
164 tid = next->get_tid();
165 node_stack->pop_restofstack(2);
166 } else if (nextnode->increment_relseq_break()) {
167 /* The next node will try to resolve a release sequence differently */
168 tid = next->get_tid();
169 node_stack->pop_restofstack(2);
171 /* Make a different thread execute for next step */
172 Node *node = nextnode->get_parent();
173 tid = node->get_next_backtrack();
174 node_stack->pop_restofstack(1);
175 if (diverge==earliest_diverge) {
176 earliest_diverge=node->get_action();
179 DEBUG("*** Divergence point ***\n");
183 tid = next->get_tid();
185 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
186 ASSERT(tid != THREAD_ID_T_NONE);
187 return thread_map->get(id_to_int(tid));
191 * Queries the model-checker for more executions to explore and, if one
192 * exists, resets the model-checker state to execute a new execution.
194 * @return If there are more executions to explore, return true. Otherwise,
197 bool ModelChecker::next_execution()
203 if (isfinalfeasible()) {
204 printf("Earliest divergence point since last feasible execution:\n");
205 if (earliest_diverge)
206 earliest_diverge->print();
208 printf("(Not set)\n");
210 earliest_diverge = NULL;
211 num_feasible_executions++;
214 DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
215 pending_rel_seqs->size());
217 if (isfinalfeasible() || DBG_ENABLED())
220 if ((diverge = get_next_backtrack()) == NULL)
224 printf("Next execution will diverge at:\n");
228 reset_to_initial_state();
232 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
234 switch (act->get_type()) {
238 /* linear search: from most recent to oldest */
239 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
240 action_list_t::reverse_iterator rit;
241 for (rit = list->rbegin(); rit != list->rend(); rit++) {
242 ModelAction *prev = *rit;
243 if (prev->could_synchronize_with(act))
249 case ATOMIC_TRYLOCK: {
250 /* linear search: from most recent to oldest */
251 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
252 action_list_t::reverse_iterator rit;
253 for (rit = list->rbegin(); rit != list->rend(); rit++) {
254 ModelAction *prev = *rit;
255 if (act->is_conflicting_lock(prev))
260 case ATOMIC_UNLOCK: {
261 /* linear search: from most recent to oldest */
262 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
263 action_list_t::reverse_iterator rit;
264 for (rit = list->rbegin(); rit != list->rend(); rit++) {
265 ModelAction *prev = *rit;
266 if (!act->same_thread(prev)&&prev->is_failed_trylock())
277 /** This method find backtracking points where we should try to
278 * reorder the parameter ModelAction against.
280 * @param the ModelAction to find backtracking points for.
282 void ModelChecker::set_backtracking(ModelAction *act)
284 Thread *t = get_thread(act);
285 ModelAction * prev = get_last_conflict(act);
289 Node * node = prev->get_node()->get_parent();
291 int low_tid, high_tid;
292 if (node->is_enabled(t)) {
293 low_tid = id_to_int(act->get_tid());
294 high_tid = low_tid+1;
297 high_tid = get_num_threads();
300 for(int i = low_tid; i < high_tid; i++) {
301 thread_id_t tid = int_to_id(i);
302 if (!node->is_enabled(tid))
305 /* Check if this has been explored already */
306 if (node->has_been_explored(tid))
309 /* See if fairness allows */
310 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
312 for(int t=0;t<node->get_num_threads();t++) {
313 thread_id_t tother=int_to_id(t);
314 if (node->is_enabled(tother) && node->has_priority(tother)) {
323 /* Cache the latest backtracking point */
324 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
325 priv->next_backtrack = prev;
327 /* If this is a new backtracking point, mark the tree */
328 if (!node->set_backtrack(tid))
330 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
331 id_to_int(prev->get_tid()),
332 id_to_int(t->get_id()));
341 * Returns last backtracking point. The model checker will explore a different
342 * path for this point in the next execution.
343 * @return The ModelAction at which the next execution should diverge.
345 ModelAction * ModelChecker::get_next_backtrack()
347 ModelAction *next = priv->next_backtrack;
348 priv->next_backtrack = NULL;
353 * Processes a read or rmw model action.
354 * @param curr is the read model action to process.
355 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
356 * @return True if processing this read updates the mo_graph.
358 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
361 bool updated = false;
363 const ModelAction *reads_from = curr->get_node()->get_read_from();
364 if (reads_from != NULL) {
365 mo_graph->startChanges();
367 value = reads_from->get_value();
368 bool r_status = false;
370 if (!second_part_of_rmw) {
371 check_recency(curr, reads_from);
372 r_status = r_modification_order(curr, reads_from);
376 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
377 mo_graph->rollbackChanges();
378 too_many_reads = false;
382 curr->read_from(reads_from);
383 mo_graph->commitChanges();
384 mo_check_promises(curr->get_tid(), reads_from);
387 } else if (!second_part_of_rmw) {
388 /* Read from future value */
389 value = curr->get_node()->get_future_value();
390 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
391 curr->read_from(NULL);
392 Promise *valuepromise = new Promise(curr, value, expiration);
393 promises->push_back(valuepromise);
395 get_thread(curr)->set_return_value(value);
401 * Processes a lock, trylock, or unlock model action. @param curr is
402 * the read model action to process.
404 * The try lock operation checks whether the lock is taken. If not,
405 * it falls to the normal lock operation case. If so, it returns
408 * The lock operation has already been checked that it is enabled, so
409 * it just grabs the lock and synchronizes with the previous unlock.
411 * The unlock operation has to re-enable all of the threads that are
412 * waiting on the lock.
414 * @return True if synchronization was updated; false otherwise
416 bool ModelChecker::process_mutex(ModelAction *curr) {
417 std::mutex *mutex = (std::mutex *)curr->get_location();
418 struct std::mutex_state *state = mutex->get_state();
419 switch (curr->get_type()) {
420 case ATOMIC_TRYLOCK: {
421 bool success = !state->islocked;
422 curr->set_try_lock(success);
424 get_thread(curr)->set_return_value(0);
427 get_thread(curr)->set_return_value(1);
429 //otherwise fall into the lock case
431 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
432 printf("Lock access before initialization\n");
435 state->islocked = true;
436 ModelAction *unlock = get_last_unlock(curr);
437 //synchronize with the previous unlock statement
438 if (unlock != NULL) {
439 curr->synchronize_with(unlock);
444 case ATOMIC_UNLOCK: {
446 state->islocked = false;
447 //wake up the other threads
448 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
449 //activate all the waiting threads
450 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
451 scheduler->wake(get_thread(*rit));
463 * Process a write ModelAction
464 * @param curr The ModelAction to process
465 * @return True if the mo_graph was updated or promises were resolved
467 bool ModelChecker::process_write(ModelAction *curr)
469 bool updated_mod_order = w_modification_order(curr);
470 bool updated_promises = resolve_promises(curr);
472 if (promises->size() == 0) {
473 for (unsigned int i = 0; i < futurevalues->size(); i++) {
474 struct PendingFutureValue pfv = (*futurevalues)[i];
475 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
476 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
477 priv->next_backtrack = pfv.act;
479 futurevalues->resize(0);
482 mo_graph->commitChanges();
483 mo_check_promises(curr->get_tid(), curr);
485 get_thread(curr)->set_return_value(VALUE_NONE);
486 return updated_mod_order || updated_promises;
490 * @brief Process the current action for thread-related activity
492 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
493 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
494 * synchronization, etc. This function is a no-op for non-THREAD actions
495 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
497 * @param curr The current action
498 * @return True if synchronization was updated or a thread completed
500 bool ModelChecker::process_thread_action(ModelAction *curr)
502 bool updated = false;
504 switch (curr->get_type()) {
505 case THREAD_CREATE: {
506 Thread *th = (Thread *)curr->get_location();
507 th->set_creation(curr);
511 Thread *waiting, *blocking;
512 waiting = get_thread(curr);
513 blocking = (Thread *)curr->get_location();
514 if (!blocking->is_complete()) {
515 blocking->push_wait_list(curr);
516 scheduler->sleep(waiting);
518 do_complete_join(curr);
519 updated = true; /* trigger rel-seq checks */
523 case THREAD_FINISH: {
524 Thread *th = get_thread(curr);
525 while (!th->wait_list_empty()) {
526 ModelAction *act = th->pop_wait_list();
527 Thread *wake = get_thread(act);
528 scheduler->wake(wake);
529 do_complete_join(act);
530 updated = true; /* trigger rel-seq checks */
533 updated = true; /* trigger rel-seq checks */
537 check_promises(curr->get_tid(), NULL, curr->get_cv());
548 * @brief Process the current action for release sequence fixup activity
550 * Performs model-checker release sequence fixups for the current action,
551 * forcing a single pending release sequence to break (with a given, potential
552 * "loose" write) or to complete (i.e., synchronize). If a pending release
553 * sequence forms a complete release sequence, then we must perform the fixup
554 * synchronization, mo_graph additions, etc.
556 * @param curr The current action; must be a release sequence fixup action
557 * @param work_queue The work queue to which to add work items as they are
560 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
562 const ModelAction *write = curr->get_node()->get_relseq_break();
563 struct release_seq *sequence = pending_rel_seqs->back();
564 pending_rel_seqs->pop_back();
566 ModelAction *acquire = sequence->acquire;
567 const ModelAction *rf = sequence->rf;
568 const ModelAction *release = sequence->release;
572 ASSERT(release->same_thread(rf));
575 /* Must synchronize */
576 if (!acquire->synchronize_with(release)) {
577 set_bad_synchronization();
580 /* Re-check all pending release sequences */
581 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
582 /* Re-check act for mo_graph edges */
583 work_queue->push_back(MOEdgeWorkEntry(acquire));
585 /* propagate synchronization to later actions */
586 action_list_t::reverse_iterator rit = action_trace->rbegin();
587 for (; (*rit) != acquire; rit++) {
588 ModelAction *propagate = *rit;
589 if (acquire->happens_before(propagate)) {
590 propagate->synchronize_with(acquire);
591 /* Re-check 'propagate' for mo_graph edges */
592 work_queue->push_back(MOEdgeWorkEntry(propagate));
596 /* Break release sequence with new edges:
597 * release --mo--> write --mo--> rf */
598 mo_graph->addEdge(release, write);
599 mo_graph->addEdge(write, rf);
604 * Initialize the current action by performing one or more of the following
605 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
606 * in the NodeStack, manipulating backtracking sets, allocating and
607 * initializing clock vectors, and computing the promises to fulfill.
609 * @param curr The current action, as passed from the user context; may be
610 * freed/invalidated after the execution of this function
611 * @return The current action, as processed by the ModelChecker. Is only the
612 * same as the parameter @a curr if this is a newly-explored action.
614 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
616 ModelAction *newcurr;
618 if (curr->is_rmwc() || curr->is_rmw()) {
619 newcurr = process_rmw(curr);
622 if (newcurr->is_rmw())
623 compute_promises(newcurr);
627 curr->set_seq_number(get_next_seq_num());
629 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
631 /* First restore type and order in case of RMW operation */
633 newcurr->copy_typeandorder(curr);
635 ASSERT(curr->get_location() == newcurr->get_location());
636 newcurr->copy_from_new(curr);
638 /* Discard duplicate ModelAction; use action from NodeStack */
641 /* Always compute new clock vector */
642 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
646 /* Always compute new clock vector */
647 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
649 * Perform one-time actions when pushing new ModelAction onto
652 if (newcurr->is_write())
653 compute_promises(newcurr);
654 else if (newcurr->is_relseq_fixup())
655 compute_relseq_breakwrites(newcurr);
661 * This method checks whether a model action is enabled at the given point.
662 * At this point, it checks whether a lock operation would be successful at this point.
663 * If not, it puts the thread in a waiter list.
664 * @param curr is the ModelAction to check whether it is enabled.
665 * @return a bool that indicates whether the action is enabled.
667 bool ModelChecker::check_action_enabled(ModelAction *curr) {
668 if (curr->is_lock()) {
669 std::mutex * lock = (std::mutex *)curr->get_location();
670 struct std::mutex_state * state = lock->get_state();
671 if (state->islocked) {
672 //Stick the action in the appropriate waiting queue
673 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
682 * This is the heart of the model checker routine. It performs model-checking
683 * actions corresponding to a given "current action." Among other processes, it
684 * calculates reads-from relationships, updates synchronization clock vectors,
685 * forms a memory_order constraints graph, and handles replay/backtrack
686 * execution when running permutations of previously-observed executions.
688 * @param curr The current action to process
689 * @return The next Thread that must be executed. May be NULL if ModelChecker
690 * makes no choice (e.g., according to replay execution, combining RMW actions,
693 Thread * ModelChecker::check_current_action(ModelAction *curr)
697 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
699 if (!check_action_enabled(curr)) {
700 /* Make the execution look like we chose to run this action
701 * much later, when a lock is actually available to release */
702 get_current_thread()->set_pending(curr);
703 scheduler->sleep(get_current_thread());
704 return get_next_thread(NULL);
707 ModelAction *newcurr = initialize_curr_action(curr);
709 /* Add the action to lists before any other model-checking tasks */
710 if (!second_part_of_rmw)
711 add_action_to_lists(newcurr);
713 /* Build may_read_from set for newly-created actions */
714 if (curr == newcurr && curr->is_read())
715 build_reads_from_past(curr);
718 /* Initialize work_queue with the "current action" work */
719 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
721 while (!work_queue.empty()) {
722 WorkQueueEntry work = work_queue.front();
723 work_queue.pop_front();
726 case WORK_CHECK_CURR_ACTION: {
727 ModelAction *act = work.action;
728 bool update = false; /* update this location's release seq's */
729 bool update_all = false; /* update all release seq's */
731 if (process_thread_action(curr))
734 if (act->is_read() && process_read(act, second_part_of_rmw))
737 if (act->is_write() && process_write(act))
740 if (act->is_mutex_op() && process_mutex(act))
743 if (act->is_relseq_fixup())
744 process_relseq_fixup(curr, &work_queue);
747 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
749 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
752 case WORK_CHECK_RELEASE_SEQ:
753 resolve_release_sequences(work.location, &work_queue);
755 case WORK_CHECK_MO_EDGES: {
756 /** @todo Complete verification of work_queue */
757 ModelAction *act = work.action;
758 bool updated = false;
760 if (act->is_read()) {
761 const ModelAction *rf = act->get_reads_from();
762 if (rf != NULL && r_modification_order(act, rf))
765 if (act->is_write()) {
766 if (w_modification_order(act))
769 mo_graph->commitChanges();
772 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
781 check_curr_backtracking(curr);
783 set_backtracking(curr);
785 return get_next_thread(curr);
789 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
790 * operation from the Thread it is joining with. Must be called after the
791 * completion of the Thread in question.
792 * @param join The THREAD_JOIN action
794 void ModelChecker::do_complete_join(ModelAction *join)
796 Thread *blocking = (Thread *)join->get_location();
797 ModelAction *act = get_last_action(blocking->get_id());
798 join->synchronize_with(act);
801 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
802 Node *currnode = curr->get_node();
803 Node *parnode = currnode->get_parent();
805 if ((!parnode->backtrack_empty() ||
806 !currnode->read_from_empty() ||
807 !currnode->future_value_empty() ||
808 !currnode->promise_empty() ||
809 !currnode->relseq_break_empty())
810 && (!priv->next_backtrack ||
811 *curr > *priv->next_backtrack)) {
812 priv->next_backtrack = curr;
816 bool ModelChecker::promises_expired() {
817 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
818 Promise *promise = (*promises)[promise_index];
819 if (promise->get_expiration()<priv->used_sequence_numbers) {
826 /** @return whether the current partial trace must be a prefix of a
828 bool ModelChecker::isfeasibleprefix() {
829 return promises->size() == 0 && pending_rel_seqs->size() == 0;
832 /** @return whether the current partial trace is feasible. */
833 bool ModelChecker::isfeasible() {
834 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
835 DEBUG("Infeasible: RMW violation\n");
837 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
840 /** @return whether the current partial trace is feasible other than
841 * multiple RMW reading from the same store. */
842 bool ModelChecker::isfeasibleotherthanRMW() {
844 if (mo_graph->checkForCycles())
845 DEBUG("Infeasible: modification order cycles\n");
847 DEBUG("Infeasible: failed promise\n");
849 DEBUG("Infeasible: too many reads\n");
850 if (bad_synchronization)
851 DEBUG("Infeasible: bad synchronization ordering\n");
852 if (promises_expired())
853 DEBUG("Infeasible: promises expired\n");
855 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
858 /** Returns whether the current completed trace is feasible. */
859 bool ModelChecker::isfinalfeasible() {
860 if (DBG_ENABLED() && promises->size() != 0)
861 DEBUG("Infeasible: unrevolved promises\n");
863 return isfeasible() && promises->size() == 0;
866 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
867 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
868 ModelAction *lastread = get_last_action(act->get_tid());
869 lastread->process_rmw(act);
870 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
871 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
872 mo_graph->commitChanges();
878 * Checks whether a thread has read from the same write for too many times
879 * without seeing the effects of a later write.
882 * 1) there must a different write that we could read from that would satisfy the modification order,
883 * 2) we must have read from the same value in excess of maxreads times, and
884 * 3) that other write must have been in the reads_from set for maxreads times.
886 * If so, we decide that the execution is no longer feasible.
888 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
889 if (params.maxreads != 0) {
891 if (curr->get_node()->get_read_from_size() <= 1)
893 //Must make sure that execution is currently feasible... We could
894 //accidentally clear by rolling back
897 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
898 int tid = id_to_int(curr->get_tid());
901 if ((int)thrd_lists->size() <= tid)
903 action_list_t *list = &(*thrd_lists)[tid];
905 action_list_t::reverse_iterator rit = list->rbegin();
907 for (; (*rit) != curr; rit++)
909 /* go past curr now */
912 action_list_t::reverse_iterator ritcopy = rit;
913 //See if we have enough reads from the same value
915 for (; count < params.maxreads; rit++,count++) {
916 if (rit==list->rend())
918 ModelAction *act = *rit;
922 if (act->get_reads_from() != rf)
924 if (act->get_node()->get_read_from_size() <= 1)
927 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
929 const ModelAction * write = curr->get_node()->get_read_from_at(i);
931 //Need a different write
935 /* Test to see whether this is a feasible write to read from*/
936 mo_graph->startChanges();
937 r_modification_order(curr, write);
938 bool feasiblereadfrom = isfeasible();
939 mo_graph->rollbackChanges();
941 if (!feasiblereadfrom)
945 bool feasiblewrite = true;
946 //new we need to see if this write works for everyone
948 for (int loop = count; loop>0; loop--,rit++) {
949 ModelAction *act=*rit;
950 bool foundvalue = false;
951 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
952 if (act->get_node()->get_read_from_at(i)==write) {
958 feasiblewrite = false;
963 too_many_reads = true;
971 * Updates the mo_graph with the constraints imposed from the current
974 * Basic idea is the following: Go through each other thread and find
975 * the lastest action that happened before our read. Two cases:
977 * (1) The action is a write => that write must either occur before
978 * the write we read from or be the write we read from.
980 * (2) The action is a read => the write that that action read from
981 * must occur before the write we read from or be the same write.
983 * @param curr The current action. Must be a read.
984 * @param rf The action that curr reads from. Must be a write.
985 * @return True if modification order edges were added; false otherwise
987 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
989 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
992 ASSERT(curr->is_read());
994 /* Iterate over all threads */
995 for (i = 0; i < thrd_lists->size(); i++) {
996 /* Iterate over actions in thread, starting from most recent */
997 action_list_t *list = &(*thrd_lists)[i];
998 action_list_t::reverse_iterator rit;
999 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1000 ModelAction *act = *rit;
1003 * Include at most one act per-thread that "happens
1004 * before" curr. Don't consider reflexively.
1006 if (act->happens_before(curr) && act != curr) {
1007 if (act->is_write()) {
1009 mo_graph->addEdge(act, rf);
1013 const ModelAction *prevreadfrom = act->get_reads_from();
1014 //if the previous read is unresolved, keep going...
1015 if (prevreadfrom == NULL)
1018 if (rf != prevreadfrom) {
1019 mo_graph->addEdge(prevreadfrom, rf);
1031 /** This method fixes up the modification order when we resolve a
1032 * promises. The basic problem is that actions that occur after the
1033 * read curr could not property add items to the modification order
1036 * So for each thread, we find the earliest item that happens after
1037 * the read curr. This is the item we have to fix up with additional
1038 * constraints. If that action is write, we add a MO edge between
1039 * the Action rf and that action. If the action is a read, we add a
1040 * MO edge between the Action rf, and whatever the read accessed.
1042 * @param curr is the read ModelAction that we are fixing up MO edges for.
1043 * @param rf is the write ModelAction that curr reads from.
1046 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1048 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1050 ASSERT(curr->is_read());
1052 /* Iterate over all threads */
1053 for (i = 0; i < thrd_lists->size(); i++) {
1054 /* Iterate over actions in thread, starting from most recent */
1055 action_list_t *list = &(*thrd_lists)[i];
1056 action_list_t::reverse_iterator rit;
1057 ModelAction *lastact = NULL;
1059 /* Find last action that happens after curr that is either not curr or a rmw */
1060 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1061 ModelAction *act = *rit;
1062 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1068 /* Include at most one act per-thread that "happens before" curr */
1069 if (lastact != NULL) {
1070 if (lastact==curr) {
1071 //Case 1: The resolved read is a RMW, and we need to make sure
1072 //that the write portion of the RMW mod order after rf
1074 mo_graph->addEdge(rf, lastact);
1075 } else if (lastact->is_read()) {
1076 //Case 2: The resolved read is a normal read and the next
1077 //operation is a read, and we need to make sure the value read
1078 //is mod ordered after rf
1080 const ModelAction *postreadfrom = lastact->get_reads_from();
1081 if (postreadfrom != NULL&&rf != postreadfrom)
1082 mo_graph->addEdge(rf, postreadfrom);
1084 //Case 3: The resolved read is a normal read and the next
1085 //operation is a write, and we need to make sure that the
1086 //write is mod ordered after rf
1088 mo_graph->addEdge(rf, lastact);
1096 * Updates the mo_graph with the constraints imposed from the current write.
1098 * Basic idea is the following: Go through each other thread and find
1099 * the lastest action that happened before our write. Two cases:
1101 * (1) The action is a write => that write must occur before
1104 * (2) The action is a read => the write that that action read from
1105 * must occur before the current write.
1107 * This method also handles two other issues:
1109 * (I) Sequential Consistency: Making sure that if the current write is
1110 * seq_cst, that it occurs after the previous seq_cst write.
1112 * (II) Sending the write back to non-synchronizing reads.
1114 * @param curr The current action. Must be a write.
1115 * @return True if modification order edges were added; false otherwise
1117 bool ModelChecker::w_modification_order(ModelAction *curr)
1119 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1122 ASSERT(curr->is_write());
1124 if (curr->is_seqcst()) {
1125 /* We have to at least see the last sequentially consistent write,
1126 so we are initialized. */
1127 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1128 if (last_seq_cst != NULL) {
1129 mo_graph->addEdge(last_seq_cst, curr);
1134 /* Iterate over all threads */
1135 for (i = 0; i < thrd_lists->size(); i++) {
1136 /* Iterate over actions in thread, starting from most recent */
1137 action_list_t *list = &(*thrd_lists)[i];
1138 action_list_t::reverse_iterator rit;
1139 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1140 ModelAction *act = *rit;
1143 * 1) If RMW and it actually read from something, then we
1144 * already have all relevant edges, so just skip to next
1147 * 2) If RMW and it didn't read from anything, we should
1148 * whatever edge we can get to speed up convergence.
1150 * 3) If normal write, we need to look at earlier actions, so
1151 * continue processing list.
1153 if (curr->is_rmw()) {
1154 if (curr->get_reads_from()!=NULL)
1163 * Include at most one act per-thread that "happens
1166 if (act->happens_before(curr)) {
1168 * Note: if act is RMW, just add edge:
1170 * The following edge should be handled elsewhere:
1171 * readfrom(act) --mo--> act
1173 if (act->is_write())
1174 mo_graph->addEdge(act, curr);
1175 else if (act->is_read()) {
1176 //if previous read accessed a null, just keep going
1177 if (act->get_reads_from() == NULL)
1179 mo_graph->addEdge(act->get_reads_from(), curr);
1183 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1184 !act->same_thread(curr)) {
1185 /* We have an action that:
1186 (1) did not happen before us
1187 (2) is a read and we are a write
1188 (3) cannot synchronize with us
1189 (4) is in a different thread
1191 that read could potentially read from our write.
1193 if (thin_air_constraint_may_allow(curr, act)) {
1195 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1196 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1197 futurevalues->push_back(pfv);
1207 /** Arbitrary reads from the future are not allowed. Section 29.3
1208 * part 9 places some constraints. This method checks one result of constraint
1209 * constraint. Others require compiler support. */
1210 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1211 if (!writer->is_rmw())
1214 if (!reader->is_rmw())
1217 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1218 if (search == reader)
1220 if (search->get_tid() == reader->get_tid() &&
1221 search->happens_before(reader))
1229 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1230 * The ModelAction under consideration is expected to be taking part in
1231 * release/acquire synchronization as an object of the "reads from" relation.
1232 * Note that this can only provide release sequence support for RMW chains
1233 * which do not read from the future, as those actions cannot be traced until
1234 * their "promise" is fulfilled. Similarly, we may not even establish the
1235 * presence of a release sequence with certainty, as some modification order
1236 * constraints may be decided further in the future. Thus, this function
1237 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1238 * and a boolean representing certainty.
1240 * @todo Finish lazy updating, when promises are fulfilled in the future
1241 * @param rf The action that might be part of a release sequence. Must be a
1243 * @param release_heads A pass-by-reference style return parameter. After
1244 * execution of this function, release_heads will contain the heads of all the
1245 * relevant release sequences, if any exists with certainty
1246 * @param pending A pass-by-reference style return parameter which is only used
1247 * when returning false (i.e., uncertain). Returns most information regarding
1248 * an uncertain release sequence, including any write operations that might
1249 * break the sequence.
1250 * @return true, if the ModelChecker is certain that release_heads is complete;
1253 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1254 rel_heads_list_t *release_heads,
1255 struct release_seq *pending) const
1257 /* Only check for release sequences if there are no cycles */
1258 if (mo_graph->checkForCycles())
1262 ASSERT(rf->is_write());
1264 if (rf->is_release())
1265 release_heads->push_back(rf);
1267 break; /* End of RMW chain */
1269 /** @todo Need to be smarter here... In the linux lock
1270 * example, this will run to the beginning of the program for
1272 /** @todo The way to be smarter here is to keep going until 1
1273 * thread has a release preceded by an acquire and you've seen
1276 /* acq_rel RMW is a sufficient stopping condition */
1277 if (rf->is_acquire() && rf->is_release())
1278 return true; /* complete */
1280 rf = rf->get_reads_from();
1283 /* read from future: need to settle this later */
1285 return false; /* incomplete */
1288 if (rf->is_release())
1289 return true; /* complete */
1291 /* else relaxed write; check modification order for contiguous subsequence
1292 * -> rf must be same thread as release */
1293 int tid = id_to_int(rf->get_tid());
1294 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1295 action_list_t *list = &(*thrd_lists)[tid];
1296 action_list_t::const_reverse_iterator rit;
1298 /* Find rf in the thread list */
1299 rit = std::find(list->rbegin(), list->rend(), rf);
1300 ASSERT(rit != list->rend());
1302 /* Find the last write/release */
1303 for (; rit != list->rend(); rit++)
1304 if ((*rit)->is_release())
1306 if (rit == list->rend()) {
1307 /* No write-release in this thread */
1308 return true; /* complete */
1310 ModelAction *release = *rit;
1312 ASSERT(rf->same_thread(release));
1314 pending->writes.clear();
1316 bool certain = true;
1317 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1318 if (id_to_int(rf->get_tid()) == (int)i)
1320 list = &(*thrd_lists)[i];
1322 /* Can we ensure no future writes from this thread may break
1323 * the release seq? */
1324 bool future_ordered = false;
1326 ModelAction *last = get_last_action(int_to_id(i));
1327 Thread *th = get_thread(int_to_id(i));
1328 if ((last && rf->happens_before(last)) ||
1329 !scheduler->is_enabled(th) ||
1331 future_ordered = true;
1333 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1334 const ModelAction *act = *rit;
1335 /* Reach synchronization -> this thread is complete */
1336 if (act->happens_before(release))
1338 if (rf->happens_before(act)) {
1339 future_ordered = true;
1343 /* Only writes can break release sequences */
1344 if (!act->is_write())
1347 /* Check modification order */
1348 if (mo_graph->checkReachable(rf, act)) {
1349 /* rf --mo--> act */
1350 future_ordered = true;
1353 if (mo_graph->checkReachable(act, release))
1354 /* act --mo--> release */
1356 if (mo_graph->checkReachable(release, act) &&
1357 mo_graph->checkReachable(act, rf)) {
1358 /* release --mo-> act --mo--> rf */
1359 return true; /* complete */
1361 /* act may break release sequence */
1362 pending->writes.push_back(act);
1365 if (!future_ordered)
1366 certain = false; /* This thread is uncertain */
1370 release_heads->push_back(release);
1371 pending->writes.clear();
1373 pending->release = release;
1380 * A public interface for getting the release sequence head(s) with which a
1381 * given ModelAction must synchronize. This function only returns a non-empty
1382 * result when it can locate a release sequence head with certainty. Otherwise,
1383 * it may mark the internal state of the ModelChecker so that it will handle
1384 * the release sequence at a later time, causing @a act to update its
1385 * synchronization at some later point in execution.
1386 * @param act The 'acquire' action that may read from a release sequence
1387 * @param release_heads A pass-by-reference return parameter. Will be filled
1388 * with the head(s) of the release sequence(s), if they exists with certainty.
1389 * @see ModelChecker::release_seq_heads
1391 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1393 const ModelAction *rf = act->get_reads_from();
1394 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1395 sequence->acquire = act;
1397 if (!release_seq_heads(rf, release_heads, sequence)) {
1398 /* add act to 'lazy checking' list */
1399 pending_rel_seqs->push_back(sequence);
1401 snapshot_free(sequence);
1406 * Attempt to resolve all stashed operations that might synchronize with a
1407 * release sequence for a given location. This implements the "lazy" portion of
1408 * determining whether or not a release sequence was contiguous, since not all
1409 * modification order information is present at the time an action occurs.
1411 * @param location The location/object that should be checked for release
1412 * sequence resolutions. A NULL value means to check all locations.
1413 * @param work_queue The work queue to which to add work items as they are
1415 * @return True if any updates occurred (new synchronization, new mo_graph
1418 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1420 bool updated = false;
1421 std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1422 while (it != pending_rel_seqs->end()) {
1423 struct release_seq *pending = *it;
1424 ModelAction *act = pending->acquire;
1426 /* Only resolve sequences on the given location, if provided */
1427 if (location && act->get_location() != location) {
1432 const ModelAction *rf = act->get_reads_from();
1433 rel_heads_list_t release_heads;
1435 complete = release_seq_heads(rf, &release_heads, pending);
1436 for (unsigned int i = 0; i < release_heads.size(); i++) {
1437 if (!act->has_synchronized_with(release_heads[i])) {
1438 if (act->synchronize_with(release_heads[i]))
1441 set_bad_synchronization();
1446 /* Re-check all pending release sequences */
1447 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1448 /* Re-check act for mo_graph edges */
1449 work_queue->push_back(MOEdgeWorkEntry(act));
1451 /* propagate synchronization to later actions */
1452 action_list_t::reverse_iterator rit = action_trace->rbegin();
1453 for (; (*rit) != act; rit++) {
1454 ModelAction *propagate = *rit;
1455 if (act->happens_before(propagate)) {
1456 propagate->synchronize_with(act);
1457 /* Re-check 'propagate' for mo_graph edges */
1458 work_queue->push_back(MOEdgeWorkEntry(propagate));
1463 it = pending_rel_seqs->erase(it);
1464 snapshot_free(pending);
1470 // If we resolved promises or data races, see if we have realized a data race.
1471 if (checkDataRaces()) {
1479 * Performs various bookkeeping operations for the current ModelAction. For
1480 * instance, adds action to the per-object, per-thread action vector and to the
1481 * action trace list of all thread actions.
1483 * @param act is the ModelAction to add.
1485 void ModelChecker::add_action_to_lists(ModelAction *act)
1487 int tid = id_to_int(act->get_tid());
1488 action_trace->push_back(act);
1490 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1492 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1493 if (tid >= (int)vec->size())
1494 vec->resize(priv->next_thread_id);
1495 (*vec)[tid].push_back(act);
1497 if ((int)thrd_last_action->size() <= tid)
1498 thrd_last_action->resize(get_num_threads());
1499 (*thrd_last_action)[tid] = act;
1503 * @brief Get the last action performed by a particular Thread
1504 * @param tid The thread ID of the Thread in question
1505 * @return The last action in the thread
1507 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1509 int threadid = id_to_int(tid);
1510 if (threadid < (int)thrd_last_action->size())
1511 return (*thrd_last_action)[id_to_int(tid)];
1517 * Gets the last memory_order_seq_cst write (in the total global sequence)
1518 * performed on a particular object (i.e., memory location), not including the
1520 * @param curr The current ModelAction; also denotes the object location to
1522 * @return The last seq_cst write
1524 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1526 void *location = curr->get_location();
1527 action_list_t *list = obj_map->get_safe_ptr(location);
1528 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1529 action_list_t::reverse_iterator rit;
1530 for (rit = list->rbegin(); rit != list->rend(); rit++)
1531 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1537 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1538 * location). This function identifies the mutex according to the current
1539 * action, which is presumed to perform on the same mutex.
1540 * @param curr The current ModelAction; also denotes the object location to
1542 * @return The last unlock operation
1544 ModelAction * ModelChecker::get_last_unlock(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) | isUnlock(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_unlock())
1556 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1558 ModelAction *parent = get_last_action(tid);
1560 parent = get_thread(tid)->get_creation();
1565 * Returns the clock vector for a given thread.
1566 * @param tid The thread whose clock vector we want
1567 * @return Desired clock vector
1569 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1571 return get_parent_action(tid)->get_cv();
1575 * Resolve a set of Promises with a current write. The set is provided in the
1576 * Node corresponding to @a write.
1577 * @param write The ModelAction that is fulfilling Promises
1578 * @return True if promises were resolved; false otherwise
1580 bool ModelChecker::resolve_promises(ModelAction *write)
1582 bool resolved = false;
1583 std::vector<thread_id_t> threads_to_check;
1585 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1586 Promise *promise = (*promises)[promise_index];
1587 if (write->get_node()->get_promise(i)) {
1588 ModelAction *read = promise->get_action();
1589 if (read->is_rmw()) {
1590 mo_graph->addRMWEdge(write, read);
1592 read->read_from(write);
1593 //First fix up the modification order for actions that happened
1595 r_modification_order(read, write);
1596 //Next fix up the modification order for actions that happened
1598 post_r_modification_order(read, write);
1599 //Make sure the promise's value matches the write's value
1600 ASSERT(promise->get_value() == write->get_value());
1603 promises->erase(promises->begin() + promise_index);
1604 threads_to_check.push_back(read->get_tid());
1611 //Check whether reading these writes has made threads unable to
1614 for(unsigned int i=0;i<threads_to_check.size();i++)
1615 mo_check_promises(threads_to_check[i], write);
1621 * Compute the set of promises that could potentially be satisfied by this
1622 * action. Note that the set computation actually appears in the Node, not in
1624 * @param curr The ModelAction that may satisfy promises
1626 void ModelChecker::compute_promises(ModelAction *curr)
1628 for (unsigned int i = 0; i < promises->size(); i++) {
1629 Promise *promise = (*promises)[i];
1630 const ModelAction *act = promise->get_action();
1631 if (!act->happens_before(curr) &&
1633 !act->could_synchronize_with(curr) &&
1634 !act->same_thread(curr) &&
1635 promise->get_value() == curr->get_value()) {
1636 curr->get_node()->set_promise(i);
1641 /** Checks promises in response to change in ClockVector Threads. */
1642 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1644 for (unsigned int i = 0; i < promises->size(); i++) {
1645 Promise *promise = (*promises)[i];
1646 const ModelAction *act = promise->get_action();
1647 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1648 merge_cv->synchronized_since(act)) {
1649 if (promise->increment_threads(tid)) {
1650 //Promise has failed
1651 failed_promise = true;
1658 /** Checks promises in response to addition to modification order for threads.
1660 * pthread is the thread that performed the read that created the promise
1662 * pread is the read that created the promise
1664 * pwrite is either the first write to same location as pread by
1665 * pthread that is sequenced after pread or the value read by the
1666 * first read to the same lcoation as pread by pthread that is
1667 * sequenced after pread..
1669 * 1. If tid=pthread, then we check what other threads are reachable
1670 * through the mode order starting with pwrite. Those threads cannot
1671 * perform a write that will resolve the promise due to modification
1672 * order constraints.
1674 * 2. If the tid is not pthread, we check whether pwrite can reach the
1675 * action write through the modification order. If so, that thread
1676 * cannot perform a future write that will resolve the promise due to
1677 * modificatin order constraints.
1679 * @parem tid The thread that either read from the model action
1680 * write, or actually did the model action write.
1682 * @parem write The ModelAction representing the relevant write.
1685 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1686 void * location = write->get_location();
1687 for (unsigned int i = 0; i < promises->size(); i++) {
1688 Promise *promise = (*promises)[i];
1689 const ModelAction *act = promise->get_action();
1691 //Is this promise on the same location?
1692 if ( act->get_location() != location )
1695 //same thread as the promise
1696 if ( act->get_tid()==tid ) {
1698 //do we have a pwrite for the promise, if not, set it
1699 if (promise->get_write() == NULL ) {
1700 promise->set_write(write);
1702 if (mo_graph->checkPromise(write, promise)) {
1703 failed_promise = true;
1708 //Don't do any lookups twice for the same thread
1709 if (promise->has_sync_thread(tid))
1712 if (mo_graph->checkReachable(promise->get_write(), write)) {
1713 if (promise->increment_threads(tid)) {
1714 failed_promise = true;
1722 * Compute the set of writes that may break the current pending release
1723 * sequence. This information is extracted from previou release sequence
1726 * @param curr The current ModelAction. Must be a release sequence fixup
1729 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1731 if (pending_rel_seqs->empty())
1734 struct release_seq *pending = pending_rel_seqs->back();
1735 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1736 const ModelAction *write = pending->writes[i];
1737 curr->get_node()->add_relseq_break(write);
1740 /* NULL means don't break the sequence; just synchronize */
1741 curr->get_node()->add_relseq_break(NULL);
1745 * Build up an initial set of all past writes that this 'read' action may read
1746 * from. This set is determined by the clock vector's "happens before"
1748 * @param curr is the current ModelAction that we are exploring; it must be a
1751 void ModelChecker::build_reads_from_past(ModelAction *curr)
1753 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1755 ASSERT(curr->is_read());
1757 ModelAction *last_seq_cst = NULL;
1759 /* Track whether this object has been initialized */
1760 bool initialized = false;
1762 if (curr->is_seqcst()) {
1763 last_seq_cst = get_last_seq_cst(curr);
1764 /* We have to at least see the last sequentially consistent write,
1765 so we are initialized. */
1766 if (last_seq_cst != NULL)
1770 /* Iterate over all threads */
1771 for (i = 0; i < thrd_lists->size(); i++) {
1772 /* Iterate over actions in thread, starting from most recent */
1773 action_list_t *list = &(*thrd_lists)[i];
1774 action_list_t::reverse_iterator rit;
1775 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1776 ModelAction *act = *rit;
1778 /* Only consider 'write' actions */
1779 if (!act->is_write() || act == curr)
1782 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1783 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1784 DEBUG("Adding action to may_read_from:\n");
1785 if (DBG_ENABLED()) {
1789 curr->get_node()->add_read_from(act);
1792 /* Include at most one act per-thread that "happens before" curr */
1793 if (act->happens_before(curr)) {
1801 /** @todo Need a more informative way of reporting errors. */
1802 printf("ERROR: may read from uninitialized atomic\n");
1805 if (DBG_ENABLED() || !initialized) {
1806 printf("Reached read action:\n");
1808 printf("Printing may_read_from\n");
1809 curr->get_node()->print_may_read_from();
1810 printf("End printing may_read_from\n");
1813 ASSERT(initialized);
1816 static void print_list(action_list_t *list)
1818 action_list_t::iterator it;
1820 printf("---------------------------------------------------------------------\n");
1823 for (it = list->begin(); it != list->end(); it++) {
1826 printf("---------------------------------------------------------------------\n");
1829 #if SUPPORT_MOD_ORDER_DUMP
1830 void ModelChecker::dumpGraph(char *filename) {
1832 sprintf(buffer, "%s.dot",filename);
1833 FILE *file=fopen(buffer, "w");
1834 fprintf(file, "digraph %s {\n",filename);
1835 mo_graph->dumpNodes(file);
1836 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1838 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1839 ModelAction *action=*it;
1840 if (action->is_read()) {
1841 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1842 if (action->get_reads_from()!=NULL)
1843 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1845 if (thread_array[action->get_tid()] != NULL) {
1846 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1849 thread_array[action->get_tid()]=action;
1851 fprintf(file,"}\n");
1852 model_free(thread_array);
1857 void ModelChecker::print_summary()
1860 printf("Number of executions: %d\n", num_executions);
1861 printf("Number of feasible executions: %d\n", num_feasible_executions);
1862 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1864 #if SUPPORT_MOD_ORDER_DUMP
1866 char buffername[100];
1867 sprintf(buffername, "exec%04u", num_executions);
1868 mo_graph->dumpGraphToFile(buffername);
1869 sprintf(buffername, "graph%04u", num_executions);
1870 dumpGraph(buffername);
1873 if (!isfinalfeasible())
1874 printf("INFEASIBLE EXECUTION!\n");
1875 print_list(action_trace);
1880 * Add a Thread to the system for the first time. Should only be called once
1882 * @param t The Thread to add
1884 void ModelChecker::add_thread(Thread *t)
1886 thread_map->put(id_to_int(t->get_id()), t);
1887 scheduler->add_thread(t);
1891 * Removes a thread from the scheduler.
1892 * @param the thread to remove.
1894 void ModelChecker::remove_thread(Thread *t)
1896 scheduler->remove_thread(t);
1900 * @brief Get a Thread reference by its ID
1901 * @param tid The Thread's ID
1902 * @return A Thread reference
1904 Thread * ModelChecker::get_thread(thread_id_t tid) const
1906 return thread_map->get(id_to_int(tid));
1910 * @brief Get a reference to the Thread in which a ModelAction was executed
1911 * @param act The ModelAction
1912 * @return A Thread reference
1914 Thread * ModelChecker::get_thread(ModelAction *act) const
1916 return get_thread(act->get_tid());
1920 * Switch from a user-context to the "master thread" context (a.k.a. system
1921 * context). This switch is made with the intention of exploring a particular
1922 * model-checking action (described by a ModelAction object). Must be called
1923 * from a user-thread context.
1925 * @param act The current action that will be explored. May be NULL only if
1926 * trace is exiting via an assertion (see ModelChecker::set_assert and
1927 * ModelChecker::has_asserted).
1928 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1930 int ModelChecker::switch_to_master(ModelAction *act)
1933 Thread *old = thread_current();
1934 set_current_action(act);
1935 old->set_state(THREAD_READY);
1936 return Thread::swap(old, &system_context);
1940 * Takes the next step in the execution, if possible.
1941 * @return Returns true (success) if a step was taken and false otherwise.
1943 bool ModelChecker::take_step() {
1947 Thread *curr = thread_current();
1949 if (curr->get_state() == THREAD_READY) {
1950 ASSERT(priv->current_action);
1952 priv->nextThread = check_current_action(priv->current_action);
1953 priv->current_action = NULL;
1955 if (curr->is_blocked() || curr->is_complete())
1956 scheduler->remove_thread(curr);
1961 Thread *next = scheduler->next_thread(priv->nextThread);
1963 /* Infeasible -> don't take any more steps */
1967 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1968 next ? id_to_int(next->get_id()) : -1);
1970 /* next == NULL -> don't take any more steps */
1974 next->set_state(THREAD_RUNNING);
1976 if (next->get_pending() != NULL) {
1977 /* restart a pending action */
1978 set_current_action(next->get_pending());
1979 next->set_pending(NULL);
1980 next->set_state(THREAD_READY);
1984 /* Return false only if swap fails with an error */
1985 return (Thread::swap(&system_context, next) == 0);
1988 /** Runs the current execution until threre are no more steps to take. */
1989 void ModelChecker::finish_execution() {
1992 while (take_step());