8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
17 #define INITIAL_THREAD_ID 0
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23 /* Initialize default scheduler */
25 scheduler(new Scheduler()),
27 num_feasible_executions(0),
29 earliest_diverge(NULL),
30 action_trace(new action_list_t()),
31 thread_map(new HashTable<int, Thread *, int>()),
32 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
34 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
35 promises(new std::vector<Promise *>()),
36 futurevalues(new std::vector<struct PendingFutureValue>()),
37 pending_rel_seqs(new std::vector<struct release_seq *>()),
38 thrd_last_action(new std::vector<ModelAction *>(1)),
39 node_stack(new NodeStack()),
40 mo_graph(new CycleGraph()),
41 failed_promise(false),
42 too_many_reads(false),
44 bad_synchronization(false)
46 /* Allocate this "size" on the snapshotting heap */
47 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
48 /* First thread created will have id INITIAL_THREAD_ID */
49 priv->next_thread_id = INITIAL_THREAD_ID;
51 /* Initialize a model-checker thread, for special ModelActions */
52 model_thread = new Thread(get_next_id());
53 thread_map->put(id_to_int(model_thread->get_id()), model_thread);
56 /** @brief Destructor */
57 ModelChecker::~ModelChecker()
59 for (unsigned int i = 0; i < get_num_threads(); i++)
60 delete thread_map->get(i);
65 delete lock_waiters_map;
68 for (unsigned int i = 0; i < promises->size(); i++)
69 delete (*promises)[i];
72 delete pending_rel_seqs;
74 delete thrd_last_action;
81 * Restores user program to initial state and resets all model-checker data
84 void ModelChecker::reset_to_initial_state()
86 DEBUG("+++ Resetting to initial state +++\n");
87 node_stack->reset_execution();
88 failed_promise = false;
89 too_many_reads = false;
90 bad_synchronization = false;
92 snapshotObject->backTrackBeforeStep(0);
95 /** @return a thread ID for a new Thread */
96 thread_id_t ModelChecker::get_next_id()
98 return priv->next_thread_id++;
101 /** @return the number of user threads created during this execution */
102 unsigned int ModelChecker::get_num_threads()
104 return priv->next_thread_id;
107 /** @return The currently executing Thread. */
108 Thread * ModelChecker::get_current_thread()
110 return scheduler->get_current_thread();
113 /** @return a sequence number for a new ModelAction */
114 modelclock_t ModelChecker::get_next_seq_num()
116 return ++priv->used_sequence_numbers;
120 * @brief Choose the next thread to execute.
122 * This function chooses the next thread that should execute. It can force the
123 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
124 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
125 * The model-checker may have no preference regarding the next thread (i.e.,
126 * when exploring a new execution ordering), in which case this will return
128 * @param curr The current ModelAction. This action might guide the choice of
130 * @return The next thread to run. If the model-checker has no preference, NULL.
132 Thread * ModelChecker::get_next_thread(ModelAction *curr)
137 /* Do not split atomic actions. */
139 return thread_current();
140 /* The THREAD_CREATE action points to the created Thread */
141 else if (curr->get_type() == THREAD_CREATE)
142 return (Thread *)curr->get_location();
145 /* Have we completed exploring the preselected path? */
149 /* Else, we are trying to replay an execution */
150 ModelAction *next = node_stack->get_next()->get_action();
152 if (next == diverge) {
153 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
154 earliest_diverge=diverge;
156 Node *nextnode = next->get_node();
157 /* Reached divergence point */
158 if (nextnode->increment_promise()) {
159 /* The next node will try to satisfy a different set of promises. */
160 tid = next->get_tid();
161 node_stack->pop_restofstack(2);
162 } else if (nextnode->increment_read_from()) {
163 /* The next node will read from a different value. */
164 tid = next->get_tid();
165 node_stack->pop_restofstack(2);
166 } else if (nextnode->increment_future_value()) {
167 /* The next node will try to read from a different future value. */
168 tid = next->get_tid();
169 node_stack->pop_restofstack(2);
170 } else if (nextnode->increment_relseq_break()) {
171 /* The next node will try to resolve a release sequence differently */
172 tid = next->get_tid();
173 node_stack->pop_restofstack(2);
175 /* Make a different thread execute for next step */
176 Node *node = nextnode->get_parent();
177 tid = node->get_next_backtrack();
178 node_stack->pop_restofstack(1);
179 if (diverge==earliest_diverge) {
180 earliest_diverge=node->get_action();
183 DEBUG("*** Divergence point ***\n");
187 tid = next->get_tid();
189 DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
190 ASSERT(tid != THREAD_ID_T_NONE);
191 return thread_map->get(id_to_int(tid));
195 * Queries the model-checker for more executions to explore and, if one
196 * exists, resets the model-checker state to execute a new execution.
198 * @return If there are more executions to explore, return true. Otherwise,
201 bool ModelChecker::next_execution()
207 if (isfinalfeasible()) {
208 printf("Earliest divergence point since last feasible execution:\n");
209 if (earliest_diverge)
210 earliest_diverge->print();
212 printf("(Not set)\n");
214 earliest_diverge = NULL;
215 num_feasible_executions++;
218 DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
219 pending_rel_seqs->size());
221 if (isfinalfeasible() || DBG_ENABLED())
224 if ((diverge = get_next_backtrack()) == NULL)
228 printf("Next execution will diverge at:\n");
232 reset_to_initial_state();
236 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
238 switch (act->get_type()) {
242 /* linear search: from most recent to oldest */
243 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
244 action_list_t::reverse_iterator rit;
245 for (rit = list->rbegin(); rit != list->rend(); rit++) {
246 ModelAction *prev = *rit;
247 if (prev->could_synchronize_with(act))
253 case ATOMIC_TRYLOCK: {
254 /* linear search: from most recent to oldest */
255 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
256 action_list_t::reverse_iterator rit;
257 for (rit = list->rbegin(); rit != list->rend(); rit++) {
258 ModelAction *prev = *rit;
259 if (act->is_conflicting_lock(prev))
264 case ATOMIC_UNLOCK: {
265 /* linear search: from most recent to oldest */
266 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
267 action_list_t::reverse_iterator rit;
268 for (rit = list->rbegin(); rit != list->rend(); rit++) {
269 ModelAction *prev = *rit;
270 if (!act->same_thread(prev)&&prev->is_failed_trylock())
281 /** This method find backtracking points where we should try to
282 * reorder the parameter ModelAction against.
284 * @param the ModelAction to find backtracking points for.
286 void ModelChecker::set_backtracking(ModelAction *act)
288 Thread *t = get_thread(act);
289 ModelAction * prev = get_last_conflict(act);
293 Node * node = prev->get_node()->get_parent();
295 int low_tid, high_tid;
296 if (node->is_enabled(t)) {
297 low_tid = id_to_int(act->get_tid());
298 high_tid = low_tid+1;
301 high_tid = get_num_threads();
304 for(int i = low_tid; i < high_tid; i++) {
305 thread_id_t tid = int_to_id(i);
306 if (!node->is_enabled(tid))
309 /* Check if this has been explored already */
310 if (node->has_been_explored(tid))
313 /* See if fairness allows */
314 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
316 for(int t=0;t<node->get_num_threads();t++) {
317 thread_id_t tother=int_to_id(t);
318 if (node->is_enabled(tother) && node->has_priority(tother)) {
327 /* Cache the latest backtracking point */
328 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
329 priv->next_backtrack = prev;
331 /* If this is a new backtracking point, mark the tree */
332 if (!node->set_backtrack(tid))
334 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
335 id_to_int(prev->get_tid()),
336 id_to_int(t->get_id()));
345 * Returns last backtracking point. The model checker will explore a different
346 * path for this point in the next execution.
347 * @return The ModelAction at which the next execution should diverge.
349 ModelAction * ModelChecker::get_next_backtrack()
351 ModelAction *next = priv->next_backtrack;
352 priv->next_backtrack = NULL;
357 * Processes a read or rmw model action.
358 * @param curr is the read model action to process.
359 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
360 * @return True if processing this read updates the mo_graph.
362 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
365 bool updated = false;
367 const ModelAction *reads_from = curr->get_node()->get_read_from();
368 if (reads_from != NULL) {
369 mo_graph->startChanges();
371 value = reads_from->get_value();
372 bool r_status = false;
374 if (!second_part_of_rmw) {
375 check_recency(curr, reads_from);
376 r_status = r_modification_order(curr, reads_from);
380 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
381 mo_graph->rollbackChanges();
382 too_many_reads = false;
386 curr->read_from(reads_from);
387 mo_graph->commitChanges();
388 mo_check_promises(curr->get_tid(), reads_from);
391 } else if (!second_part_of_rmw) {
392 /* Read from future value */
393 value = curr->get_node()->get_future_value();
394 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
395 curr->read_from(NULL);
396 Promise *valuepromise = new Promise(curr, value, expiration);
397 promises->push_back(valuepromise);
399 get_thread(curr)->set_return_value(value);
405 * Processes a lock, trylock, or unlock model action. @param curr is
406 * the read model action to process.
408 * The try lock operation checks whether the lock is taken. If not,
409 * it falls to the normal lock operation case. If so, it returns
412 * The lock operation has already been checked that it is enabled, so
413 * it just grabs the lock and synchronizes with the previous unlock.
415 * The unlock operation has to re-enable all of the threads that are
416 * waiting on the lock.
418 * @return True if synchronization was updated; false otherwise
420 bool ModelChecker::process_mutex(ModelAction *curr) {
421 std::mutex *mutex = (std::mutex *)curr->get_location();
422 struct std::mutex_state *state = mutex->get_state();
423 switch (curr->get_type()) {
424 case ATOMIC_TRYLOCK: {
425 bool success = !state->islocked;
426 curr->set_try_lock(success);
428 get_thread(curr)->set_return_value(0);
431 get_thread(curr)->set_return_value(1);
433 //otherwise fall into the lock case
435 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
436 printf("Lock access before initialization\n");
439 state->islocked = true;
440 ModelAction *unlock = get_last_unlock(curr);
441 //synchronize with the previous unlock statement
442 if (unlock != NULL) {
443 curr->synchronize_with(unlock);
448 case ATOMIC_UNLOCK: {
450 state->islocked = false;
451 //wake up the other threads
452 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
453 //activate all the waiting threads
454 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
455 scheduler->wake(get_thread(*rit));
467 * Process a write ModelAction
468 * @param curr The ModelAction to process
469 * @return True if the mo_graph was updated or promises were resolved
471 bool ModelChecker::process_write(ModelAction *curr)
473 bool updated_mod_order = w_modification_order(curr);
474 bool updated_promises = resolve_promises(curr);
476 if (promises->size() == 0) {
477 for (unsigned int i = 0; i < futurevalues->size(); i++) {
478 struct PendingFutureValue pfv = (*futurevalues)[i];
479 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
480 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
481 priv->next_backtrack = pfv.act;
483 futurevalues->resize(0);
486 mo_graph->commitChanges();
487 mo_check_promises(curr->get_tid(), curr);
489 get_thread(curr)->set_return_value(VALUE_NONE);
490 return updated_mod_order || updated_promises;
494 * @brief Process the current action for thread-related activity
496 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
497 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
498 * synchronization, etc. This function is a no-op for non-THREAD actions
499 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
501 * @param curr The current action
502 * @return True if synchronization was updated or a thread completed
504 bool ModelChecker::process_thread_action(ModelAction *curr)
506 bool updated = false;
508 switch (curr->get_type()) {
509 case THREAD_CREATE: {
510 Thread *th = (Thread *)curr->get_location();
511 th->set_creation(curr);
515 Thread *waiting, *blocking;
516 waiting = get_thread(curr);
517 blocking = (Thread *)curr->get_location();
518 if (!blocking->is_complete()) {
519 blocking->push_wait_list(curr);
520 scheduler->sleep(waiting);
522 do_complete_join(curr);
523 updated = true; /* trigger rel-seq checks */
527 case THREAD_FINISH: {
528 Thread *th = get_thread(curr);
529 while (!th->wait_list_empty()) {
530 ModelAction *act = th->pop_wait_list();
531 Thread *wake = get_thread(act);
532 scheduler->wake(wake);
533 do_complete_join(act);
534 updated = true; /* trigger rel-seq checks */
537 updated = true; /* trigger rel-seq checks */
541 check_promises(curr->get_tid(), NULL, curr->get_cv());
552 * @brief Process the current action for release sequence fixup activity
554 * Performs model-checker release sequence fixups for the current action,
555 * forcing a single pending release sequence to break (with a given, potential
556 * "loose" write) or to complete (i.e., synchronize). If a pending release
557 * sequence forms a complete release sequence, then we must perform the fixup
558 * synchronization, mo_graph additions, etc.
560 * @param curr The current action; must be a release sequence fixup action
561 * @param work_queue The work queue to which to add work items as they are
564 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
566 const ModelAction *write = curr->get_node()->get_relseq_break();
567 struct release_seq *sequence = pending_rel_seqs->back();
568 pending_rel_seqs->pop_back();
570 ModelAction *acquire = sequence->acquire;
571 const ModelAction *rf = sequence->rf;
572 const ModelAction *release = sequence->release;
576 ASSERT(release->same_thread(rf));
579 /* Must synchronize */
580 if (!acquire->synchronize_with(release)) {
581 set_bad_synchronization();
584 /* Re-check all pending release sequences */
585 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
586 /* Re-check act for mo_graph edges */
587 work_queue->push_back(MOEdgeWorkEntry(acquire));
589 /* propagate synchronization to later actions */
590 action_list_t::reverse_iterator rit = action_trace->rbegin();
591 for (; (*rit) != acquire; rit++) {
592 ModelAction *propagate = *rit;
593 if (acquire->happens_before(propagate)) {
594 propagate->synchronize_with(acquire);
595 /* Re-check 'propagate' for mo_graph edges */
596 work_queue->push_back(MOEdgeWorkEntry(propagate));
600 /* Break release sequence with new edges:
601 * release --mo--> write --mo--> rf */
602 mo_graph->addEdge(release, write);
603 mo_graph->addEdge(write, rf);
608 * Initialize the current action by performing one or more of the following
609 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
610 * in the NodeStack, manipulating backtracking sets, allocating and
611 * initializing clock vectors, and computing the promises to fulfill.
613 * @param curr The current action, as passed from the user context; may be
614 * freed/invalidated after the execution of this function
615 * @return The current action, as processed by the ModelChecker. Is only the
616 * same as the parameter @a curr if this is a newly-explored action.
618 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
620 ModelAction *newcurr;
622 if (curr->is_rmwc() || curr->is_rmw()) {
623 newcurr = process_rmw(curr);
626 if (newcurr->is_rmw())
627 compute_promises(newcurr);
631 curr->set_seq_number(get_next_seq_num());
633 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
635 /* First restore type and order in case of RMW operation */
637 newcurr->copy_typeandorder(curr);
639 ASSERT(curr->get_location() == newcurr->get_location());
640 newcurr->copy_from_new(curr);
642 /* Discard duplicate ModelAction; use action from NodeStack */
645 /* Always compute new clock vector */
646 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
650 /* Always compute new clock vector */
651 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
653 * Perform one-time actions when pushing new ModelAction onto
656 if (newcurr->is_write())
657 compute_promises(newcurr);
658 else if (newcurr->is_relseq_fixup())
659 compute_relseq_breakwrites(newcurr);
665 * This method checks whether a model action is enabled at the given point.
666 * At this point, it checks whether a lock operation would be successful at this point.
667 * If not, it puts the thread in a waiter list.
668 * @param curr is the ModelAction to check whether it is enabled.
669 * @return a bool that indicates whether the action is enabled.
671 bool ModelChecker::check_action_enabled(ModelAction *curr) {
672 if (curr->is_lock()) {
673 std::mutex * lock = (std::mutex *)curr->get_location();
674 struct std::mutex_state * state = lock->get_state();
675 if (state->islocked) {
676 //Stick the action in the appropriate waiting queue
677 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
686 * This is the heart of the model checker routine. It performs model-checking
687 * actions corresponding to a given "current action." Among other processes, it
688 * calculates reads-from relationships, updates synchronization clock vectors,
689 * forms a memory_order constraints graph, and handles replay/backtrack
690 * execution when running permutations of previously-observed executions.
692 * @param curr The current action to process
693 * @return The next Thread that must be executed. May be NULL if ModelChecker
694 * makes no choice (e.g., according to replay execution, combining RMW actions,
697 Thread * ModelChecker::check_current_action(ModelAction *curr)
701 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
703 if (!check_action_enabled(curr)) {
704 /* Make the execution look like we chose to run this action
705 * much later, when a lock is actually available to release */
706 get_current_thread()->set_pending(curr);
707 scheduler->sleep(get_current_thread());
708 return get_next_thread(NULL);
711 ModelAction *newcurr = initialize_curr_action(curr);
713 /* Add the action to lists before any other model-checking tasks */
714 if (!second_part_of_rmw)
715 add_action_to_lists(newcurr);
717 /* Build may_read_from set for newly-created actions */
718 if (curr == newcurr && curr->is_read())
719 build_reads_from_past(curr);
722 /* Initialize work_queue with the "current action" work */
723 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
725 while (!work_queue.empty()) {
726 WorkQueueEntry work = work_queue.front();
727 work_queue.pop_front();
730 case WORK_CHECK_CURR_ACTION: {
731 ModelAction *act = work.action;
732 bool update = false; /* update this location's release seq's */
733 bool update_all = false; /* update all release seq's */
735 if (process_thread_action(curr))
738 if (act->is_read() && process_read(act, second_part_of_rmw))
741 if (act->is_write() && process_write(act))
744 if (act->is_mutex_op() && process_mutex(act))
747 if (act->is_relseq_fixup())
748 process_relseq_fixup(curr, &work_queue);
751 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
753 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
756 case WORK_CHECK_RELEASE_SEQ:
757 resolve_release_sequences(work.location, &work_queue);
759 case WORK_CHECK_MO_EDGES: {
760 /** @todo Complete verification of work_queue */
761 ModelAction *act = work.action;
762 bool updated = false;
764 if (act->is_read()) {
765 const ModelAction *rf = act->get_reads_from();
766 if (rf != NULL && r_modification_order(act, rf))
769 if (act->is_write()) {
770 if (w_modification_order(act))
773 mo_graph->commitChanges();
776 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
785 check_curr_backtracking(curr);
787 set_backtracking(curr);
789 return get_next_thread(curr);
793 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
794 * operation from the Thread it is joining with. Must be called after the
795 * completion of the Thread in question.
796 * @param join The THREAD_JOIN action
798 void ModelChecker::do_complete_join(ModelAction *join)
800 Thread *blocking = (Thread *)join->get_location();
801 ModelAction *act = get_last_action(blocking->get_id());
802 join->synchronize_with(act);
805 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
806 Node *currnode = curr->get_node();
807 Node *parnode = currnode->get_parent();
809 if ((!parnode->backtrack_empty() ||
810 !currnode->read_from_empty() ||
811 !currnode->future_value_empty() ||
812 !currnode->promise_empty() ||
813 !currnode->relseq_break_empty())
814 && (!priv->next_backtrack ||
815 *curr > *priv->next_backtrack)) {
816 priv->next_backtrack = curr;
820 bool ModelChecker::promises_expired() {
821 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
822 Promise *promise = (*promises)[promise_index];
823 if (promise->get_expiration()<priv->used_sequence_numbers) {
830 /** @return whether the current partial trace must be a prefix of a
832 bool ModelChecker::isfeasibleprefix() {
833 return promises->size() == 0 && pending_rel_seqs->size() == 0;
836 /** @return whether the current partial trace is feasible. */
837 bool ModelChecker::isfeasible() {
838 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
839 DEBUG("Infeasible: RMW violation\n");
841 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
844 /** @return whether the current partial trace is feasible other than
845 * multiple RMW reading from the same store. */
846 bool ModelChecker::isfeasibleotherthanRMW() {
848 if (mo_graph->checkForCycles())
849 DEBUG("Infeasible: modification order cycles\n");
851 DEBUG("Infeasible: failed promise\n");
853 DEBUG("Infeasible: too many reads\n");
854 if (bad_synchronization)
855 DEBUG("Infeasible: bad synchronization ordering\n");
856 if (promises_expired())
857 DEBUG("Infeasible: promises expired\n");
859 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
862 /** Returns whether the current completed trace is feasible. */
863 bool ModelChecker::isfinalfeasible() {
864 if (DBG_ENABLED() && promises->size() != 0)
865 DEBUG("Infeasible: unrevolved promises\n");
867 return isfeasible() && promises->size() == 0;
870 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
871 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
872 ModelAction *lastread = get_last_action(act->get_tid());
873 lastread->process_rmw(act);
874 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
875 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
876 mo_graph->commitChanges();
882 * Checks whether a thread has read from the same write for too many times
883 * without seeing the effects of a later write.
886 * 1) there must a different write that we could read from that would satisfy the modification order,
887 * 2) we must have read from the same value in excess of maxreads times, and
888 * 3) that other write must have been in the reads_from set for maxreads times.
890 * If so, we decide that the execution is no longer feasible.
892 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
893 if (params.maxreads != 0) {
895 if (curr->get_node()->get_read_from_size() <= 1)
897 //Must make sure that execution is currently feasible... We could
898 //accidentally clear by rolling back
901 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
902 int tid = id_to_int(curr->get_tid());
905 if ((int)thrd_lists->size() <= tid)
907 action_list_t *list = &(*thrd_lists)[tid];
909 action_list_t::reverse_iterator rit = list->rbegin();
911 for (; (*rit) != curr; rit++)
913 /* go past curr now */
916 action_list_t::reverse_iterator ritcopy = rit;
917 //See if we have enough reads from the same value
919 for (; count < params.maxreads; rit++,count++) {
920 if (rit==list->rend())
922 ModelAction *act = *rit;
926 if (act->get_reads_from() != rf)
928 if (act->get_node()->get_read_from_size() <= 1)
931 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
933 const ModelAction * write = curr->get_node()->get_read_from_at(i);
935 //Need a different write
939 /* Test to see whether this is a feasible write to read from*/
940 mo_graph->startChanges();
941 r_modification_order(curr, write);
942 bool feasiblereadfrom = isfeasible();
943 mo_graph->rollbackChanges();
945 if (!feasiblereadfrom)
949 bool feasiblewrite = true;
950 //new we need to see if this write works for everyone
952 for (int loop = count; loop>0; loop--,rit++) {
953 ModelAction *act=*rit;
954 bool foundvalue = false;
955 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
956 if (act->get_node()->get_read_from_at(i)==write) {
962 feasiblewrite = false;
967 too_many_reads = true;
975 * Updates the mo_graph with the constraints imposed from the current
978 * Basic idea is the following: Go through each other thread and find
979 * the lastest action that happened before our read. Two cases:
981 * (1) The action is a write => that write must either occur before
982 * the write we read from or be the write we read from.
984 * (2) The action is a read => the write that that action read from
985 * must occur before the write we read from or be the same write.
987 * @param curr The current action. Must be a read.
988 * @param rf The action that curr reads from. Must be a write.
989 * @return True if modification order edges were added; false otherwise
991 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
993 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
996 ASSERT(curr->is_read());
998 /* Iterate over all threads */
999 for (i = 0; i < thrd_lists->size(); i++) {
1000 /* Iterate over actions in thread, starting from most recent */
1001 action_list_t *list = &(*thrd_lists)[i];
1002 action_list_t::reverse_iterator rit;
1003 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1004 ModelAction *act = *rit;
1007 * Include at most one act per-thread that "happens
1008 * before" curr. Don't consider reflexively.
1010 if (act->happens_before(curr) && act != curr) {
1011 if (act->is_write()) {
1013 mo_graph->addEdge(act, rf);
1017 const ModelAction *prevreadfrom = act->get_reads_from();
1018 //if the previous read is unresolved, keep going...
1019 if (prevreadfrom == NULL)
1022 if (rf != prevreadfrom) {
1023 mo_graph->addEdge(prevreadfrom, rf);
1035 /** This method fixes up the modification order when we resolve a
1036 * promises. The basic problem is that actions that occur after the
1037 * read curr could not property add items to the modification order
1040 * So for each thread, we find the earliest item that happens after
1041 * the read curr. This is the item we have to fix up with additional
1042 * constraints. If that action is write, we add a MO edge between
1043 * the Action rf and that action. If the action is a read, we add a
1044 * MO edge between the Action rf, and whatever the read accessed.
1046 * @param curr is the read ModelAction that we are fixing up MO edges for.
1047 * @param rf is the write ModelAction that curr reads from.
1050 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1052 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1054 ASSERT(curr->is_read());
1056 /* Iterate over all threads */
1057 for (i = 0; i < thrd_lists->size(); i++) {
1058 /* Iterate over actions in thread, starting from most recent */
1059 action_list_t *list = &(*thrd_lists)[i];
1060 action_list_t::reverse_iterator rit;
1061 ModelAction *lastact = NULL;
1063 /* Find last action that happens after curr that is either not curr or a rmw */
1064 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1065 ModelAction *act = *rit;
1066 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1072 /* Include at most one act per-thread that "happens before" curr */
1073 if (lastact != NULL) {
1074 if (lastact==curr) {
1075 //Case 1: The resolved read is a RMW, and we need to make sure
1076 //that the write portion of the RMW mod order after rf
1078 mo_graph->addEdge(rf, lastact);
1079 } else if (lastact->is_read()) {
1080 //Case 2: The resolved read is a normal read and the next
1081 //operation is a read, and we need to make sure the value read
1082 //is mod ordered after rf
1084 const ModelAction *postreadfrom = lastact->get_reads_from();
1085 if (postreadfrom != NULL&&rf != postreadfrom)
1086 mo_graph->addEdge(rf, postreadfrom);
1088 //Case 3: The resolved read is a normal read and the next
1089 //operation is a write, and we need to make sure that the
1090 //write is mod ordered after rf
1092 mo_graph->addEdge(rf, lastact);
1100 * Updates the mo_graph with the constraints imposed from the current write.
1102 * Basic idea is the following: Go through each other thread and find
1103 * the lastest action that happened before our write. Two cases:
1105 * (1) The action is a write => that write must occur before
1108 * (2) The action is a read => the write that that action read from
1109 * must occur before the current write.
1111 * This method also handles two other issues:
1113 * (I) Sequential Consistency: Making sure that if the current write is
1114 * seq_cst, that it occurs after the previous seq_cst write.
1116 * (II) Sending the write back to non-synchronizing reads.
1118 * @param curr The current action. Must be a write.
1119 * @return True if modification order edges were added; false otherwise
1121 bool ModelChecker::w_modification_order(ModelAction *curr)
1123 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1126 ASSERT(curr->is_write());
1128 if (curr->is_seqcst()) {
1129 /* We have to at least see the last sequentially consistent write,
1130 so we are initialized. */
1131 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1132 if (last_seq_cst != NULL) {
1133 mo_graph->addEdge(last_seq_cst, curr);
1138 /* Iterate over all threads */
1139 for (i = 0; i < thrd_lists->size(); i++) {
1140 /* Iterate over actions in thread, starting from most recent */
1141 action_list_t *list = &(*thrd_lists)[i];
1142 action_list_t::reverse_iterator rit;
1143 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1144 ModelAction *act = *rit;
1147 * 1) If RMW and it actually read from something, then we
1148 * already have all relevant edges, so just skip to next
1151 * 2) If RMW and it didn't read from anything, we should
1152 * whatever edge we can get to speed up convergence.
1154 * 3) If normal write, we need to look at earlier actions, so
1155 * continue processing list.
1157 if (curr->is_rmw()) {
1158 if (curr->get_reads_from()!=NULL)
1167 * Include at most one act per-thread that "happens
1170 if (act->happens_before(curr)) {
1172 * Note: if act is RMW, just add edge:
1174 * The following edge should be handled elsewhere:
1175 * readfrom(act) --mo--> act
1177 if (act->is_write())
1178 mo_graph->addEdge(act, curr);
1179 else if (act->is_read()) {
1180 //if previous read accessed a null, just keep going
1181 if (act->get_reads_from() == NULL)
1183 mo_graph->addEdge(act->get_reads_from(), curr);
1187 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1188 !act->same_thread(curr)) {
1189 /* We have an action that:
1190 (1) did not happen before us
1191 (2) is a read and we are a write
1192 (3) cannot synchronize with us
1193 (4) is in a different thread
1195 that read could potentially read from our write.
1197 if (thin_air_constraint_may_allow(curr, act)) {
1199 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1200 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1201 futurevalues->push_back(pfv);
1211 /** Arbitrary reads from the future are not allowed. Section 29.3
1212 * part 9 places some constraints. This method checks one result of constraint
1213 * constraint. Others require compiler support. */
1214 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1215 if (!writer->is_rmw())
1218 if (!reader->is_rmw())
1221 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1222 if (search == reader)
1224 if (search->get_tid() == reader->get_tid() &&
1225 search->happens_before(reader))
1233 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1234 * The ModelAction under consideration is expected to be taking part in
1235 * release/acquire synchronization as an object of the "reads from" relation.
1236 * Note that this can only provide release sequence support for RMW chains
1237 * which do not read from the future, as those actions cannot be traced until
1238 * their "promise" is fulfilled. Similarly, we may not even establish the
1239 * presence of a release sequence with certainty, as some modification order
1240 * constraints may be decided further in the future. Thus, this function
1241 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1242 * and a boolean representing certainty.
1244 * @todo Finish lazy updating, when promises are fulfilled in the future
1245 * @param rf The action that might be part of a release sequence. Must be a
1247 * @param release_heads A pass-by-reference style return parameter. After
1248 * execution of this function, release_heads will contain the heads of all the
1249 * relevant release sequences, if any exists with certainty
1250 * @param pending A pass-by-reference style return parameter which is only used
1251 * when returning false (i.e., uncertain). Returns most information regarding
1252 * an uncertain release sequence, including any write operations that might
1253 * break the sequence.
1254 * @return true, if the ModelChecker is certain that release_heads is complete;
1257 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1258 rel_heads_list_t *release_heads,
1259 struct release_seq *pending) const
1261 /* Only check for release sequences if there are no cycles */
1262 if (mo_graph->checkForCycles())
1266 ASSERT(rf->is_write());
1268 if (rf->is_release())
1269 release_heads->push_back(rf);
1271 break; /* End of RMW chain */
1273 /** @todo Need to be smarter here... In the linux lock
1274 * example, this will run to the beginning of the program for
1276 /** @todo The way to be smarter here is to keep going until 1
1277 * thread has a release preceded by an acquire and you've seen
1280 /* acq_rel RMW is a sufficient stopping condition */
1281 if (rf->is_acquire() && rf->is_release())
1282 return true; /* complete */
1284 rf = rf->get_reads_from();
1287 /* read from future: need to settle this later */
1289 return false; /* incomplete */
1292 if (rf->is_release())
1293 return true; /* complete */
1295 /* else relaxed write; check modification order for contiguous subsequence
1296 * -> rf must be same thread as release */
1297 int tid = id_to_int(rf->get_tid());
1298 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1299 action_list_t *list = &(*thrd_lists)[tid];
1300 action_list_t::const_reverse_iterator rit;
1302 /* Find rf in the thread list */
1303 rit = std::find(list->rbegin(), list->rend(), rf);
1304 ASSERT(rit != list->rend());
1306 /* Find the last write/release */
1307 for (; rit != list->rend(); rit++)
1308 if ((*rit)->is_release())
1310 if (rit == list->rend()) {
1311 /* No write-release in this thread */
1312 return true; /* complete */
1314 ModelAction *release = *rit;
1316 ASSERT(rf->same_thread(release));
1318 pending->writes.clear();
1320 bool certain = true;
1321 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1322 if (id_to_int(rf->get_tid()) == (int)i)
1324 list = &(*thrd_lists)[i];
1326 /* Can we ensure no future writes from this thread may break
1327 * the release seq? */
1328 bool future_ordered = false;
1330 ModelAction *last = get_last_action(int_to_id(i));
1331 Thread *th = get_thread(int_to_id(i));
1332 if ((last && rf->happens_before(last)) ||
1333 !scheduler->is_enabled(th) ||
1335 future_ordered = true;
1337 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1338 const ModelAction *act = *rit;
1339 /* Reach synchronization -> this thread is complete */
1340 if (act->happens_before(release))
1342 if (rf->happens_before(act)) {
1343 future_ordered = true;
1347 /* Only writes can break release sequences */
1348 if (!act->is_write())
1351 /* Check modification order */
1352 if (mo_graph->checkReachable(rf, act)) {
1353 /* rf --mo--> act */
1354 future_ordered = true;
1357 if (mo_graph->checkReachable(act, release))
1358 /* act --mo--> release */
1360 if (mo_graph->checkReachable(release, act) &&
1361 mo_graph->checkReachable(act, rf)) {
1362 /* release --mo-> act --mo--> rf */
1363 return true; /* complete */
1365 /* act may break release sequence */
1366 pending->writes.push_back(act);
1369 if (!future_ordered)
1370 certain = false; /* This thread is uncertain */
1374 release_heads->push_back(release);
1375 pending->writes.clear();
1377 pending->release = release;
1384 * A public interface for getting the release sequence head(s) with which a
1385 * given ModelAction must synchronize. This function only returns a non-empty
1386 * result when it can locate a release sequence head with certainty. Otherwise,
1387 * it may mark the internal state of the ModelChecker so that it will handle
1388 * the release sequence at a later time, causing @a act to update its
1389 * synchronization at some later point in execution.
1390 * @param act The 'acquire' action that may read from a release sequence
1391 * @param release_heads A pass-by-reference return parameter. Will be filled
1392 * with the head(s) of the release sequence(s), if they exists with certainty.
1393 * @see ModelChecker::release_seq_heads
1395 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1397 const ModelAction *rf = act->get_reads_from();
1398 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1399 sequence->acquire = act;
1401 if (!release_seq_heads(rf, release_heads, sequence)) {
1402 /* add act to 'lazy checking' list */
1403 pending_rel_seqs->push_back(sequence);
1405 snapshot_free(sequence);
1410 * Attempt to resolve all stashed operations that might synchronize with a
1411 * release sequence for a given location. This implements the "lazy" portion of
1412 * determining whether or not a release sequence was contiguous, since not all
1413 * modification order information is present at the time an action occurs.
1415 * @param location The location/object that should be checked for release
1416 * sequence resolutions. A NULL value means to check all locations.
1417 * @param work_queue The work queue to which to add work items as they are
1419 * @return True if any updates occurred (new synchronization, new mo_graph
1422 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1424 bool updated = false;
1425 std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1426 while (it != pending_rel_seqs->end()) {
1427 struct release_seq *pending = *it;
1428 ModelAction *act = pending->acquire;
1430 /* Only resolve sequences on the given location, if provided */
1431 if (location && act->get_location() != location) {
1436 const ModelAction *rf = act->get_reads_from();
1437 rel_heads_list_t release_heads;
1439 complete = release_seq_heads(rf, &release_heads, pending);
1440 for (unsigned int i = 0; i < release_heads.size(); i++) {
1441 if (!act->has_synchronized_with(release_heads[i])) {
1442 if (act->synchronize_with(release_heads[i]))
1445 set_bad_synchronization();
1450 /* Re-check all pending release sequences */
1451 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1452 /* Re-check act for mo_graph edges */
1453 work_queue->push_back(MOEdgeWorkEntry(act));
1455 /* propagate synchronization to later actions */
1456 action_list_t::reverse_iterator rit = action_trace->rbegin();
1457 for (; (*rit) != act; rit++) {
1458 ModelAction *propagate = *rit;
1459 if (act->happens_before(propagate)) {
1460 propagate->synchronize_with(act);
1461 /* Re-check 'propagate' for mo_graph edges */
1462 work_queue->push_back(MOEdgeWorkEntry(propagate));
1467 it = pending_rel_seqs->erase(it);
1468 snapshot_free(pending);
1474 // If we resolved promises or data races, see if we have realized a data race.
1475 if (checkDataRaces()) {
1483 * Performs various bookkeeping operations for the current ModelAction. For
1484 * instance, adds action to the per-object, per-thread action vector and to the
1485 * action trace list of all thread actions.
1487 * @param act is the ModelAction to add.
1489 void ModelChecker::add_action_to_lists(ModelAction *act)
1491 int tid = id_to_int(act->get_tid());
1492 action_trace->push_back(act);
1494 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1496 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1497 if (tid >= (int)vec->size())
1498 vec->resize(priv->next_thread_id);
1499 (*vec)[tid].push_back(act);
1501 if ((int)thrd_last_action->size() <= tid)
1502 thrd_last_action->resize(get_num_threads());
1503 (*thrd_last_action)[tid] = act;
1507 * @brief Get the last action performed by a particular Thread
1508 * @param tid The thread ID of the Thread in question
1509 * @return The last action in the thread
1511 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1513 int threadid = id_to_int(tid);
1514 if (threadid < (int)thrd_last_action->size())
1515 return (*thrd_last_action)[id_to_int(tid)];
1521 * Gets the last memory_order_seq_cst write (in the total global sequence)
1522 * performed on a particular object (i.e., memory location), not including the
1524 * @param curr The current ModelAction; also denotes the object location to
1526 * @return The last seq_cst write
1528 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1530 void *location = curr->get_location();
1531 action_list_t *list = obj_map->get_safe_ptr(location);
1532 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1533 action_list_t::reverse_iterator rit;
1534 for (rit = list->rbegin(); rit != list->rend(); rit++)
1535 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1541 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1542 * location). This function identifies the mutex according to the current
1543 * action, which is presumed to perform on the same mutex.
1544 * @param curr The current ModelAction; also denotes the object location to
1546 * @return The last unlock operation
1548 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1550 void *location = curr->get_location();
1551 action_list_t *list = obj_map->get_safe_ptr(location);
1552 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1553 action_list_t::reverse_iterator rit;
1554 for (rit = list->rbegin(); rit != list->rend(); rit++)
1555 if ((*rit)->is_unlock())
1560 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1562 ModelAction *parent = get_last_action(tid);
1564 parent = get_thread(tid)->get_creation();
1569 * Returns the clock vector for a given thread.
1570 * @param tid The thread whose clock vector we want
1571 * @return Desired clock vector
1573 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1575 return get_parent_action(tid)->get_cv();
1579 * Resolve a set of Promises with a current write. The set is provided in the
1580 * Node corresponding to @a write.
1581 * @param write The ModelAction that is fulfilling Promises
1582 * @return True if promises were resolved; false otherwise
1584 bool ModelChecker::resolve_promises(ModelAction *write)
1586 bool resolved = false;
1587 std::vector<thread_id_t> threads_to_check;
1589 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1590 Promise *promise = (*promises)[promise_index];
1591 if (write->get_node()->get_promise(i)) {
1592 ModelAction *read = promise->get_action();
1593 if (read->is_rmw()) {
1594 mo_graph->addRMWEdge(write, read);
1596 read->read_from(write);
1597 //First fix up the modification order for actions that happened
1599 r_modification_order(read, write);
1600 //Next fix up the modification order for actions that happened
1602 post_r_modification_order(read, write);
1603 //Make sure the promise's value matches the write's value
1604 ASSERT(promise->get_value() == write->get_value());
1607 promises->erase(promises->begin() + promise_index);
1608 threads_to_check.push_back(read->get_tid());
1615 //Check whether reading these writes has made threads unable to
1618 for(unsigned int i=0;i<threads_to_check.size();i++)
1619 mo_check_promises(threads_to_check[i], write);
1625 * Compute the set of promises that could potentially be satisfied by this
1626 * action. Note that the set computation actually appears in the Node, not in
1628 * @param curr The ModelAction that may satisfy promises
1630 void ModelChecker::compute_promises(ModelAction *curr)
1632 for (unsigned int i = 0; i < promises->size(); i++) {
1633 Promise *promise = (*promises)[i];
1634 const ModelAction *act = promise->get_action();
1635 if (!act->happens_before(curr) &&
1637 !act->could_synchronize_with(curr) &&
1638 !act->same_thread(curr) &&
1639 promise->get_value() == curr->get_value()) {
1640 curr->get_node()->set_promise(i);
1645 /** Checks promises in response to change in ClockVector Threads. */
1646 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1648 for (unsigned int i = 0; i < promises->size(); i++) {
1649 Promise *promise = (*promises)[i];
1650 const ModelAction *act = promise->get_action();
1651 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1652 merge_cv->synchronized_since(act)) {
1653 if (promise->increment_threads(tid)) {
1654 //Promise has failed
1655 failed_promise = true;
1662 /** Checks promises in response to addition to modification order for threads.
1664 * pthread is the thread that performed the read that created the promise
1666 * pread is the read that created the promise
1668 * pwrite is either the first write to same location as pread by
1669 * pthread that is sequenced after pread or the value read by the
1670 * first read to the same lcoation as pread by pthread that is
1671 * sequenced after pread..
1673 * 1. If tid=pthread, then we check what other threads are reachable
1674 * through the mode order starting with pwrite. Those threads cannot
1675 * perform a write that will resolve the promise due to modification
1676 * order constraints.
1678 * 2. If the tid is not pthread, we check whether pwrite can reach the
1679 * action write through the modification order. If so, that thread
1680 * cannot perform a future write that will resolve the promise due to
1681 * modificatin order constraints.
1683 * @parem tid The thread that either read from the model action
1684 * write, or actually did the model action write.
1686 * @parem write The ModelAction representing the relevant write.
1689 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1690 void * location = write->get_location();
1691 for (unsigned int i = 0; i < promises->size(); i++) {
1692 Promise *promise = (*promises)[i];
1693 const ModelAction *act = promise->get_action();
1695 //Is this promise on the same location?
1696 if ( act->get_location() != location )
1699 //same thread as the promise
1700 if ( act->get_tid()==tid ) {
1702 //do we have a pwrite for the promise, if not, set it
1703 if (promise->get_write() == NULL ) {
1704 promise->set_write(write);
1706 if (mo_graph->checkPromise(write, promise)) {
1707 failed_promise = true;
1712 //Don't do any lookups twice for the same thread
1713 if (promise->has_sync_thread(tid))
1716 if (mo_graph->checkReachable(promise->get_write(), write)) {
1717 if (promise->increment_threads(tid)) {
1718 failed_promise = true;
1726 * Compute the set of writes that may break the current pending release
1727 * sequence. This information is extracted from previou release sequence
1730 * @param curr The current ModelAction. Must be a release sequence fixup
1733 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1735 if (pending_rel_seqs->empty())
1738 struct release_seq *pending = pending_rel_seqs->back();
1739 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1740 const ModelAction *write = pending->writes[i];
1741 curr->get_node()->add_relseq_break(write);
1744 /* NULL means don't break the sequence; just synchronize */
1745 curr->get_node()->add_relseq_break(NULL);
1749 * Build up an initial set of all past writes that this 'read' action may read
1750 * from. This set is determined by the clock vector's "happens before"
1752 * @param curr is the current ModelAction that we are exploring; it must be a
1755 void ModelChecker::build_reads_from_past(ModelAction *curr)
1757 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1759 ASSERT(curr->is_read());
1761 ModelAction *last_seq_cst = NULL;
1763 /* Track whether this object has been initialized */
1764 bool initialized = false;
1766 if (curr->is_seqcst()) {
1767 last_seq_cst = get_last_seq_cst(curr);
1768 /* We have to at least see the last sequentially consistent write,
1769 so we are initialized. */
1770 if (last_seq_cst != NULL)
1774 /* Iterate over all threads */
1775 for (i = 0; i < thrd_lists->size(); i++) {
1776 /* Iterate over actions in thread, starting from most recent */
1777 action_list_t *list = &(*thrd_lists)[i];
1778 action_list_t::reverse_iterator rit;
1779 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1780 ModelAction *act = *rit;
1782 /* Only consider 'write' actions */
1783 if (!act->is_write() || act == curr)
1786 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1787 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1788 DEBUG("Adding action to may_read_from:\n");
1789 if (DBG_ENABLED()) {
1793 curr->get_node()->add_read_from(act);
1796 /* Include at most one act per-thread that "happens before" curr */
1797 if (act->happens_before(curr)) {
1805 /** @todo Need a more informative way of reporting errors. */
1806 printf("ERROR: may read from uninitialized atomic\n");
1809 if (DBG_ENABLED() || !initialized) {
1810 printf("Reached read action:\n");
1812 printf("Printing may_read_from\n");
1813 curr->get_node()->print_may_read_from();
1814 printf("End printing may_read_from\n");
1817 ASSERT(initialized);
1820 static void print_list(action_list_t *list)
1822 action_list_t::iterator it;
1824 printf("---------------------------------------------------------------------\n");
1827 for (it = list->begin(); it != list->end(); it++) {
1830 printf("---------------------------------------------------------------------\n");
1833 #if SUPPORT_MOD_ORDER_DUMP
1834 void ModelChecker::dumpGraph(char *filename) {
1836 sprintf(buffer, "%s.dot",filename);
1837 FILE *file=fopen(buffer, "w");
1838 fprintf(file, "digraph %s {\n",filename);
1839 mo_graph->dumpNodes(file);
1840 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1842 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1843 ModelAction *action=*it;
1844 if (action->is_read()) {
1845 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1846 if (action->get_reads_from()!=NULL)
1847 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1849 if (thread_array[action->get_tid()] != NULL) {
1850 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1853 thread_array[action->get_tid()]=action;
1855 fprintf(file,"}\n");
1856 model_free(thread_array);
1861 void ModelChecker::print_summary()
1864 printf("Number of executions: %d\n", num_executions);
1865 printf("Number of feasible executions: %d\n", num_feasible_executions);
1866 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1868 #if SUPPORT_MOD_ORDER_DUMP
1870 char buffername[100];
1871 sprintf(buffername, "exec%04u", num_executions);
1872 mo_graph->dumpGraphToFile(buffername);
1873 sprintf(buffername, "graph%04u", num_executions);
1874 dumpGraph(buffername);
1877 if (!isfinalfeasible())
1878 printf("INFEASIBLE EXECUTION!\n");
1879 print_list(action_trace);
1884 * Add a Thread to the system for the first time. Should only be called once
1886 * @param t The Thread to add
1888 void ModelChecker::add_thread(Thread *t)
1890 thread_map->put(id_to_int(t->get_id()), t);
1891 scheduler->add_thread(t);
1895 * Removes a thread from the scheduler.
1896 * @param the thread to remove.
1898 void ModelChecker::remove_thread(Thread *t)
1900 scheduler->remove_thread(t);
1904 * @brief Get a Thread reference by its ID
1905 * @param tid The Thread's ID
1906 * @return A Thread reference
1908 Thread * ModelChecker::get_thread(thread_id_t tid) const
1910 return thread_map->get(id_to_int(tid));
1914 * @brief Get a reference to the Thread in which a ModelAction was executed
1915 * @param act The ModelAction
1916 * @return A Thread reference
1918 Thread * ModelChecker::get_thread(ModelAction *act) const
1920 return get_thread(act->get_tid());
1924 * Switch from a user-context to the "master thread" context (a.k.a. system
1925 * context). This switch is made with the intention of exploring a particular
1926 * model-checking action (described by a ModelAction object). Must be called
1927 * from a user-thread context.
1929 * @param act The current action that will be explored. May be NULL only if
1930 * trace is exiting via an assertion (see ModelChecker::set_assert and
1931 * ModelChecker::has_asserted).
1932 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1934 int ModelChecker::switch_to_master(ModelAction *act)
1937 Thread *old = thread_current();
1938 set_current_action(act);
1939 old->set_state(THREAD_READY);
1940 return Thread::swap(old, &system_context);
1944 * Takes the next step in the execution, if possible.
1945 * @return Returns true (success) if a step was taken and false otherwise.
1947 bool ModelChecker::take_step() {
1951 Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1953 if (curr->get_state() == THREAD_READY) {
1954 ASSERT(priv->current_action);
1956 priv->nextThread = check_current_action(priv->current_action);
1957 priv->current_action = NULL;
1959 if (curr->is_blocked() || curr->is_complete())
1960 scheduler->remove_thread(curr);
1965 Thread *next = scheduler->next_thread(priv->nextThread);
1967 /* Infeasible -> don't take any more steps */
1971 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1972 next ? id_to_int(next->get_id()) : -1);
1974 /* next == NULL -> don't take any more steps */
1978 next->set_state(THREAD_RUNNING);
1980 if (next->get_pending() != NULL) {
1981 /* restart a pending action */
1982 set_current_action(next->get_pending());
1983 next->set_pending(NULL);
1984 next->set_state(THREAD_READY);
1988 /* Return false only if swap fails with an error */
1989 return (Thread::swap(&system_context, next) == 0);
1992 /** Runs the current execution until threre are no more steps to take. */
1993 void ModelChecker::finish_execution() {
1996 while (take_step());