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);
606 /* See if we have realized a data race */
607 if (checkDataRaces())
612 * Initialize the current action by performing one or more of the following
613 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
614 * in the NodeStack, manipulating backtracking sets, allocating and
615 * initializing clock vectors, and computing the promises to fulfill.
617 * @param curr The current action, as passed from the user context; may be
618 * freed/invalidated after the execution of this function
619 * @return The current action, as processed by the ModelChecker. Is only the
620 * same as the parameter @a curr if this is a newly-explored action.
622 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
624 ModelAction *newcurr;
626 if (curr->is_rmwc() || curr->is_rmw()) {
627 newcurr = process_rmw(curr);
630 if (newcurr->is_rmw())
631 compute_promises(newcurr);
635 curr->set_seq_number(get_next_seq_num());
637 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
639 /* First restore type and order in case of RMW operation */
641 newcurr->copy_typeandorder(curr);
643 ASSERT(curr->get_location() == newcurr->get_location());
644 newcurr->copy_from_new(curr);
646 /* Discard duplicate ModelAction; use action from NodeStack */
649 /* Always compute new clock vector */
650 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
654 /* Always compute new clock vector */
655 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
657 * Perform one-time actions when pushing new ModelAction onto
660 if (newcurr->is_write())
661 compute_promises(newcurr);
662 else if (newcurr->is_relseq_fixup())
663 compute_relseq_breakwrites(newcurr);
669 * This method checks whether a model action is enabled at the given point.
670 * At this point, it checks whether a lock operation would be successful at this point.
671 * If not, it puts the thread in a waiter list.
672 * @param curr is the ModelAction to check whether it is enabled.
673 * @return a bool that indicates whether the action is enabled.
675 bool ModelChecker::check_action_enabled(ModelAction *curr) {
676 if (curr->is_lock()) {
677 std::mutex * lock = (std::mutex *)curr->get_location();
678 struct std::mutex_state * state = lock->get_state();
679 if (state->islocked) {
680 //Stick the action in the appropriate waiting queue
681 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
690 * This is the heart of the model checker routine. It performs model-checking
691 * actions corresponding to a given "current action." Among other processes, it
692 * calculates reads-from relationships, updates synchronization clock vectors,
693 * forms a memory_order constraints graph, and handles replay/backtrack
694 * execution when running permutations of previously-observed executions.
696 * @param curr The current action to process
697 * @return The next Thread that must be executed. May be NULL if ModelChecker
698 * makes no choice (e.g., according to replay execution, combining RMW actions,
701 Thread * ModelChecker::check_current_action(ModelAction *curr)
705 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
707 if (!check_action_enabled(curr)) {
708 /* Make the execution look like we chose to run this action
709 * much later, when a lock is actually available to release */
710 get_current_thread()->set_pending(curr);
711 scheduler->sleep(get_current_thread());
712 return get_next_thread(NULL);
715 ModelAction *newcurr = initialize_curr_action(curr);
717 /* Add the action to lists before any other model-checking tasks */
718 if (!second_part_of_rmw)
719 add_action_to_lists(newcurr);
721 /* Build may_read_from set for newly-created actions */
722 if (curr == newcurr && curr->is_read())
723 build_reads_from_past(curr);
726 /* Initialize work_queue with the "current action" work */
727 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
729 while (!work_queue.empty()) {
730 WorkQueueEntry work = work_queue.front();
731 work_queue.pop_front();
734 case WORK_CHECK_CURR_ACTION: {
735 ModelAction *act = work.action;
736 bool update = false; /* update this location's release seq's */
737 bool update_all = false; /* update all release seq's */
739 if (process_thread_action(curr))
742 if (act->is_read() && process_read(act, second_part_of_rmw))
745 if (act->is_write() && process_write(act))
748 if (act->is_mutex_op() && process_mutex(act))
751 if (act->is_relseq_fixup())
752 process_relseq_fixup(curr, &work_queue);
755 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
757 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
760 case WORK_CHECK_RELEASE_SEQ:
761 resolve_release_sequences(work.location, &work_queue);
763 case WORK_CHECK_MO_EDGES: {
764 /** @todo Complete verification of work_queue */
765 ModelAction *act = work.action;
766 bool updated = false;
768 if (act->is_read()) {
769 const ModelAction *rf = act->get_reads_from();
770 if (rf != NULL && r_modification_order(act, rf))
773 if (act->is_write()) {
774 if (w_modification_order(act))
777 mo_graph->commitChanges();
780 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
789 check_curr_backtracking(curr);
791 set_backtracking(curr);
793 return get_next_thread(curr);
797 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
798 * operation from the Thread it is joining with. Must be called after the
799 * completion of the Thread in question.
800 * @param join The THREAD_JOIN action
802 void ModelChecker::do_complete_join(ModelAction *join)
804 Thread *blocking = (Thread *)join->get_location();
805 ModelAction *act = get_last_action(blocking->get_id());
806 join->synchronize_with(act);
809 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
810 Node *currnode = curr->get_node();
811 Node *parnode = currnode->get_parent();
813 if ((!parnode->backtrack_empty() ||
814 !currnode->read_from_empty() ||
815 !currnode->future_value_empty() ||
816 !currnode->promise_empty() ||
817 !currnode->relseq_break_empty())
818 && (!priv->next_backtrack ||
819 *curr > *priv->next_backtrack)) {
820 priv->next_backtrack = curr;
824 bool ModelChecker::promises_expired() {
825 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
826 Promise *promise = (*promises)[promise_index];
827 if (promise->get_expiration()<priv->used_sequence_numbers) {
834 /** @return whether the current partial trace must be a prefix of a
836 bool ModelChecker::isfeasibleprefix() {
837 return promises->size() == 0 && pending_rel_seqs->size() == 0;
840 /** @return whether the current partial trace is feasible. */
841 bool ModelChecker::isfeasible() {
842 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
843 DEBUG("Infeasible: RMW violation\n");
845 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
848 /** @return whether the current partial trace is feasible other than
849 * multiple RMW reading from the same store. */
850 bool ModelChecker::isfeasibleotherthanRMW() {
852 if (mo_graph->checkForCycles())
853 DEBUG("Infeasible: modification order cycles\n");
855 DEBUG("Infeasible: failed promise\n");
857 DEBUG("Infeasible: too many reads\n");
858 if (bad_synchronization)
859 DEBUG("Infeasible: bad synchronization ordering\n");
860 if (promises_expired())
861 DEBUG("Infeasible: promises expired\n");
863 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
866 /** Returns whether the current completed trace is feasible. */
867 bool ModelChecker::isfinalfeasible() {
868 if (DBG_ENABLED() && promises->size() != 0)
869 DEBUG("Infeasible: unrevolved promises\n");
871 return isfeasible() && promises->size() == 0;
874 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
875 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
876 ModelAction *lastread = get_last_action(act->get_tid());
877 lastread->process_rmw(act);
878 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
879 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
880 mo_graph->commitChanges();
886 * Checks whether a thread has read from the same write for too many times
887 * without seeing the effects of a later write.
890 * 1) there must a different write that we could read from that would satisfy the modification order,
891 * 2) we must have read from the same value in excess of maxreads times, and
892 * 3) that other write must have been in the reads_from set for maxreads times.
894 * If so, we decide that the execution is no longer feasible.
896 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
897 if (params.maxreads != 0) {
899 if (curr->get_node()->get_read_from_size() <= 1)
901 //Must make sure that execution is currently feasible... We could
902 //accidentally clear by rolling back
905 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
906 int tid = id_to_int(curr->get_tid());
909 if ((int)thrd_lists->size() <= tid)
911 action_list_t *list = &(*thrd_lists)[tid];
913 action_list_t::reverse_iterator rit = list->rbegin();
915 for (; (*rit) != curr; rit++)
917 /* go past curr now */
920 action_list_t::reverse_iterator ritcopy = rit;
921 //See if we have enough reads from the same value
923 for (; count < params.maxreads; rit++,count++) {
924 if (rit==list->rend())
926 ModelAction *act = *rit;
930 if (act->get_reads_from() != rf)
932 if (act->get_node()->get_read_from_size() <= 1)
935 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
937 const ModelAction * write = curr->get_node()->get_read_from_at(i);
939 //Need a different write
943 /* Test to see whether this is a feasible write to read from*/
944 mo_graph->startChanges();
945 r_modification_order(curr, write);
946 bool feasiblereadfrom = isfeasible();
947 mo_graph->rollbackChanges();
949 if (!feasiblereadfrom)
953 bool feasiblewrite = true;
954 //new we need to see if this write works for everyone
956 for (int loop = count; loop>0; loop--,rit++) {
957 ModelAction *act=*rit;
958 bool foundvalue = false;
959 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
960 if (act->get_node()->get_read_from_at(i)==write) {
966 feasiblewrite = false;
971 too_many_reads = true;
979 * Updates the mo_graph with the constraints imposed from the current
982 * Basic idea is the following: Go through each other thread and find
983 * the lastest action that happened before our read. Two cases:
985 * (1) The action is a write => that write must either occur before
986 * the write we read from or be the write we read from.
988 * (2) The action is a read => the write that that action read from
989 * must occur before the write we read from or be the same write.
991 * @param curr The current action. Must be a read.
992 * @param rf The action that curr reads from. Must be a write.
993 * @return True if modification order edges were added; false otherwise
995 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
997 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1000 ASSERT(curr->is_read());
1002 /* Iterate over all threads */
1003 for (i = 0; i < thrd_lists->size(); i++) {
1004 /* Iterate over actions in thread, starting from most recent */
1005 action_list_t *list = &(*thrd_lists)[i];
1006 action_list_t::reverse_iterator rit;
1007 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1008 ModelAction *act = *rit;
1011 * Include at most one act per-thread that "happens
1012 * before" curr. Don't consider reflexively.
1014 if (act->happens_before(curr) && act != curr) {
1015 if (act->is_write()) {
1017 mo_graph->addEdge(act, rf);
1021 const ModelAction *prevreadfrom = act->get_reads_from();
1022 //if the previous read is unresolved, keep going...
1023 if (prevreadfrom == NULL)
1026 if (rf != prevreadfrom) {
1027 mo_graph->addEdge(prevreadfrom, rf);
1039 /** This method fixes up the modification order when we resolve a
1040 * promises. The basic problem is that actions that occur after the
1041 * read curr could not property add items to the modification order
1044 * So for each thread, we find the earliest item that happens after
1045 * the read curr. This is the item we have to fix up with additional
1046 * constraints. If that action is write, we add a MO edge between
1047 * the Action rf and that action. If the action is a read, we add a
1048 * MO edge between the Action rf, and whatever the read accessed.
1050 * @param curr is the read ModelAction that we are fixing up MO edges for.
1051 * @param rf is the write ModelAction that curr reads from.
1054 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1056 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1058 ASSERT(curr->is_read());
1060 /* Iterate over all threads */
1061 for (i = 0; i < thrd_lists->size(); i++) {
1062 /* Iterate over actions in thread, starting from most recent */
1063 action_list_t *list = &(*thrd_lists)[i];
1064 action_list_t::reverse_iterator rit;
1065 ModelAction *lastact = NULL;
1067 /* Find last action that happens after curr that is either not curr or a rmw */
1068 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1069 ModelAction *act = *rit;
1070 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1076 /* Include at most one act per-thread that "happens before" curr */
1077 if (lastact != NULL) {
1078 if (lastact==curr) {
1079 //Case 1: The resolved read is a RMW, and we need to make sure
1080 //that the write portion of the RMW mod order after rf
1082 mo_graph->addEdge(rf, lastact);
1083 } else if (lastact->is_read()) {
1084 //Case 2: The resolved read is a normal read and the next
1085 //operation is a read, and we need to make sure the value read
1086 //is mod ordered after rf
1088 const ModelAction *postreadfrom = lastact->get_reads_from();
1089 if (postreadfrom != NULL&&rf != postreadfrom)
1090 mo_graph->addEdge(rf, postreadfrom);
1092 //Case 3: The resolved read is a normal read and the next
1093 //operation is a write, and we need to make sure that the
1094 //write is mod ordered after rf
1096 mo_graph->addEdge(rf, lastact);
1104 * Updates the mo_graph with the constraints imposed from the current write.
1106 * Basic idea is the following: Go through each other thread and find
1107 * the lastest action that happened before our write. Two cases:
1109 * (1) The action is a write => that write must occur before
1112 * (2) The action is a read => the write that that action read from
1113 * must occur before the current write.
1115 * This method also handles two other issues:
1117 * (I) Sequential Consistency: Making sure that if the current write is
1118 * seq_cst, that it occurs after the previous seq_cst write.
1120 * (II) Sending the write back to non-synchronizing reads.
1122 * @param curr The current action. Must be a write.
1123 * @return True if modification order edges were added; false otherwise
1125 bool ModelChecker::w_modification_order(ModelAction *curr)
1127 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1130 ASSERT(curr->is_write());
1132 if (curr->is_seqcst()) {
1133 /* We have to at least see the last sequentially consistent write,
1134 so we are initialized. */
1135 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1136 if (last_seq_cst != NULL) {
1137 mo_graph->addEdge(last_seq_cst, curr);
1142 /* Iterate over all threads */
1143 for (i = 0; i < thrd_lists->size(); i++) {
1144 /* Iterate over actions in thread, starting from most recent */
1145 action_list_t *list = &(*thrd_lists)[i];
1146 action_list_t::reverse_iterator rit;
1147 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1148 ModelAction *act = *rit;
1151 * 1) If RMW and it actually read from something, then we
1152 * already have all relevant edges, so just skip to next
1155 * 2) If RMW and it didn't read from anything, we should
1156 * whatever edge we can get to speed up convergence.
1158 * 3) If normal write, we need to look at earlier actions, so
1159 * continue processing list.
1161 if (curr->is_rmw()) {
1162 if (curr->get_reads_from()!=NULL)
1171 * Include at most one act per-thread that "happens
1174 if (act->happens_before(curr)) {
1176 * Note: if act is RMW, just add edge:
1178 * The following edge should be handled elsewhere:
1179 * readfrom(act) --mo--> act
1181 if (act->is_write())
1182 mo_graph->addEdge(act, curr);
1183 else if (act->is_read()) {
1184 //if previous read accessed a null, just keep going
1185 if (act->get_reads_from() == NULL)
1187 mo_graph->addEdge(act->get_reads_from(), curr);
1191 } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1192 !act->same_thread(curr)) {
1193 /* We have an action that:
1194 (1) did not happen before us
1195 (2) is a read and we are a write
1196 (3) cannot synchronize with us
1197 (4) is in a different thread
1199 that read could potentially read from our write.
1201 if (thin_air_constraint_may_allow(curr, act)) {
1203 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1204 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1205 futurevalues->push_back(pfv);
1215 /** Arbitrary reads from the future are not allowed. Section 29.3
1216 * part 9 places some constraints. This method checks one result of constraint
1217 * constraint. Others require compiler support. */
1218 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1219 if (!writer->is_rmw())
1222 if (!reader->is_rmw())
1225 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1226 if (search == reader)
1228 if (search->get_tid() == reader->get_tid() &&
1229 search->happens_before(reader))
1237 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1238 * The ModelAction under consideration is expected to be taking part in
1239 * release/acquire synchronization as an object of the "reads from" relation.
1240 * Note that this can only provide release sequence support for RMW chains
1241 * which do not read from the future, as those actions cannot be traced until
1242 * their "promise" is fulfilled. Similarly, we may not even establish the
1243 * presence of a release sequence with certainty, as some modification order
1244 * constraints may be decided further in the future. Thus, this function
1245 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1246 * and a boolean representing certainty.
1248 * @todo Finish lazy updating, when promises are fulfilled in the future
1249 * @param rf The action that might be part of a release sequence. Must be a
1251 * @param release_heads A pass-by-reference style return parameter. After
1252 * execution of this function, release_heads will contain the heads of all the
1253 * relevant release sequences, if any exists with certainty
1254 * @param pending A pass-by-reference style return parameter which is only used
1255 * when returning false (i.e., uncertain). Returns most information regarding
1256 * an uncertain release sequence, including any write operations that might
1257 * break the sequence.
1258 * @return true, if the ModelChecker is certain that release_heads is complete;
1261 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1262 rel_heads_list_t *release_heads,
1263 struct release_seq *pending) const
1265 /* Only check for release sequences if there are no cycles */
1266 if (mo_graph->checkForCycles())
1270 ASSERT(rf->is_write());
1272 if (rf->is_release())
1273 release_heads->push_back(rf);
1275 break; /* End of RMW chain */
1277 /** @todo Need to be smarter here... In the linux lock
1278 * example, this will run to the beginning of the program for
1280 /** @todo The way to be smarter here is to keep going until 1
1281 * thread has a release preceded by an acquire and you've seen
1284 /* acq_rel RMW is a sufficient stopping condition */
1285 if (rf->is_acquire() && rf->is_release())
1286 return true; /* complete */
1288 rf = rf->get_reads_from();
1291 /* read from future: need to settle this later */
1293 return false; /* incomplete */
1296 if (rf->is_release())
1297 return true; /* complete */
1299 /* else relaxed write; check modification order for contiguous subsequence
1300 * -> rf must be same thread as release */
1301 int tid = id_to_int(rf->get_tid());
1302 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1303 action_list_t *list = &(*thrd_lists)[tid];
1304 action_list_t::const_reverse_iterator rit;
1306 /* Find rf in the thread list */
1307 rit = std::find(list->rbegin(), list->rend(), rf);
1308 ASSERT(rit != list->rend());
1310 /* Find the last write/release */
1311 for (; rit != list->rend(); rit++)
1312 if ((*rit)->is_release())
1314 if (rit == list->rend()) {
1315 /* No write-release in this thread */
1316 return true; /* complete */
1318 ModelAction *release = *rit;
1320 ASSERT(rf->same_thread(release));
1322 pending->writes.clear();
1324 bool certain = true;
1325 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1326 if (id_to_int(rf->get_tid()) == (int)i)
1328 list = &(*thrd_lists)[i];
1330 /* Can we ensure no future writes from this thread may break
1331 * the release seq? */
1332 bool future_ordered = false;
1334 ModelAction *last = get_last_action(int_to_id(i));
1335 Thread *th = get_thread(int_to_id(i));
1336 if ((last && rf->happens_before(last)) ||
1337 !scheduler->is_enabled(th) ||
1339 future_ordered = true;
1341 ASSERT(!th->is_model_thread() || future_ordered);
1343 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1344 const ModelAction *act = *rit;
1345 /* Reach synchronization -> this thread is complete */
1346 if (act->happens_before(release))
1348 if (rf->happens_before(act)) {
1349 future_ordered = true;
1353 /* Only writes can break release sequences */
1354 if (!act->is_write())
1357 /* Check modification order */
1358 if (mo_graph->checkReachable(rf, act)) {
1359 /* rf --mo--> act */
1360 future_ordered = true;
1363 if (mo_graph->checkReachable(act, release))
1364 /* act --mo--> release */
1366 if (mo_graph->checkReachable(release, act) &&
1367 mo_graph->checkReachable(act, rf)) {
1368 /* release --mo-> act --mo--> rf */
1369 return true; /* complete */
1371 /* act may break release sequence */
1372 pending->writes.push_back(act);
1375 if (!future_ordered)
1376 certain = false; /* This thread is uncertain */
1380 release_heads->push_back(release);
1381 pending->writes.clear();
1383 pending->release = release;
1390 * A public interface for getting the release sequence head(s) with which a
1391 * given ModelAction must synchronize. This function only returns a non-empty
1392 * result when it can locate a release sequence head with certainty. Otherwise,
1393 * it may mark the internal state of the ModelChecker so that it will handle
1394 * the release sequence at a later time, causing @a act to update its
1395 * synchronization at some later point in execution.
1396 * @param act The 'acquire' action that may read from a release sequence
1397 * @param release_heads A pass-by-reference return parameter. Will be filled
1398 * with the head(s) of the release sequence(s), if they exists with certainty.
1399 * @see ModelChecker::release_seq_heads
1401 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1403 const ModelAction *rf = act->get_reads_from();
1404 struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1405 sequence->acquire = act;
1407 if (!release_seq_heads(rf, release_heads, sequence)) {
1408 /* add act to 'lazy checking' list */
1409 pending_rel_seqs->push_back(sequence);
1411 snapshot_free(sequence);
1416 * Attempt to resolve all stashed operations that might synchronize with a
1417 * release sequence for a given location. This implements the "lazy" portion of
1418 * determining whether or not a release sequence was contiguous, since not all
1419 * modification order information is present at the time an action occurs.
1421 * @param location The location/object that should be checked for release
1422 * sequence resolutions. A NULL value means to check all locations.
1423 * @param work_queue The work queue to which to add work items as they are
1425 * @return True if any updates occurred (new synchronization, new mo_graph
1428 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1430 bool updated = false;
1431 std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1432 while (it != pending_rel_seqs->end()) {
1433 struct release_seq *pending = *it;
1434 ModelAction *act = pending->acquire;
1436 /* Only resolve sequences on the given location, if provided */
1437 if (location && act->get_location() != location) {
1442 const ModelAction *rf = act->get_reads_from();
1443 rel_heads_list_t release_heads;
1445 complete = release_seq_heads(rf, &release_heads, pending);
1446 for (unsigned int i = 0; i < release_heads.size(); i++) {
1447 if (!act->has_synchronized_with(release_heads[i])) {
1448 if (act->synchronize_with(release_heads[i]))
1451 set_bad_synchronization();
1456 /* Re-check all pending release sequences */
1457 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1458 /* Re-check act for mo_graph edges */
1459 work_queue->push_back(MOEdgeWorkEntry(act));
1461 /* propagate synchronization to later actions */
1462 action_list_t::reverse_iterator rit = action_trace->rbegin();
1463 for (; (*rit) != act; rit++) {
1464 ModelAction *propagate = *rit;
1465 if (act->happens_before(propagate)) {
1466 propagate->synchronize_with(act);
1467 /* Re-check 'propagate' for mo_graph edges */
1468 work_queue->push_back(MOEdgeWorkEntry(propagate));
1473 it = pending_rel_seqs->erase(it);
1474 snapshot_free(pending);
1480 // If we resolved promises or data races, see if we have realized a data race.
1481 if (checkDataRaces()) {
1489 * Performs various bookkeeping operations for the current ModelAction. For
1490 * instance, adds action to the per-object, per-thread action vector and to the
1491 * action trace list of all thread actions.
1493 * @param act is the ModelAction to add.
1495 void ModelChecker::add_action_to_lists(ModelAction *act)
1497 int tid = id_to_int(act->get_tid());
1498 action_trace->push_back(act);
1500 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1502 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1503 if (tid >= (int)vec->size())
1504 vec->resize(priv->next_thread_id);
1505 (*vec)[tid].push_back(act);
1507 if ((int)thrd_last_action->size() <= tid)
1508 thrd_last_action->resize(get_num_threads());
1509 (*thrd_last_action)[tid] = act;
1513 * @brief Get the last action performed by a particular Thread
1514 * @param tid The thread ID of the Thread in question
1515 * @return The last action in the thread
1517 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1519 int threadid = id_to_int(tid);
1520 if (threadid < (int)thrd_last_action->size())
1521 return (*thrd_last_action)[id_to_int(tid)];
1527 * Gets the last memory_order_seq_cst write (in the total global sequence)
1528 * performed on a particular object (i.e., memory location), not including the
1530 * @param curr The current ModelAction; also denotes the object location to
1532 * @return The last seq_cst write
1534 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1536 void *location = curr->get_location();
1537 action_list_t *list = obj_map->get_safe_ptr(location);
1538 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1539 action_list_t::reverse_iterator rit;
1540 for (rit = list->rbegin(); rit != list->rend(); rit++)
1541 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1547 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1548 * location). This function identifies the mutex according to the current
1549 * action, which is presumed to perform on the same mutex.
1550 * @param curr The current ModelAction; also denotes the object location to
1552 * @return The last unlock operation
1554 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1556 void *location = curr->get_location();
1557 action_list_t *list = obj_map->get_safe_ptr(location);
1558 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1559 action_list_t::reverse_iterator rit;
1560 for (rit = list->rbegin(); rit != list->rend(); rit++)
1561 if ((*rit)->is_unlock())
1566 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1568 ModelAction *parent = get_last_action(tid);
1570 parent = get_thread(tid)->get_creation();
1575 * Returns the clock vector for a given thread.
1576 * @param tid The thread whose clock vector we want
1577 * @return Desired clock vector
1579 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1581 return get_parent_action(tid)->get_cv();
1585 * Resolve a set of Promises with a current write. The set is provided in the
1586 * Node corresponding to @a write.
1587 * @param write The ModelAction that is fulfilling Promises
1588 * @return True if promises were resolved; false otherwise
1590 bool ModelChecker::resolve_promises(ModelAction *write)
1592 bool resolved = false;
1593 std::vector<thread_id_t> threads_to_check;
1595 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1596 Promise *promise = (*promises)[promise_index];
1597 if (write->get_node()->get_promise(i)) {
1598 ModelAction *read = promise->get_action();
1599 if (read->is_rmw()) {
1600 mo_graph->addRMWEdge(write, read);
1602 read->read_from(write);
1603 //First fix up the modification order for actions that happened
1605 r_modification_order(read, write);
1606 //Next fix up the modification order for actions that happened
1608 post_r_modification_order(read, write);
1609 //Make sure the promise's value matches the write's value
1610 ASSERT(promise->get_value() == write->get_value());
1613 promises->erase(promises->begin() + promise_index);
1614 threads_to_check.push_back(read->get_tid());
1621 //Check whether reading these writes has made threads unable to
1624 for(unsigned int i=0;i<threads_to_check.size();i++)
1625 mo_check_promises(threads_to_check[i], write);
1631 * Compute the set of promises that could potentially be satisfied by this
1632 * action. Note that the set computation actually appears in the Node, not in
1634 * @param curr The ModelAction that may satisfy promises
1636 void ModelChecker::compute_promises(ModelAction *curr)
1638 for (unsigned int i = 0; i < promises->size(); i++) {
1639 Promise *promise = (*promises)[i];
1640 const ModelAction *act = promise->get_action();
1641 if (!act->happens_before(curr) &&
1643 !act->could_synchronize_with(curr) &&
1644 !act->same_thread(curr) &&
1645 promise->get_value() == curr->get_value()) {
1646 curr->get_node()->set_promise(i);
1651 /** Checks promises in response to change in ClockVector Threads. */
1652 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1654 for (unsigned int i = 0; i < promises->size(); i++) {
1655 Promise *promise = (*promises)[i];
1656 const ModelAction *act = promise->get_action();
1657 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1658 merge_cv->synchronized_since(act)) {
1659 if (promise->increment_threads(tid)) {
1660 //Promise has failed
1661 failed_promise = true;
1668 /** Checks promises in response to addition to modification order for threads.
1670 * pthread is the thread that performed the read that created the promise
1672 * pread is the read that created the promise
1674 * pwrite is either the first write to same location as pread by
1675 * pthread that is sequenced after pread or the value read by the
1676 * first read to the same lcoation as pread by pthread that is
1677 * sequenced after pread..
1679 * 1. If tid=pthread, then we check what other threads are reachable
1680 * through the mode order starting with pwrite. Those threads cannot
1681 * perform a write that will resolve the promise due to modification
1682 * order constraints.
1684 * 2. If the tid is not pthread, we check whether pwrite can reach the
1685 * action write through the modification order. If so, that thread
1686 * cannot perform a future write that will resolve the promise due to
1687 * modificatin order constraints.
1689 * @parem tid The thread that either read from the model action
1690 * write, or actually did the model action write.
1692 * @parem write The ModelAction representing the relevant write.
1695 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1696 void * location = write->get_location();
1697 for (unsigned int i = 0; i < promises->size(); i++) {
1698 Promise *promise = (*promises)[i];
1699 const ModelAction *act = promise->get_action();
1701 //Is this promise on the same location?
1702 if ( act->get_location() != location )
1705 //same thread as the promise
1706 if ( act->get_tid()==tid ) {
1708 //do we have a pwrite for the promise, if not, set it
1709 if (promise->get_write() == NULL ) {
1710 promise->set_write(write);
1712 if (mo_graph->checkPromise(write, promise)) {
1713 failed_promise = true;
1718 //Don't do any lookups twice for the same thread
1719 if (promise->has_sync_thread(tid))
1722 if (mo_graph->checkReachable(promise->get_write(), write)) {
1723 if (promise->increment_threads(tid)) {
1724 failed_promise = true;
1732 * Compute the set of writes that may break the current pending release
1733 * sequence. This information is extracted from previou release sequence
1736 * @param curr The current ModelAction. Must be a release sequence fixup
1739 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1741 if (pending_rel_seqs->empty())
1744 struct release_seq *pending = pending_rel_seqs->back();
1745 for (unsigned int i = 0; i < pending->writes.size(); i++) {
1746 const ModelAction *write = pending->writes[i];
1747 curr->get_node()->add_relseq_break(write);
1750 /* NULL means don't break the sequence; just synchronize */
1751 curr->get_node()->add_relseq_break(NULL);
1755 * Build up an initial set of all past writes that this 'read' action may read
1756 * from. This set is determined by the clock vector's "happens before"
1758 * @param curr is the current ModelAction that we are exploring; it must be a
1761 void ModelChecker::build_reads_from_past(ModelAction *curr)
1763 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1765 ASSERT(curr->is_read());
1767 ModelAction *last_seq_cst = NULL;
1769 /* Track whether this object has been initialized */
1770 bool initialized = false;
1772 if (curr->is_seqcst()) {
1773 last_seq_cst = get_last_seq_cst(curr);
1774 /* We have to at least see the last sequentially consistent write,
1775 so we are initialized. */
1776 if (last_seq_cst != NULL)
1780 /* Iterate over all threads */
1781 for (i = 0; i < thrd_lists->size(); i++) {
1782 /* Iterate over actions in thread, starting from most recent */
1783 action_list_t *list = &(*thrd_lists)[i];
1784 action_list_t::reverse_iterator rit;
1785 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1786 ModelAction *act = *rit;
1788 /* Only consider 'write' actions */
1789 if (!act->is_write() || act == curr)
1792 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1793 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1794 DEBUG("Adding action to may_read_from:\n");
1795 if (DBG_ENABLED()) {
1799 curr->get_node()->add_read_from(act);
1802 /* Include at most one act per-thread that "happens before" curr */
1803 if (act->happens_before(curr)) {
1811 /** @todo Need a more informative way of reporting errors. */
1812 printf("ERROR: may read from uninitialized atomic\n");
1815 if (DBG_ENABLED() || !initialized) {
1816 printf("Reached read action:\n");
1818 printf("Printing may_read_from\n");
1819 curr->get_node()->print_may_read_from();
1820 printf("End printing may_read_from\n");
1823 ASSERT(initialized);
1826 static void print_list(action_list_t *list)
1828 action_list_t::iterator it;
1830 printf("---------------------------------------------------------------------\n");
1833 for (it = list->begin(); it != list->end(); it++) {
1836 printf("---------------------------------------------------------------------\n");
1839 #if SUPPORT_MOD_ORDER_DUMP
1840 void ModelChecker::dumpGraph(char *filename) {
1842 sprintf(buffer, "%s.dot",filename);
1843 FILE *file=fopen(buffer, "w");
1844 fprintf(file, "digraph %s {\n",filename);
1845 mo_graph->dumpNodes(file);
1846 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1848 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1849 ModelAction *action=*it;
1850 if (action->is_read()) {
1851 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1852 if (action->get_reads_from()!=NULL)
1853 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1855 if (thread_array[action->get_tid()] != NULL) {
1856 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1859 thread_array[action->get_tid()]=action;
1861 fprintf(file,"}\n");
1862 model_free(thread_array);
1867 void ModelChecker::print_summary()
1870 printf("Number of executions: %d\n", num_executions);
1871 printf("Number of feasible executions: %d\n", num_feasible_executions);
1872 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1874 #if SUPPORT_MOD_ORDER_DUMP
1876 char buffername[100];
1877 sprintf(buffername, "exec%04u", num_executions);
1878 mo_graph->dumpGraphToFile(buffername);
1879 sprintf(buffername, "graph%04u", num_executions);
1880 dumpGraph(buffername);
1883 if (!isfinalfeasible())
1884 printf("INFEASIBLE EXECUTION!\n");
1885 print_list(action_trace);
1890 * Add a Thread to the system for the first time. Should only be called once
1892 * @param t The Thread to add
1894 void ModelChecker::add_thread(Thread *t)
1896 thread_map->put(id_to_int(t->get_id()), t);
1897 scheduler->add_thread(t);
1901 * Removes a thread from the scheduler.
1902 * @param the thread to remove.
1904 void ModelChecker::remove_thread(Thread *t)
1906 scheduler->remove_thread(t);
1910 * @brief Get a Thread reference by its ID
1911 * @param tid The Thread's ID
1912 * @return A Thread reference
1914 Thread * ModelChecker::get_thread(thread_id_t tid) const
1916 return thread_map->get(id_to_int(tid));
1920 * @brief Get a reference to the Thread in which a ModelAction was executed
1921 * @param act The ModelAction
1922 * @return A Thread reference
1924 Thread * ModelChecker::get_thread(ModelAction *act) const
1926 return get_thread(act->get_tid());
1930 * Switch from a user-context to the "master thread" context (a.k.a. system
1931 * context). This switch is made with the intention of exploring a particular
1932 * model-checking action (described by a ModelAction object). Must be called
1933 * from a user-thread context.
1935 * @param act The current action that will be explored. May be NULL only if
1936 * trace is exiting via an assertion (see ModelChecker::set_assert and
1937 * ModelChecker::has_asserted).
1938 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1940 int ModelChecker::switch_to_master(ModelAction *act)
1943 Thread *old = thread_current();
1944 set_current_action(act);
1945 old->set_state(THREAD_READY);
1946 return Thread::swap(old, &system_context);
1950 * Takes the next step in the execution, if possible.
1951 * @return Returns true (success) if a step was taken and false otherwise.
1953 bool ModelChecker::take_step() {
1957 Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1959 if (curr->get_state() == THREAD_READY) {
1960 ASSERT(priv->current_action);
1962 priv->nextThread = check_current_action(priv->current_action);
1963 priv->current_action = NULL;
1965 if (curr->is_blocked() || curr->is_complete())
1966 scheduler->remove_thread(curr);
1971 Thread *next = scheduler->next_thread(priv->nextThread);
1973 /* Infeasible -> don't take any more steps */
1977 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1978 next ? id_to_int(next->get_id()) : -1);
1981 * Launch end-of-execution release sequence fixups only when there are:
1983 * (1) no more user threads to run (or when execution replay chooses
1984 * the 'model_thread')
1985 * (2) pending release sequences
1986 * (3) pending assertions (i.e., data races)
1988 if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
1989 !unrealizedraces.empty()) {
1990 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
1991 pending_rel_seqs->size());
1992 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
1993 std::memory_order_seq_cst, NULL, VALUE_NONE,
1995 set_current_action(fixup);
1999 /* next == NULL -> don't take any more steps */
2003 next->set_state(THREAD_RUNNING);
2005 if (next->get_pending() != NULL) {
2006 /* restart a pending action */
2007 set_current_action(next->get_pending());
2008 next->set_pending(NULL);
2009 next->set_state(THREAD_READY);
2013 /* Return false only if swap fails with an error */
2014 return (Thread::swap(&system_context, next) == 0);
2017 /** Runs the current execution until threre are no more steps to take. */
2018 void ModelChecker::finish_execution() {
2021 while (take_step());