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 Node *prevnode = nextnode->get_parent();
154 scheduler->update_sleep_set(prevnode);
156 /* Reached divergence point */
157 if (nextnode->increment_promise()) {
158 /* The next node will try to satisfy a different set of promises. */
159 tid = next->get_tid();
160 node_stack->pop_restofstack(2);
161 } else if (nextnode->increment_read_from()) {
162 /* The next node will read from a different value. */
163 tid = next->get_tid();
164 node_stack->pop_restofstack(2);
165 } else if (nextnode->increment_future_value()) {
166 /* The next node will try to read from a different future value. */
167 tid = next->get_tid();
168 node_stack->pop_restofstack(2);
170 /* Make a different thread execute for next step */
171 scheduler->add_sleep(thread_map->get(id_to_int(next->get_tid())));
172 tid = prevnode->get_next_backtrack();
173 /* Make sure the backtracked thread isn't sleeping. */
174 scheduler->remove_sleep(thread_map->get(id_to_int(tid)));
175 node_stack->pop_restofstack(1);
176 if (diverge==earliest_diverge) {
177 earliest_diverge=prevnode->get_action();
180 /* The correct sleep set is in the parent node. */
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 * We need to know what the next actions of all threads in the sleep
196 * set will be. This method computes them and stores the actions at
197 * the corresponding thread object's pending action.
200 void ModelChecker::execute_sleep_set() {
201 for(unsigned int i=0;i<get_num_threads();i++) {
202 thread_id_t tid=int_to_id(i);
203 Thread *thr=get_thread(tid);
204 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
205 thr->set_state(THREAD_RUNNING);
206 scheduler->next_thread(thr);
207 Thread::swap(&system_context, thr);
208 thr->set_pending(priv->current_action);
211 priv->current_action = NULL;
214 void ModelChecker::wake_up_sleeping_actions(ModelAction * curr) {
215 for(unsigned int i=0;i<get_num_threads();i++) {
216 thread_id_t tid=int_to_id(i);
217 Thread *thr=get_thread(tid);
218 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
219 ModelAction *pending_act=thr->get_pending();
220 if (pending_act->could_synchronize_with(curr)) {
221 //Remove this thread from sleep set
222 scheduler->remove_sleep(thr);
229 * Queries the model-checker for more executions to explore and, if one
230 * exists, resets the model-checker state to execute a new execution.
232 * @return If there are more executions to explore, return true. Otherwise,
235 bool ModelChecker::next_execution()
241 if (isfinalfeasible()) {
242 printf("Earliest divergence point since last feasible execution:\n");
243 if (earliest_diverge)
244 earliest_diverge->print();
246 printf("(Not set)\n");
248 earliest_diverge = NULL;
249 num_feasible_executions++;
252 DEBUG("Number of acquires waiting on pending release sequences: %lu\n",
253 pending_rel_seqs->size());
255 if (isfinalfeasible() || DBG_ENABLED())
258 if ((diverge = get_next_backtrack()) == NULL)
262 printf("Next execution will diverge at:\n");
266 reset_to_initial_state();
270 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
272 switch (act->get_type()) {
276 /* linear search: from most recent to oldest */
277 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
278 action_list_t::reverse_iterator rit;
279 for (rit = list->rbegin(); rit != list->rend(); rit++) {
280 ModelAction *prev = *rit;
281 if (prev->could_synchronize_with(act))
287 case ATOMIC_TRYLOCK: {
288 /* linear search: from most recent to oldest */
289 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
290 action_list_t::reverse_iterator rit;
291 for (rit = list->rbegin(); rit != list->rend(); rit++) {
292 ModelAction *prev = *rit;
293 if (act->is_conflicting_lock(prev))
298 case ATOMIC_UNLOCK: {
299 /* linear search: from most recent to oldest */
300 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
301 action_list_t::reverse_iterator rit;
302 for (rit = list->rbegin(); rit != list->rend(); rit++) {
303 ModelAction *prev = *rit;
304 if (!act->same_thread(prev)&&prev->is_failed_trylock())
315 /** This method finds backtracking points where we should try to
316 * reorder the parameter ModelAction against.
318 * @param the ModelAction to find backtracking points for.
320 void ModelChecker::set_backtracking(ModelAction *act)
322 Thread *t = get_thread(act);
323 ModelAction * prev = get_last_conflict(act);
327 Node * node = prev->get_node()->get_parent();
329 int low_tid, high_tid;
330 if (node->is_enabled(t)) {
331 low_tid = id_to_int(act->get_tid());
332 high_tid = low_tid+1;
335 high_tid = get_num_threads();
338 for(int i = low_tid; i < high_tid; i++) {
339 thread_id_t tid = int_to_id(i);
341 if (!node->is_enabled(tid))
344 /* Check if this has been explored already */
345 if (node->has_been_explored(tid))
348 /* See if fairness allows */
349 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
351 for(int t=0;t<node->get_num_threads();t++) {
352 thread_id_t tother=int_to_id(t);
353 if (node->is_enabled(tother) && node->has_priority(tother)) {
361 /* Cache the latest backtracking point */
362 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
363 priv->next_backtrack = prev;
365 /* If this is a new backtracking point, mark the tree */
366 if (!node->set_backtrack(tid))
368 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
369 id_to_int(prev->get_tid()),
370 id_to_int(t->get_id()));
379 * Returns last backtracking point. The model checker will explore a different
380 * path for this point in the next execution.
381 * @return The ModelAction at which the next execution should diverge.
383 ModelAction * ModelChecker::get_next_backtrack()
385 ModelAction *next = priv->next_backtrack;
386 priv->next_backtrack = NULL;
391 * Processes a read or rmw model action.
392 * @param curr is the read model action to process.
393 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
394 * @return True if processing this read updates the mo_graph.
396 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
399 bool updated = false;
401 const ModelAction *reads_from = curr->get_node()->get_read_from();
402 if (reads_from != NULL) {
403 mo_graph->startChanges();
405 value = reads_from->get_value();
406 bool r_status = false;
408 if (!second_part_of_rmw) {
409 check_recency(curr, reads_from);
410 r_status = r_modification_order(curr, reads_from);
414 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
415 mo_graph->rollbackChanges();
416 too_many_reads = false;
420 curr->read_from(reads_from);
421 mo_graph->commitChanges();
422 mo_check_promises(curr->get_tid(), reads_from);
425 } else if (!second_part_of_rmw) {
426 /* Read from future value */
427 value = curr->get_node()->get_future_value();
428 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
429 curr->read_from(NULL);
430 Promise *valuepromise = new Promise(curr, value, expiration);
431 promises->push_back(valuepromise);
433 get_thread(curr)->set_return_value(value);
439 * Processes a lock, trylock, or unlock model action. @param curr is
440 * the read model action to process.
442 * The try lock operation checks whether the lock is taken. If not,
443 * it falls to the normal lock operation case. If so, it returns
446 * The lock operation has already been checked that it is enabled, so
447 * it just grabs the lock and synchronizes with the previous unlock.
449 * The unlock operation has to re-enable all of the threads that are
450 * waiting on the lock.
452 * @return True if synchronization was updated; false otherwise
454 bool ModelChecker::process_mutex(ModelAction *curr) {
455 std::mutex *mutex = (std::mutex *)curr->get_location();
456 struct std::mutex_state *state = mutex->get_state();
457 switch (curr->get_type()) {
458 case ATOMIC_TRYLOCK: {
459 bool success = !state->islocked;
460 curr->set_try_lock(success);
462 get_thread(curr)->set_return_value(0);
465 get_thread(curr)->set_return_value(1);
467 //otherwise fall into the lock case
469 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
470 printf("Lock access before initialization\n");
473 state->islocked = true;
474 ModelAction *unlock = get_last_unlock(curr);
475 //synchronize with the previous unlock statement
476 if (unlock != NULL) {
477 curr->synchronize_with(unlock);
482 case ATOMIC_UNLOCK: {
484 state->islocked = false;
485 //wake up the other threads
486 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
487 //activate all the waiting threads
488 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
489 scheduler->wake(get_thread(*rit));
501 * Process a write ModelAction
502 * @param curr The ModelAction to process
503 * @return True if the mo_graph was updated or promises were resolved
505 bool ModelChecker::process_write(ModelAction *curr)
507 bool updated_mod_order = w_modification_order(curr);
508 bool updated_promises = resolve_promises(curr);
510 if (promises->size() == 0) {
511 for (unsigned int i = 0; i < futurevalues->size(); i++) {
512 struct PendingFutureValue pfv = (*futurevalues)[i];
513 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
514 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
515 priv->next_backtrack = pfv.act;
517 futurevalues->resize(0);
520 mo_graph->commitChanges();
521 mo_check_promises(curr->get_tid(), curr);
523 get_thread(curr)->set_return_value(VALUE_NONE);
524 return updated_mod_order || updated_promises;
528 * @brief Process the current action for thread-related activity
530 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
531 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
532 * synchronization, etc. This function is a no-op for non-THREAD actions
533 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
535 * @param curr The current action
536 * @return True if synchronization was updated or a thread completed
538 bool ModelChecker::process_thread_action(ModelAction *curr)
540 bool updated = false;
542 switch (curr->get_type()) {
543 case THREAD_CREATE: {
544 Thread *th = (Thread *)curr->get_location();
545 th->set_creation(curr);
549 Thread *waiting, *blocking;
550 waiting = get_thread(curr);
551 blocking = (Thread *)curr->get_location();
552 if (!blocking->is_complete()) {
553 blocking->push_wait_list(curr);
554 scheduler->sleep(waiting);
556 do_complete_join(curr);
557 updated = true; /* trigger rel-seq checks */
561 case THREAD_FINISH: {
562 Thread *th = get_thread(curr);
563 while (!th->wait_list_empty()) {
564 ModelAction *act = th->pop_wait_list();
565 Thread *wake = get_thread(act);
566 scheduler->wake(wake);
567 do_complete_join(act);
568 updated = true; /* trigger rel-seq checks */
571 updated = true; /* trigger rel-seq checks */
575 check_promises(curr->get_tid(), NULL, curr->get_cv());
586 * Initialize the current action by performing one or more of the following
587 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
588 * in the NodeStack, manipulating backtracking sets, allocating and
589 * initializing clock vectors, and computing the promises to fulfill.
591 * @param curr The current action, as passed from the user context; may be
592 * freed/invalidated after the execution of this function
593 * @return The current action, as processed by the ModelChecker. Is only the
594 * same as the parameter @a curr if this is a newly-explored action.
596 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
598 ModelAction *newcurr;
600 if (curr->is_rmwc() || curr->is_rmw()) {
601 newcurr = process_rmw(curr);
604 if (newcurr->is_rmw())
605 compute_promises(newcurr);
609 curr->set_seq_number(get_next_seq_num());
611 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
613 /* First restore type and order in case of RMW operation */
615 newcurr->copy_typeandorder(curr);
617 ASSERT(curr->get_location() == newcurr->get_location());
618 newcurr->copy_from_new(curr);
620 /* Discard duplicate ModelAction; use action from NodeStack */
623 /* Always compute new clock vector */
624 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
628 /* Always compute new clock vector */
629 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
631 * Perform one-time actions when pushing new ModelAction onto
634 if (newcurr->is_write())
635 compute_promises(newcurr);
641 * This method checks whether a model action is enabled at the given point.
642 * At this point, it checks whether a lock operation would be successful at this point.
643 * If not, it puts the thread in a waiter list.
644 * @param curr is the ModelAction to check whether it is enabled.
645 * @return a bool that indicates whether the action is enabled.
647 bool ModelChecker::check_action_enabled(ModelAction *curr) {
648 if (curr->is_lock()) {
649 std::mutex * lock = (std::mutex *)curr->get_location();
650 struct std::mutex_state * state = lock->get_state();
651 if (state->islocked) {
652 //Stick the action in the appropriate waiting queue
653 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
662 * This is the heart of the model checker routine. It performs model-checking
663 * actions corresponding to a given "current action." Among other processes, it
664 * calculates reads-from relationships, updates synchronization clock vectors,
665 * forms a memory_order constraints graph, and handles replay/backtrack
666 * execution when running permutations of previously-observed executions.
668 * @param curr The current action to process
669 * @return The next Thread that must be executed. May be NULL if ModelChecker
670 * makes no choice (e.g., according to replay execution, combining RMW actions,
673 Thread * ModelChecker::check_current_action(ModelAction *curr)
676 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
678 if (!check_action_enabled(curr)) {
679 /* Make the execution look like we chose to run this action
680 * much later, when a lock is actually available to release */
681 get_current_thread()->set_pending(curr);
682 scheduler->sleep(get_current_thread());
683 return get_next_thread(NULL);
686 wake_up_sleeping_actions(curr);
688 ModelAction *newcurr = initialize_curr_action(curr);
691 /* Add the action to lists before any other model-checking tasks */
692 if (!second_part_of_rmw)
693 add_action_to_lists(newcurr);
695 /* Build may_read_from set for newly-created actions */
696 if (curr == newcurr && curr->is_read())
697 build_reads_from_past(curr);
700 /* Initialize work_queue with the "current action" work */
701 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
702 while (!work_queue.empty()) {
703 WorkQueueEntry work = work_queue.front();
704 work_queue.pop_front();
707 case WORK_CHECK_CURR_ACTION: {
708 ModelAction *act = work.action;
709 bool update = false; /* update this location's release seq's */
710 bool update_all = false; /* update all release seq's */
712 if (process_thread_action(curr))
715 if (act->is_read() && process_read(act, second_part_of_rmw))
718 if (act->is_write() && process_write(act))
721 if (act->is_mutex_op() && process_mutex(act))
725 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
727 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
730 case WORK_CHECK_RELEASE_SEQ:
731 resolve_release_sequences(work.location, &work_queue);
733 case WORK_CHECK_MO_EDGES: {
734 /** @todo Complete verification of work_queue */
735 ModelAction *act = work.action;
736 bool updated = false;
738 if (act->is_read()) {
739 const ModelAction *rf = act->get_reads_from();
740 if (rf != NULL && r_modification_order(act, rf))
743 if (act->is_write()) {
744 if (w_modification_order(act))
747 mo_graph->commitChanges();
750 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
759 check_curr_backtracking(curr);
760 set_backtracking(curr);
761 return get_next_thread(curr);
765 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
766 * operation from the Thread it is joining with. Must be called after the
767 * completion of the Thread in question.
768 * @param join The THREAD_JOIN action
770 void ModelChecker::do_complete_join(ModelAction *join)
772 Thread *blocking = (Thread *)join->get_location();
773 ModelAction *act = get_last_action(blocking->get_id());
774 join->synchronize_with(act);
777 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
778 Node *currnode = curr->get_node();
779 Node *parnode = currnode->get_parent();
781 if ((!parnode->backtrack_empty() ||
782 !currnode->read_from_empty() ||
783 !currnode->future_value_empty() ||
784 !currnode->promise_empty())
785 && (!priv->next_backtrack ||
786 *curr > *priv->next_backtrack)) {
787 priv->next_backtrack = curr;
791 bool ModelChecker::promises_expired() {
792 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
793 Promise *promise = (*promises)[promise_index];
794 if (promise->get_expiration()<priv->used_sequence_numbers) {
801 /** @return whether the current partial trace must be a prefix of a
803 bool ModelChecker::isfeasibleprefix() {
804 return promises->size() == 0 && pending_rel_seqs->size() == 0;
807 /** @return whether the current partial trace is feasible. */
808 bool ModelChecker::isfeasible() {
809 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
810 DEBUG("Infeasible: RMW violation\n");
812 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
815 /** @return whether the current partial trace is feasible other than
816 * multiple RMW reading from the same store. */
817 bool ModelChecker::isfeasibleotherthanRMW() {
819 if (mo_graph->checkForCycles())
820 DEBUG("Infeasible: modification order cycles\n");
822 DEBUG("Infeasible: failed promise\n");
824 DEBUG("Infeasible: too many reads\n");
825 if (bad_synchronization)
826 DEBUG("Infeasible: bad synchronization ordering\n");
827 if (promises_expired())
828 DEBUG("Infeasible: promises expired\n");
830 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
833 /** Returns whether the current completed trace is feasible. */
834 bool ModelChecker::isfinalfeasible() {
835 if (DBG_ENABLED() && promises->size() != 0)
836 DEBUG("Infeasible: unrevolved promises\n");
838 return isfeasible() && promises->size() == 0;
841 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
842 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
843 ModelAction *lastread = get_last_action(act->get_tid());
844 lastread->process_rmw(act);
845 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
846 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
847 mo_graph->commitChanges();
853 * Checks whether a thread has read from the same write for too many times
854 * without seeing the effects of a later write.
857 * 1) there must a different write that we could read from that would satisfy the modification order,
858 * 2) we must have read from the same value in excess of maxreads times, and
859 * 3) that other write must have been in the reads_from set for maxreads times.
861 * If so, we decide that the execution is no longer feasible.
863 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
864 if (params.maxreads != 0) {
866 if (curr->get_node()->get_read_from_size() <= 1)
868 //Must make sure that execution is currently feasible... We could
869 //accidentally clear by rolling back
872 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
873 int tid = id_to_int(curr->get_tid());
876 if ((int)thrd_lists->size() <= tid)
878 action_list_t *list = &(*thrd_lists)[tid];
880 action_list_t::reverse_iterator rit = list->rbegin();
882 for (; (*rit) != curr; rit++)
884 /* go past curr now */
887 action_list_t::reverse_iterator ritcopy = rit;
888 //See if we have enough reads from the same value
890 for (; count < params.maxreads; rit++,count++) {
891 if (rit==list->rend())
893 ModelAction *act = *rit;
897 if (act->get_reads_from() != rf)
899 if (act->get_node()->get_read_from_size() <= 1)
902 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
904 const ModelAction * write = curr->get_node()->get_read_from_at(i);
906 //Need a different write
910 /* Test to see whether this is a feasible write to read from*/
911 mo_graph->startChanges();
912 r_modification_order(curr, write);
913 bool feasiblereadfrom = isfeasible();
914 mo_graph->rollbackChanges();
916 if (!feasiblereadfrom)
920 bool feasiblewrite = true;
921 //new we need to see if this write works for everyone
923 for (int loop = count; loop>0; loop--,rit++) {
924 ModelAction *act=*rit;
925 bool foundvalue = false;
926 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
927 if (act->get_node()->get_read_from_at(i)==write) {
933 feasiblewrite = false;
938 too_many_reads = true;
946 * Updates the mo_graph with the constraints imposed from the current
949 * Basic idea is the following: Go through each other thread and find
950 * the lastest action that happened before our read. Two cases:
952 * (1) The action is a write => that write must either occur before
953 * the write we read from or be the write we read from.
955 * (2) The action is a read => the write that that action read from
956 * must occur before the write we read from or be the same write.
958 * @param curr The current action. Must be a read.
959 * @param rf The action that curr reads from. Must be a write.
960 * @return True if modification order edges were added; false otherwise
962 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
964 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
967 ASSERT(curr->is_read());
969 /* Iterate over all threads */
970 for (i = 0; i < thrd_lists->size(); i++) {
971 /* Iterate over actions in thread, starting from most recent */
972 action_list_t *list = &(*thrd_lists)[i];
973 action_list_t::reverse_iterator rit;
974 for (rit = list->rbegin(); rit != list->rend(); rit++) {
975 ModelAction *act = *rit;
978 * Include at most one act per-thread that "happens
979 * before" curr. Don't consider reflexively.
981 if (act->happens_before(curr) && act != curr) {
982 if (act->is_write()) {
984 mo_graph->addEdge(act, rf);
988 const ModelAction *prevreadfrom = act->get_reads_from();
989 //if the previous read is unresolved, keep going...
990 if (prevreadfrom == NULL)
993 if (rf != prevreadfrom) {
994 mo_graph->addEdge(prevreadfrom, rf);
1006 /** This method fixes up the modification order when we resolve a
1007 * promises. The basic problem is that actions that occur after the
1008 * read curr could not property add items to the modification order
1011 * So for each thread, we find the earliest item that happens after
1012 * the read curr. This is the item we have to fix up with additional
1013 * constraints. If that action is write, we add a MO edge between
1014 * the Action rf and that action. If the action is a read, we add a
1015 * MO edge between the Action rf, and whatever the read accessed.
1017 * @param curr is the read ModelAction that we are fixing up MO edges for.
1018 * @param rf is the write ModelAction that curr reads from.
1021 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1023 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1025 ASSERT(curr->is_read());
1027 /* Iterate over all threads */
1028 for (i = 0; i < thrd_lists->size(); i++) {
1029 /* Iterate over actions in thread, starting from most recent */
1030 action_list_t *list = &(*thrd_lists)[i];
1031 action_list_t::reverse_iterator rit;
1032 ModelAction *lastact = NULL;
1034 /* Find last action that happens after curr that is either not curr or a rmw */
1035 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1036 ModelAction *act = *rit;
1037 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1043 /* Include at most one act per-thread that "happens before" curr */
1044 if (lastact != NULL) {
1045 if (lastact==curr) {
1046 //Case 1: The resolved read is a RMW, and we need to make sure
1047 //that the write portion of the RMW mod order after rf
1049 mo_graph->addEdge(rf, lastact);
1050 } else if (lastact->is_read()) {
1051 //Case 2: The resolved read is a normal read and the next
1052 //operation is a read, and we need to make sure the value read
1053 //is mod ordered after rf
1055 const ModelAction *postreadfrom = lastact->get_reads_from();
1056 if (postreadfrom != NULL&&rf != postreadfrom)
1057 mo_graph->addEdge(rf, postreadfrom);
1059 //Case 3: The resolved read is a normal read and the next
1060 //operation is a write, and we need to make sure that the
1061 //write is mod ordered after rf
1063 mo_graph->addEdge(rf, lastact);
1071 * Updates the mo_graph with the constraints imposed from the current write.
1073 * Basic idea is the following: Go through each other thread and find
1074 * the lastest action that happened before our write. Two cases:
1076 * (1) The action is a write => that write must occur before
1079 * (2) The action is a read => the write that that action read from
1080 * must occur before the current write.
1082 * This method also handles two other issues:
1084 * (I) Sequential Consistency: Making sure that if the current write is
1085 * seq_cst, that it occurs after the previous seq_cst write.
1087 * (II) Sending the write back to non-synchronizing reads.
1089 * @param curr The current action. Must be a write.
1090 * @return True if modification order edges were added; false otherwise
1092 bool ModelChecker::w_modification_order(ModelAction *curr)
1094 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1097 ASSERT(curr->is_write());
1099 if (curr->is_seqcst()) {
1100 /* We have to at least see the last sequentially consistent write,
1101 so we are initialized. */
1102 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1103 if (last_seq_cst != NULL) {
1104 mo_graph->addEdge(last_seq_cst, curr);
1109 /* Iterate over all threads */
1110 for (i = 0; i < thrd_lists->size(); i++) {
1111 /* Iterate over actions in thread, starting from most recent */
1112 action_list_t *list = &(*thrd_lists)[i];
1113 action_list_t::reverse_iterator rit;
1114 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1115 ModelAction *act = *rit;
1118 * 1) If RMW and it actually read from something, then we
1119 * already have all relevant edges, so just skip to next
1122 * 2) If RMW and it didn't read from anything, we should
1123 * whatever edge we can get to speed up convergence.
1125 * 3) If normal write, we need to look at earlier actions, so
1126 * continue processing list.
1128 if (curr->is_rmw()) {
1129 if (curr->get_reads_from()!=NULL)
1138 * Include at most one act per-thread that "happens
1141 if (act->happens_before(curr)) {
1143 * Note: if act is RMW, just add edge:
1145 * The following edge should be handled elsewhere:
1146 * readfrom(act) --mo--> act
1148 if (act->is_write())
1149 mo_graph->addEdge(act, curr);
1150 else if (act->is_read()) {
1151 //if previous read accessed a null, just keep going
1152 if (act->get_reads_from() == NULL)
1154 mo_graph->addEdge(act->get_reads_from(), curr);
1158 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1159 !act->same_thread(curr)) {
1160 /* We have an action that:
1161 (1) did not happen before us
1162 (2) is a read and we are a write
1163 (3) cannot synchronize with us
1164 (4) is in a different thread
1166 that read could potentially read from our write.
1168 if (thin_air_constraint_may_allow(curr, act)) {
1170 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1171 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1172 futurevalues->push_back(pfv);
1182 /** Arbitrary reads from the future are not allowed. Section 29.3
1183 * part 9 places some constraints. This method checks one result of constraint
1184 * constraint. Others require compiler support. */
1185 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1186 if (!writer->is_rmw())
1189 if (!reader->is_rmw())
1192 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1193 if (search == reader)
1195 if (search->get_tid() == reader->get_tid() &&
1196 search->happens_before(reader))
1204 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1205 * The ModelAction under consideration is expected to be taking part in
1206 * release/acquire synchronization as an object of the "reads from" relation.
1207 * Note that this can only provide release sequence support for RMW chains
1208 * which do not read from the future, as those actions cannot be traced until
1209 * their "promise" is fulfilled. Similarly, we may not even establish the
1210 * presence of a release sequence with certainty, as some modification order
1211 * constraints may be decided further in the future. Thus, this function
1212 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1213 * and a boolean representing certainty.
1215 * @todo Finish lazy updating, when promises are fulfilled in the future
1216 * @param rf The action that might be part of a release sequence. Must be a
1218 * @param release_heads A pass-by-reference style return parameter. After
1219 * execution of this function, release_heads will contain the heads of all the
1220 * relevant release sequences, if any exists with certainty
1221 * @param pending A pass-by-reference style return parameter which is only used
1222 * when returning false (i.e., uncertain). Returns most information regarding
1223 * an uncertain release sequence, including any write operations that might
1224 * break the sequence.
1225 * @return true, if the ModelChecker is certain that release_heads is complete;
1228 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1229 rel_heads_list_t *release_heads,
1230 struct release_seq *pending) const
1232 /* Only check for release sequences if there are no cycles */
1233 if (mo_graph->checkForCycles())
1237 ASSERT(rf->is_write());
1239 if (rf->is_release())
1240 release_heads->push_back(rf);
1242 break; /* End of RMW chain */
1244 /** @todo Need to be smarter here... In the linux lock
1245 * example, this will run to the beginning of the program for
1247 /** @todo The way to be smarter here is to keep going until 1
1248 * thread has a release preceded by an acquire and you've seen
1251 /* acq_rel RMW is a sufficient stopping condition */
1252 if (rf->is_acquire() && rf->is_release())
1253 return true; /* complete */
1255 rf = rf->get_reads_from();
1258 /* read from future: need to settle this later */
1260 return false; /* incomplete */
1263 if (rf->is_release())
1264 return true; /* complete */
1266 /* else relaxed write; check modification order for contiguous subsequence
1267 * -> rf must be same thread as release */
1268 int tid = id_to_int(rf->get_tid());
1269 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1270 action_list_t *list = &(*thrd_lists)[tid];
1271 action_list_t::const_reverse_iterator rit;
1273 /* Find rf in the thread list */
1274 rit = std::find(list->rbegin(), list->rend(), rf);
1275 ASSERT(rit != list->rend());
1277 /* Find the last write/release */
1278 for (; rit != list->rend(); rit++)
1279 if ((*rit)->is_release())
1281 if (rit == list->rend()) {
1282 /* No write-release in this thread */
1283 return true; /* complete */
1285 ModelAction *release = *rit;
1287 ASSERT(rf->same_thread(release));
1289 pending->writes.clear();
1291 bool certain = true;
1292 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1293 if (id_to_int(rf->get_tid()) == (int)i)
1295 list = &(*thrd_lists)[i];
1297 /* Can we ensure no future writes from this thread may break
1298 * the release seq? */
1299 bool future_ordered = false;
1301 ModelAction *last = get_last_action(int_to_id(i));
1302 if (last && (rf->happens_before(last) ||
1303 get_thread(int_to_id(i))->is_complete()))
1304 future_ordered = true;
1306 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1307 const ModelAction *act = *rit;
1308 /* Reach synchronization -> this thread is complete */
1309 if (act->happens_before(release))
1311 if (rf->happens_before(act)) {
1312 future_ordered = true;
1316 /* Only writes can break release sequences */
1317 if (!act->is_write())
1320 /* Check modification order */
1321 if (mo_graph->checkReachable(rf, act)) {
1322 /* rf --mo--> act */
1323 future_ordered = true;
1326 if (mo_graph->checkReachable(act, release))
1327 /* act --mo--> release */
1329 if (mo_graph->checkReachable(release, act) &&
1330 mo_graph->checkReachable(act, rf)) {
1331 /* release --mo-> act --mo--> rf */
1332 return true; /* complete */
1334 /* act may break release sequence */
1335 pending->writes.push_back(act);
1338 if (!future_ordered)
1339 certain = false; /* This thread is uncertain */
1343 release_heads->push_back(release);
1344 pending->writes.clear();
1346 pending->release = release;
1353 * A public interface for getting the release sequence head(s) with which a
1354 * given ModelAction must synchronize. This function only returns a non-empty
1355 * result when it can locate a release sequence head with certainty. Otherwise,
1356 * it may mark the internal state of the ModelChecker so that it will handle
1357 * the release sequence at a later time, causing @a act to update its
1358 * synchronization at some later point in execution.
1359 * @param act The 'acquire' action that may read from a release sequence
1360 * @param release_heads A pass-by-reference return parameter. Will be filled
1361 * with the head(s) of the release sequence(s), if they exists with certainty.
1362 * @see ModelChecker::release_seq_heads
1364 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1366 const ModelAction *rf = act->get_reads_from();
1367 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1368 sequence->acquire = act;
1370 if (!release_seq_heads(rf, release_heads, sequence)) {
1371 /* add act to 'lazy checking' list */
1372 pending_rel_seqs->push_back(sequence);
1374 snapshot_free(sequence);
1379 * Attempt to resolve all stashed operations that might synchronize with a
1380 * release sequence for a given location. This implements the "lazy" portion of
1381 * determining whether or not a release sequence was contiguous, since not all
1382 * modification order information is present at the time an action occurs.
1384 * @param location The location/object that should be checked for release
1385 * sequence resolutions. A NULL value means to check all locations.
1386 * @param work_queue The work queue to which to add work items as they are
1388 * @return True if any updates occurred (new synchronization, new mo_graph
1391 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1393 bool updated = false;
1394 std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1395 while (it != pending_rel_seqs->end()) {
1396 struct release_seq *pending = *it;
1397 ModelAction *act = pending->acquire;
1399 /* Only resolve sequences on the given location, if provided */
1400 if (location && act->get_location() != location) {
1405 const ModelAction *rf = act->get_reads_from();
1406 rel_heads_list_t release_heads;
1408 complete = release_seq_heads(rf, &release_heads, pending);
1409 for (unsigned int i = 0; i < release_heads.size(); i++) {
1410 if (!act->has_synchronized_with(release_heads[i])) {
1411 if (act->synchronize_with(release_heads[i]))
1414 set_bad_synchronization();
1419 /* Re-check all pending release sequences */
1420 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1421 /* Re-check act for mo_graph edges */
1422 work_queue->push_back(MOEdgeWorkEntry(act));
1424 /* propagate synchronization to later actions */
1425 action_list_t::reverse_iterator rit = action_trace->rbegin();
1426 for (; (*rit) != act; rit++) {
1427 ModelAction *propagate = *rit;
1428 if (act->happens_before(propagate)) {
1429 propagate->synchronize_with(act);
1430 /* Re-check 'propagate' for mo_graph edges */
1431 work_queue->push_back(MOEdgeWorkEntry(propagate));
1436 it = pending_rel_seqs->erase(it);
1437 snapshot_free(pending);
1443 // If we resolved promises or data races, see if we have realized a data race.
1444 if (checkDataRaces()) {
1452 * Performs various bookkeeping operations for the current ModelAction. For
1453 * instance, adds action to the per-object, per-thread action vector and to the
1454 * action trace list of all thread actions.
1456 * @param act is the ModelAction to add.
1458 void ModelChecker::add_action_to_lists(ModelAction *act)
1460 int tid = id_to_int(act->get_tid());
1461 action_trace->push_back(act);
1463 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1465 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1466 if (tid >= (int)vec->size())
1467 vec->resize(priv->next_thread_id);
1468 (*vec)[tid].push_back(act);
1470 if ((int)thrd_last_action->size() <= tid)
1471 thrd_last_action->resize(get_num_threads());
1472 (*thrd_last_action)[tid] = act;
1476 * @brief Get the last action performed by a particular Thread
1477 * @param tid The thread ID of the Thread in question
1478 * @return The last action in the thread
1480 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1482 int threadid = id_to_int(tid);
1483 if (threadid < (int)thrd_last_action->size())
1484 return (*thrd_last_action)[id_to_int(tid)];
1490 * Gets the last memory_order_seq_cst write (in the total global sequence)
1491 * performed on a particular object (i.e., memory location), not including the
1493 * @param curr The current ModelAction; also denotes the object location to
1495 * @return The last seq_cst write
1497 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1499 void *location = curr->get_location();
1500 action_list_t *list = obj_map->get_safe_ptr(location);
1501 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1502 action_list_t::reverse_iterator rit;
1503 for (rit = list->rbegin(); rit != list->rend(); rit++)
1504 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1510 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1511 * location). This function identifies the mutex according to the current
1512 * action, which is presumed to perform on the same mutex.
1513 * @param curr The current ModelAction; also denotes the object location to
1515 * @return The last unlock operation
1517 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1519 void *location = curr->get_location();
1520 action_list_t *list = obj_map->get_safe_ptr(location);
1521 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1522 action_list_t::reverse_iterator rit;
1523 for (rit = list->rbegin(); rit != list->rend(); rit++)
1524 if ((*rit)->is_unlock())
1529 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1531 ModelAction *parent = get_last_action(tid);
1533 parent = get_thread(tid)->get_creation();
1538 * Returns the clock vector for a given thread.
1539 * @param tid The thread whose clock vector we want
1540 * @return Desired clock vector
1542 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1544 return get_parent_action(tid)->get_cv();
1548 * Resolve a set of Promises with a current write. The set is provided in the
1549 * Node corresponding to @a write.
1550 * @param write The ModelAction that is fulfilling Promises
1551 * @return True if promises were resolved; false otherwise
1553 bool ModelChecker::resolve_promises(ModelAction *write)
1555 bool resolved = false;
1556 std::vector<thread_id_t> threads_to_check;
1558 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1559 Promise *promise = (*promises)[promise_index];
1560 if (write->get_node()->get_promise(i)) {
1561 ModelAction *read = promise->get_action();
1562 if (read->is_rmw()) {
1563 mo_graph->addRMWEdge(write, read);
1565 read->read_from(write);
1566 //First fix up the modification order for actions that happened
1568 r_modification_order(read, write);
1569 //Next fix up the modification order for actions that happened
1571 post_r_modification_order(read, write);
1572 //Make sure the promise's value matches the write's value
1573 ASSERT(promise->get_value() == write->get_value());
1576 promises->erase(promises->begin() + promise_index);
1577 threads_to_check.push_back(read->get_tid());
1584 //Check whether reading these writes has made threads unable to
1587 for(unsigned int i=0;i<threads_to_check.size();i++)
1588 mo_check_promises(threads_to_check[i], write);
1594 * Compute the set of promises that could potentially be satisfied by this
1595 * action. Note that the set computation actually appears in the Node, not in
1597 * @param curr The ModelAction that may satisfy promises
1599 void ModelChecker::compute_promises(ModelAction *curr)
1601 for (unsigned int i = 0; i < promises->size(); i++) {
1602 Promise *promise = (*promises)[i];
1603 const ModelAction *act = promise->get_action();
1604 if (!act->happens_before(curr) &&
1606 !act->could_synchronize_with(curr) &&
1607 !act->same_thread(curr) &&
1608 promise->get_value() == curr->get_value()) {
1609 curr->get_node()->set_promise(i);
1614 /** Checks promises in response to change in ClockVector Threads. */
1615 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1617 for (unsigned int i = 0; i < promises->size(); i++) {
1618 Promise *promise = (*promises)[i];
1619 const ModelAction *act = promise->get_action();
1620 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1621 merge_cv->synchronized_since(act)) {
1622 if (promise->increment_threads(tid)) {
1623 //Promise has failed
1624 failed_promise = true;
1631 /** Checks promises in response to addition to modification order for threads.
1633 * pthread is the thread that performed the read that created the promise
1635 * pread is the read that created the promise
1637 * pwrite is either the first write to same location as pread by
1638 * pthread that is sequenced after pread or the value read by the
1639 * first read to the same lcoation as pread by pthread that is
1640 * sequenced after pread..
1642 * 1. If tid=pthread, then we check what other threads are reachable
1643 * through the mode order starting with pwrite. Those threads cannot
1644 * perform a write that will resolve the promise due to modification
1645 * order constraints.
1647 * 2. If the tid is not pthread, we check whether pwrite can reach the
1648 * action write through the modification order. If so, that thread
1649 * cannot perform a future write that will resolve the promise due to
1650 * modificatin order constraints.
1652 * @parem tid The thread that either read from the model action
1653 * write, or actually did the model action write.
1655 * @parem write The ModelAction representing the relevant write.
1658 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1659 void * location = write->get_location();
1660 for (unsigned int i = 0; i < promises->size(); i++) {
1661 Promise *promise = (*promises)[i];
1662 const ModelAction *act = promise->get_action();
1664 //Is this promise on the same location?
1665 if ( act->get_location() != location )
1668 //same thread as the promise
1669 if ( act->get_tid()==tid ) {
1671 //do we have a pwrite for the promise, if not, set it
1672 if (promise->get_write() == NULL ) {
1673 promise->set_write(write);
1675 if (mo_graph->checkPromise(write, promise)) {
1676 failed_promise = true;
1681 //Don't do any lookups twice for the same thread
1682 if (promise->has_sync_thread(tid))
1685 if (mo_graph->checkReachable(promise->get_write(), write)) {
1686 if (promise->increment_threads(tid)) {
1687 failed_promise = true;
1695 * Build up an initial set of all past writes that this 'read' action may read
1696 * from. This set is determined by the clock vector's "happens before"
1698 * @param curr is the current ModelAction that we are exploring; it must be a
1701 void ModelChecker::build_reads_from_past(ModelAction *curr)
1703 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1705 ASSERT(curr->is_read());
1707 ModelAction *last_seq_cst = NULL;
1709 /* Track whether this object has been initialized */
1710 bool initialized = false;
1712 if (curr->is_seqcst()) {
1713 last_seq_cst = get_last_seq_cst(curr);
1714 /* We have to at least see the last sequentially consistent write,
1715 so we are initialized. */
1716 if (last_seq_cst != NULL)
1720 /* Iterate over all threads */
1721 for (i = 0; i < thrd_lists->size(); i++) {
1722 /* Iterate over actions in thread, starting from most recent */
1723 action_list_t *list = &(*thrd_lists)[i];
1724 action_list_t::reverse_iterator rit;
1725 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1726 ModelAction *act = *rit;
1728 /* Only consider 'write' actions */
1729 if (!act->is_write() || act == curr)
1732 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1733 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1734 DEBUG("Adding action to may_read_from:\n");
1735 if (DBG_ENABLED()) {
1739 curr->get_node()->add_read_from(act);
1742 /* Include at most one act per-thread that "happens before" curr */
1743 if (act->happens_before(curr)) {
1751 /** @todo Need a more informative way of reporting errors. */
1752 printf("ERROR: may read from uninitialized atomic\n");
1755 if (DBG_ENABLED() || !initialized) {
1756 printf("Reached read action:\n");
1758 printf("Printing may_read_from\n");
1759 curr->get_node()->print_may_read_from();
1760 printf("End printing may_read_from\n");
1763 ASSERT(initialized);
1766 static void print_list(action_list_t *list)
1768 action_list_t::iterator it;
1770 printf("---------------------------------------------------------------------\n");
1773 for (it = list->begin(); it != list->end(); it++) {
1776 printf("---------------------------------------------------------------------\n");
1779 #if SUPPORT_MOD_ORDER_DUMP
1780 void ModelChecker::dumpGraph(char *filename) {
1782 sprintf(buffer, "%s.dot",filename);
1783 FILE *file=fopen(buffer, "w");
1784 fprintf(file, "digraph %s {\n",filename);
1785 mo_graph->dumpNodes(file);
1786 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1788 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1789 ModelAction *action=*it;
1790 if (action->is_read()) {
1791 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1792 if (action->get_reads_from()!=NULL)
1793 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1795 if (thread_array[action->get_tid()] != NULL) {
1796 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1799 thread_array[action->get_tid()]=action;
1801 fprintf(file,"}\n");
1802 model_free(thread_array);
1807 void ModelChecker::print_summary()
1810 printf("Number of executions: %d\n", num_executions);
1811 printf("Number of feasible executions: %d\n", num_feasible_executions);
1812 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1814 #if SUPPORT_MOD_ORDER_DUMP
1816 char buffername[100];
1817 sprintf(buffername, "exec%04u", num_executions);
1818 mo_graph->dumpGraphToFile(buffername);
1819 sprintf(buffername, "graph%04u", num_executions);
1820 dumpGraph(buffername);
1823 if (!isfinalfeasible())
1824 printf("INFEASIBLE EXECUTION!\n");
1825 print_list(action_trace);
1830 * Add a Thread to the system for the first time. Should only be called once
1832 * @param t The Thread to add
1834 void ModelChecker::add_thread(Thread *t)
1836 thread_map->put(id_to_int(t->get_id()), t);
1837 scheduler->add_thread(t);
1841 * Removes a thread from the scheduler.
1842 * @param the thread to remove.
1844 void ModelChecker::remove_thread(Thread *t)
1846 scheduler->remove_thread(t);
1850 * @brief Get a Thread reference by its ID
1851 * @param tid The Thread's ID
1852 * @return A Thread reference
1854 Thread * ModelChecker::get_thread(thread_id_t tid) const
1856 return thread_map->get(id_to_int(tid));
1860 * @brief Get a reference to the Thread in which a ModelAction was executed
1861 * @param act The ModelAction
1862 * @return A Thread reference
1864 Thread * ModelChecker::get_thread(ModelAction *act) const
1866 return get_thread(act->get_tid());
1870 * Switch from a user-context to the "master thread" context (a.k.a. system
1871 * context). This switch is made with the intention of exploring a particular
1872 * model-checking action (described by a ModelAction object). Must be called
1873 * from a user-thread context.
1875 * @param act The current action that will be explored. May be NULL only if
1876 * trace is exiting via an assertion (see ModelChecker::set_assert and
1877 * ModelChecker::has_asserted).
1878 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1880 int ModelChecker::switch_to_master(ModelAction *act)
1883 Thread *old = thread_current();
1884 set_current_action(act);
1885 old->set_state(THREAD_READY);
1886 return Thread::swap(old, &system_context);
1890 * Takes the next step in the execution, if possible.
1891 * @return Returns true (success) if a step was taken and false otherwise.
1893 bool ModelChecker::take_step() {
1897 Thread *curr = thread_current();
1899 if (curr->get_state() == THREAD_READY) {
1900 ASSERT(priv->current_action);
1902 priv->nextThread = check_current_action(priv->current_action);
1903 priv->current_action = NULL;
1905 if (curr->is_blocked() || curr->is_complete())
1906 scheduler->remove_thread(curr);
1911 Thread *next = scheduler->next_thread(priv->nextThread);
1913 /* Infeasible -> don't take any more steps */
1917 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1918 next ? id_to_int(next->get_id()) : -1);
1920 /* next == NULL -> don't take any more steps */
1924 next->set_state(THREAD_RUNNING);
1926 if (next->get_pending() != NULL) {
1927 /* restart a pending action */
1928 set_current_action(next->get_pending());
1929 next->set_pending(NULL);
1930 next->set_state(THREAD_READY);
1934 /* Return false only if swap fails with an error */
1935 return (Thread::swap(&system_context, next) == 0);
1938 /** Runs the current execution until threre are no more steps to take. */
1939 void ModelChecker::finish_execution() {
1942 while (take_step());