8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
16 #define INITIAL_THREAD_ID 0
20 /** @brief Constructor */
21 ModelChecker::ModelChecker(struct model_params params) :
22 /* Initialize default scheduler */
24 scheduler(new Scheduler()),
26 num_feasible_executions(0),
28 action_trace(new action_list_t()),
29 thread_map(new HashTable<int, Thread *, int>()),
30 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
31 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
33 promises(new std::vector<Promise *>()),
34 futurevalues(new std::vector<struct PendingFutureValue>()),
35 pending_acq_rel_seq(new std::vector<ModelAction *>()),
36 thrd_last_action(new std::vector<ModelAction *>(1)),
37 node_stack(new NodeStack()),
38 mo_graph(new CycleGraph()),
39 failed_promise(false),
40 too_many_reads(false),
43 /* Allocate this "size" on the snapshotting heap */
44 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
45 /* First thread created will have id INITIAL_THREAD_ID */
46 priv->next_thread_id = INITIAL_THREAD_ID;
49 /** @brief Destructor */
50 ModelChecker::~ModelChecker()
52 for (int i = 0; i < get_num_threads(); i++)
53 delete thread_map->get(i);
58 delete lock_waiters_map;
61 for (unsigned int i = 0; i < promises->size(); i++)
62 delete (*promises)[i];
65 delete pending_acq_rel_seq;
67 delete thrd_last_action;
74 * Restores user program to initial state and resets all model-checker data
77 void ModelChecker::reset_to_initial_state()
79 DEBUG("+++ Resetting to initial state +++\n");
80 node_stack->reset_execution();
81 failed_promise = false;
82 too_many_reads = false;
84 snapshotObject->backTrackBeforeStep(0);
87 /** @return a thread ID for a new Thread */
88 thread_id_t ModelChecker::get_next_id()
90 return priv->next_thread_id++;
93 /** @return the number of user threads created during this execution */
94 int ModelChecker::get_num_threads()
96 return priv->next_thread_id;
99 /** @return a sequence number for a new ModelAction */
100 modelclock_t ModelChecker::get_next_seq_num()
102 return ++priv->used_sequence_numbers;
106 * @brief Choose the next thread to execute.
108 * This function chooses the next thread that should execute. It can force the
109 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
110 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
111 * The model-checker may have no preference regarding the next thread (i.e.,
112 * when exploring a new execution ordering), in which case this will return
114 * @param curr The current ModelAction. This action might guide the choice of
116 * @return The next thread to run. If the model-checker has no preference, NULL.
118 Thread * ModelChecker::get_next_thread(ModelAction *curr)
123 /* Do not split atomic actions. */
125 return thread_current();
126 /* The THREAD_CREATE action points to the created Thread */
127 else if (curr->get_type() == THREAD_CREATE)
128 return (Thread *)curr->get_location();
131 /* Have we completed exploring the preselected path? */
135 /* Else, we are trying to replay an execution */
136 ModelAction *next = node_stack->get_next()->get_action();
138 if (next == diverge) {
139 Node *nextnode = next->get_node();
140 /* Reached divergence point */
141 if (nextnode->increment_promise()) {
142 /* The next node will try to satisfy a different set of promises. */
143 tid = next->get_tid();
144 node_stack->pop_restofstack(2);
145 } else if (nextnode->increment_read_from()) {
146 /* The next node will read from a different value. */
147 tid = next->get_tid();
148 node_stack->pop_restofstack(2);
149 } else if (nextnode->increment_future_value()) {
150 /* The next node will try to read from a different future value. */
151 tid = next->get_tid();
152 node_stack->pop_restofstack(2);
154 /* Make a different thread execute for next step */
155 Node *node = nextnode->get_parent();
156 tid = node->get_next_backtrack();
157 node_stack->pop_restofstack(1);
159 DEBUG("*** Divergence point ***\n");
162 tid = next->get_tid();
164 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
165 ASSERT(tid != THREAD_ID_T_NONE);
166 return thread_map->get(id_to_int(tid));
170 * Queries the model-checker for more executions to explore and, if one
171 * exists, resets the model-checker state to execute a new execution.
173 * @return If there are more executions to explore, return true. Otherwise,
176 bool ModelChecker::next_execution()
181 if (isfinalfeasible())
182 num_feasible_executions++;
184 if (isfinalfeasible() || DBG_ENABLED())
187 if ((diverge = get_next_backtrack()) == NULL)
191 printf("Next execution will diverge at:\n");
195 reset_to_initial_state();
199 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
201 switch (act->get_type()) {
205 /* linear search: from most recent to oldest */
206 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
207 action_list_t::reverse_iterator rit;
208 for (rit = list->rbegin(); rit != list->rend(); rit++) {
209 ModelAction *prev = *rit;
210 if (act->is_synchronizing(prev))
216 case ATOMIC_TRYLOCK: {
217 /* linear search: from most recent to oldest */
218 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
219 action_list_t::reverse_iterator rit;
220 for (rit = list->rbegin(); rit != list->rend(); rit++) {
221 ModelAction *prev = *rit;
222 if (act->is_conflicting_lock(prev))
227 case ATOMIC_UNLOCK: {
228 /* linear search: from most recent to oldest */
229 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
230 action_list_t::reverse_iterator rit;
231 for (rit = list->rbegin(); rit != list->rend(); rit++) {
232 ModelAction *prev = *rit;
233 if (!act->same_thread(prev)&&prev->is_failed_trylock())
244 /** This method find backtracking points where we should try to
245 * reorder the parameter ModelAction against.
247 * @param the ModelAction to find backtracking points for.
249 void ModelChecker::set_backtracking(ModelAction *act)
251 Thread *t = get_thread(act);
252 ModelAction * prev = get_last_conflict(act);
256 Node * node = prev->get_node()->get_parent();
258 int low_tid, high_tid;
259 if (node->is_enabled(t)) {
260 low_tid = id_to_int(act->get_tid());
261 high_tid = low_tid+1;
264 high_tid = get_num_threads();
267 for(int i = low_tid; i < high_tid; i++) {
268 thread_id_t tid = int_to_id(i);
269 if (!node->is_enabled(tid))
272 /* Check if this has been explored already */
273 if (node->has_been_explored(tid))
276 /* See if fairness allows */
277 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
279 for(int t=0;t<node->get_num_threads();t++) {
280 thread_id_t tother=int_to_id(t);
281 if (node->is_enabled(tother) && node->has_priority(tother)) {
290 /* Cache the latest backtracking point */
291 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
292 priv->next_backtrack = prev;
294 /* If this is a new backtracking point, mark the tree */
295 if (!node->set_backtrack(tid))
297 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
298 prev->get_tid(), t->get_id());
307 * Returns last backtracking point. The model checker will explore a different
308 * path for this point in the next execution.
309 * @return The ModelAction at which the next execution should diverge.
311 ModelAction * ModelChecker::get_next_backtrack()
313 ModelAction *next = priv->next_backtrack;
314 priv->next_backtrack = NULL;
319 * Processes a read or rmw model action.
320 * @param curr is the read model action to process.
321 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
322 * @return True if processing this read updates the mo_graph.
324 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
327 bool updated = false;
329 const ModelAction *reads_from = curr->get_node()->get_read_from();
330 if (reads_from != NULL) {
331 mo_graph->startChanges();
333 value = reads_from->get_value();
334 bool r_status = false;
336 if (!second_part_of_rmw) {
337 check_recency(curr, reads_from);
338 r_status = r_modification_order(curr, reads_from);
342 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
343 mo_graph->rollbackChanges();
344 too_many_reads = false;
348 curr->read_from(reads_from);
349 mo_graph->commitChanges();
351 } else if (!second_part_of_rmw) {
352 /* Read from future value */
353 value = curr->get_node()->get_future_value();
354 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
355 curr->read_from(NULL);
356 Promise *valuepromise = new Promise(curr, value, expiration);
357 promises->push_back(valuepromise);
359 get_thread(curr)->set_return_value(value);
365 * Processes a lock, trylock, or unlock model action. @param curr is
366 * the read model action to process.
368 * The try lock operation checks whether the lock is taken. If not,
369 * it falls to the normal lock operation case. If so, it returns
372 * The lock operation has already been checked that it is enabled, so
373 * it just grabs the lock and synchronizes with the previous unlock.
375 * The unlock operation has to re-enable all of the threads that are
376 * waiting on the lock.
378 * @return True if synchronization was updated; false otherwise
380 bool ModelChecker::process_mutex(ModelAction *curr) {
381 std::mutex *mutex = (std::mutex *)curr->get_location();
382 struct std::mutex_state *state = mutex->get_state();
383 switch (curr->get_type()) {
384 case ATOMIC_TRYLOCK: {
385 bool success = !state->islocked;
386 curr->set_try_lock(success);
388 get_thread(curr)->set_return_value(0);
391 get_thread(curr)->set_return_value(1);
393 //otherwise fall into the lock case
395 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
396 printf("Lock access before initialization\n");
399 state->islocked = true;
400 ModelAction *unlock = get_last_unlock(curr);
401 //synchronize with the previous unlock statement
402 if (unlock != NULL) {
403 curr->synchronize_with(unlock);
408 case ATOMIC_UNLOCK: {
410 state->islocked = false;
411 //wake up the other threads
412 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
413 //activate all the waiting threads
414 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
415 scheduler->add_thread(get_thread((*rit)->get_tid()));
427 * Process a write ModelAction
428 * @param curr The ModelAction to process
429 * @return True if the mo_graph was updated or promises were resolved
431 bool ModelChecker::process_write(ModelAction *curr)
433 bool updated_mod_order = w_modification_order(curr);
434 bool updated_promises = resolve_promises(curr);
436 if (promises->size() == 0) {
437 for (unsigned int i = 0; i < futurevalues->size(); i++) {
438 struct PendingFutureValue pfv = (*futurevalues)[i];
439 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
440 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
441 priv->next_backtrack = pfv.act;
443 futurevalues->resize(0);
446 mo_graph->commitChanges();
447 get_thread(curr)->set_return_value(VALUE_NONE);
448 return updated_mod_order || updated_promises;
452 * @brief Process the current action for thread-related activity
454 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
455 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
456 * synchronization, etc. This function is a no-op for non-THREAD actions
457 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
459 * @param curr The current action
460 * @return True if synchronization was updated
462 bool ModelChecker::process_thread_action(ModelAction *curr)
464 bool synchronized = false;
466 switch (curr->get_type()) {
467 case THREAD_CREATE: {
468 Thread *th = (Thread *)curr->get_location();
469 th->set_creation(curr);
473 Thread *waiting, *blocking;
474 waiting = get_thread(curr);
475 blocking = (Thread *)curr->get_location();
476 if (!blocking->is_complete()) {
477 blocking->push_wait_list(curr);
478 scheduler->sleep(waiting);
480 do_complete_join(curr);
485 case THREAD_FINISH: {
486 Thread *th = get_thread(curr);
487 while (!th->wait_list_empty()) {
488 ModelAction *act = th->pop_wait_list();
489 Thread *wake = get_thread(act);
490 scheduler->wake(wake);
491 do_complete_join(act);
498 check_promises(NULL, curr->get_cv());
509 * Initialize the current action by performing one or more of the following
510 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
511 * in the NodeStack, manipulating backtracking sets, allocating and
512 * initializing clock vectors, and computing the promises to fulfill.
514 * @param curr The current action, as passed from the user context; may be
515 * freed/invalidated after the execution of this function
516 * @return The current action, as processed by the ModelChecker. Is only the
517 * same as the parameter @a curr if this is a newly-explored action.
519 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
521 ModelAction *newcurr;
523 if (curr->is_rmwc() || curr->is_rmw()) {
524 newcurr = process_rmw(curr);
526 compute_promises(newcurr);
530 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
532 /* First restore type and order in case of RMW operation */
534 newcurr->copy_typeandorder(curr);
536 ASSERT(curr->get_location() == newcurr->get_location());
537 newcurr->copy_from_new(curr);
539 /* Discard duplicate ModelAction; use action from NodeStack */
542 /* If we have diverged, we need to reset the clock vector. */
544 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
548 * Perform one-time actions when pushing new ModelAction onto
551 curr->create_cv(get_parent_action(curr->get_tid()));
552 if (curr->is_write())
553 compute_promises(curr);
559 * This method checks whether a model action is enabled at the given point.
560 * At this point, it checks whether a lock operation would be successful at this point.
561 * If not, it puts the thread in a waiter list.
562 * @param curr is the ModelAction to check whether it is enabled.
563 * @return a bool that indicates whether the action is enabled.
565 bool ModelChecker::check_action_enabled(ModelAction *curr) {
566 if (curr->is_lock()) {
567 std::mutex * lock = (std::mutex *)curr->get_location();
568 struct std::mutex_state * state = lock->get_state();
569 if (state->islocked) {
570 //Stick the action in the appropriate waiting queue
571 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
580 * This is the heart of the model checker routine. It performs model-checking
581 * actions corresponding to a given "current action." Among other processes, it
582 * calculates reads-from relationships, updates synchronization clock vectors,
583 * forms a memory_order constraints graph, and handles replay/backtrack
584 * execution when running permutations of previously-observed executions.
586 * @param curr The current action to process
587 * @return The next Thread that must be executed. May be NULL if ModelChecker
588 * makes no choice (e.g., according to replay execution, combining RMW actions,
591 Thread * ModelChecker::check_current_action(ModelAction *curr)
595 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
597 if (!check_action_enabled(curr)) {
598 /* Make the execution look like we chose to run this action
599 * much later, when a lock is actually available to release */
600 get_current_thread()->set_pending(curr);
601 remove_thread(get_current_thread());
602 return get_next_thread(NULL);
605 ModelAction *newcurr = initialize_curr_action(curr);
607 /* Add the action to lists before any other model-checking tasks */
608 if (!second_part_of_rmw)
609 add_action_to_lists(newcurr);
611 /* Build may_read_from set for newly-created actions */
612 if (curr == newcurr && curr->is_read())
613 build_reads_from_past(curr);
616 /* Initialize work_queue with the "current action" work */
617 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
619 while (!work_queue.empty()) {
620 WorkQueueEntry work = work_queue.front();
621 work_queue.pop_front();
624 case WORK_CHECK_CURR_ACTION: {
625 ModelAction *act = work.action;
626 bool update = false; /* update this location's release seq's */
627 bool update_all = false; /* update all release seq's */
629 if (process_thread_action(curr))
632 if (act->is_read() && process_read(act, second_part_of_rmw))
635 if (act->is_write() && process_write(act))
638 if (act->is_mutex_op() && process_mutex(act))
642 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
644 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
647 case WORK_CHECK_RELEASE_SEQ:
648 resolve_release_sequences(work.location, &work_queue);
650 case WORK_CHECK_MO_EDGES: {
651 /** @todo Complete verification of work_queue */
652 ModelAction *act = work.action;
653 bool updated = false;
655 if (act->is_read()) {
656 if (r_modification_order(act, act->get_reads_from()))
659 if (act->is_write()) {
660 if (w_modification_order(act))
663 mo_graph->commitChanges();
666 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
675 check_curr_backtracking(curr);
677 set_backtracking(curr);
679 return get_next_thread(curr);
683 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
684 * operation from the Thread it is joining with. Must be called after the
685 * completion of the Thread in question.
686 * @param join The THREAD_JOIN action
688 void ModelChecker::do_complete_join(ModelAction *join)
690 Thread *blocking = (Thread *)join->get_location();
691 ModelAction *act = get_last_action(blocking->get_id());
692 join->synchronize_with(act);
695 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
696 Node *currnode = curr->get_node();
697 Node *parnode = currnode->get_parent();
699 if ((!parnode->backtrack_empty() ||
700 !currnode->read_from_empty() ||
701 !currnode->future_value_empty() ||
702 !currnode->promise_empty())
703 && (!priv->next_backtrack ||
704 *curr > *priv->next_backtrack)) {
705 priv->next_backtrack = curr;
709 bool ModelChecker::promises_expired() {
710 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
711 Promise *promise = (*promises)[promise_index];
712 if (promise->get_expiration()<priv->used_sequence_numbers) {
719 /** @return whether the current partial trace must be a prefix of a
721 bool ModelChecker::isfeasibleprefix() {
722 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
725 /** @return whether the current partial trace is feasible. */
726 bool ModelChecker::isfeasible() {
727 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
728 DEBUG("Infeasible: RMW violation\n");
730 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
733 /** @return whether the current partial trace is feasible other than
734 * multiple RMW reading from the same store. */
735 bool ModelChecker::isfeasibleotherthanRMW() {
737 if (mo_graph->checkForCycles())
738 DEBUG("Infeasible: modification order cycles\n");
740 DEBUG("Infeasible: failed promise\n");
742 DEBUG("Infeasible: too many reads\n");
743 if (promises_expired())
744 DEBUG("Infeasible: promises expired\n");
746 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
749 /** Returns whether the current completed trace is feasible. */
750 bool ModelChecker::isfinalfeasible() {
751 if (DBG_ENABLED() && promises->size() != 0)
752 DEBUG("Infeasible: unrevolved promises\n");
754 return isfeasible() && promises->size() == 0;
757 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
758 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
759 int tid = id_to_int(act->get_tid());
760 ModelAction *lastread = get_last_action(tid);
761 lastread->process_rmw(act);
762 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
763 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
764 mo_graph->commitChanges();
770 * Checks whether a thread has read from the same write for too many times
771 * without seeing the effects of a later write.
774 * 1) there must a different write that we could read from that would satisfy the modification order,
775 * 2) we must have read from the same value in excess of maxreads times, and
776 * 3) that other write must have been in the reads_from set for maxreads times.
778 * If so, we decide that the execution is no longer feasible.
780 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
781 if (params.maxreads != 0) {
783 if (curr->get_node()->get_read_from_size() <= 1)
785 //Must make sure that execution is currently feasible... We could
786 //accidentally clear by rolling back
789 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
790 int tid = id_to_int(curr->get_tid());
793 if ((int)thrd_lists->size() <= tid)
795 action_list_t *list = &(*thrd_lists)[tid];
797 action_list_t::reverse_iterator rit = list->rbegin();
799 for (; (*rit) != curr; rit++)
801 /* go past curr now */
804 action_list_t::reverse_iterator ritcopy = rit;
805 //See if we have enough reads from the same value
807 for (; count < params.maxreads; rit++,count++) {
808 if (rit==list->rend())
810 ModelAction *act = *rit;
814 if (act->get_reads_from() != rf)
816 if (act->get_node()->get_read_from_size() <= 1)
819 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
821 const ModelAction * write = curr->get_node()->get_read_from_at(i);
823 //Need a different write
827 /* Test to see whether this is a feasible write to read from*/
828 mo_graph->startChanges();
829 r_modification_order(curr, write);
830 bool feasiblereadfrom = isfeasible();
831 mo_graph->rollbackChanges();
833 if (!feasiblereadfrom)
837 bool feasiblewrite = true;
838 //new we need to see if this write works for everyone
840 for (int loop = count; loop>0; loop--,rit++) {
841 ModelAction *act=*rit;
842 bool foundvalue = false;
843 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
844 if (act->get_node()->get_read_from_at(i)==write) {
850 feasiblewrite = false;
855 too_many_reads = true;
863 * Updates the mo_graph with the constraints imposed from the current
866 * Basic idea is the following: Go through each other thread and find
867 * the lastest action that happened before our read. Two cases:
869 * (1) The action is a write => that write must either occur before
870 * the write we read from or be the write we read from.
872 * (2) The action is a read => the write that that action read from
873 * must occur before the write we read from or be the same write.
875 * @param curr The current action. Must be a read.
876 * @param rf The action that curr reads from. Must be a write.
877 * @return True if modification order edges were added; false otherwise
879 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
881 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
884 ASSERT(curr->is_read());
886 /* Iterate over all threads */
887 for (i = 0; i < thrd_lists->size(); i++) {
888 /* Iterate over actions in thread, starting from most recent */
889 action_list_t *list = &(*thrd_lists)[i];
890 action_list_t::reverse_iterator rit;
891 for (rit = list->rbegin(); rit != list->rend(); rit++) {
892 ModelAction *act = *rit;
895 * Include at most one act per-thread that "happens
896 * before" curr. Don't consider reflexively.
898 if (act->happens_before(curr) && act != curr) {
899 if (act->is_write()) {
901 mo_graph->addEdge(act, rf);
905 const ModelAction *prevreadfrom = act->get_reads_from();
906 if (prevreadfrom != NULL && rf != prevreadfrom) {
907 mo_graph->addEdge(prevreadfrom, rf);
919 /** This method fixes up the modification order when we resolve a
920 * promises. The basic problem is that actions that occur after the
921 * read curr could not property add items to the modification order
924 * So for each thread, we find the earliest item that happens after
925 * the read curr. This is the item we have to fix up with additional
926 * constraints. If that action is write, we add a MO edge between
927 * the Action rf and that action. If the action is a read, we add a
928 * MO edge between the Action rf, and whatever the read accessed.
930 * @param curr is the read ModelAction that we are fixing up MO edges for.
931 * @param rf is the write ModelAction that curr reads from.
934 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
936 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
938 ASSERT(curr->is_read());
940 /* Iterate over all threads */
941 for (i = 0; i < thrd_lists->size(); i++) {
942 /* Iterate over actions in thread, starting from most recent */
943 action_list_t *list = &(*thrd_lists)[i];
944 action_list_t::reverse_iterator rit;
945 ModelAction *lastact = NULL;
947 /* Find last action that happens after curr */
948 for (rit = list->rbegin(); rit != list->rend(); rit++) {
949 ModelAction *act = *rit;
950 if (curr->happens_before(act)) {
956 /* Include at most one act per-thread that "happens before" curr */
957 if (lastact != NULL) {
958 if (lastact->is_read()) {
959 const ModelAction *postreadfrom = lastact->get_reads_from();
960 if (postreadfrom != NULL&&rf != postreadfrom)
961 mo_graph->addEdge(rf, postreadfrom);
962 } else if (rf != lastact) {
963 mo_graph->addEdge(rf, lastact);
971 * Updates the mo_graph with the constraints imposed from the current write.
973 * Basic idea is the following: Go through each other thread and find
974 * the lastest action that happened before our write. Two cases:
976 * (1) The action is a write => that write must occur before
979 * (2) The action is a read => the write that that action read from
980 * must occur before the current write.
982 * This method also handles two other issues:
984 * (I) Sequential Consistency: Making sure that if the current write is
985 * seq_cst, that it occurs after the previous seq_cst write.
987 * (II) Sending the write back to non-synchronizing reads.
989 * @param curr The current action. Must be a write.
990 * @return True if modification order edges were added; false otherwise
992 bool ModelChecker::w_modification_order(ModelAction *curr)
994 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
997 ASSERT(curr->is_write());
999 if (curr->is_seqcst()) {
1000 /* We have to at least see the last sequentially consistent write,
1001 so we are initialized. */
1002 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1003 if (last_seq_cst != NULL) {
1004 mo_graph->addEdge(last_seq_cst, curr);
1009 /* Iterate over all threads */
1010 for (i = 0; i < thrd_lists->size(); i++) {
1011 /* Iterate over actions in thread, starting from most recent */
1012 action_list_t *list = &(*thrd_lists)[i];
1013 action_list_t::reverse_iterator rit;
1014 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1015 ModelAction *act = *rit;
1018 * If RMW, we already have all relevant edges,
1019 * so just skip to next thread.
1020 * If normal write, we need to look at earlier
1021 * actions, so continue processing list.
1030 * Include at most one act per-thread that "happens
1033 if (act->happens_before(curr)) {
1035 * Note: if act is RMW, just add edge:
1037 * The following edge should be handled elsewhere:
1038 * readfrom(act) --mo--> act
1040 if (act->is_write())
1041 mo_graph->addEdge(act, curr);
1042 else if (act->is_read() && act->get_reads_from() != NULL)
1043 mo_graph->addEdge(act->get_reads_from(), curr);
1046 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1047 !act->same_thread(curr)) {
1048 /* We have an action that:
1049 (1) did not happen before us
1050 (2) is a read and we are a write
1051 (3) cannot synchronize with us
1052 (4) is in a different thread
1054 that read could potentially read from our write.
1056 if (thin_air_constraint_may_allow(curr, act)) {
1058 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1059 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1060 futurevalues->push_back(pfv);
1070 /** Arbitrary reads from the future are not allowed. Section 29.3
1071 * part 9 places some constraints. This method checks one result of constraint
1072 * constraint. Others require compiler support. */
1073 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1074 if (!writer->is_rmw())
1077 if (!reader->is_rmw())
1080 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1081 if (search == reader)
1083 if (search->get_tid() == reader->get_tid() &&
1084 search->happens_before(reader))
1092 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1093 * The ModelAction under consideration is expected to be taking part in
1094 * release/acquire synchronization as an object of the "reads from" relation.
1095 * Note that this can only provide release sequence support for RMW chains
1096 * which do not read from the future, as those actions cannot be traced until
1097 * their "promise" is fulfilled. Similarly, we may not even establish the
1098 * presence of a release sequence with certainty, as some modification order
1099 * constraints may be decided further in the future. Thus, this function
1100 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1101 * and a boolean representing certainty.
1103 * @todo Finish lazy updating, when promises are fulfilled in the future
1104 * @param rf The action that might be part of a release sequence. Must be a
1106 * @param release_heads A pass-by-reference style return parameter. After
1107 * execution of this function, release_heads will contain the heads of all the
1108 * relevant release sequences, if any exists
1109 * @return true, if the ModelChecker is certain that release_heads is complete;
1112 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1114 /* Only check for release sequences if there are no cycles */
1115 if (mo_graph->checkForCycles())
1119 ASSERT(rf->is_write());
1121 if (rf->is_release())
1122 release_heads->push_back(rf);
1124 break; /* End of RMW chain */
1126 /** @todo Need to be smarter here... In the linux lock
1127 * example, this will run to the beginning of the program for
1129 /** @todo The way to be smarter here is to keep going until 1
1130 * thread has a release preceded by an acquire and you've seen
1133 /* acq_rel RMW is a sufficient stopping condition */
1134 if (rf->is_acquire() && rf->is_release())
1135 return true; /* complete */
1137 rf = rf->get_reads_from();
1140 /* read from future: need to settle this later */
1141 return false; /* incomplete */
1144 if (rf->is_release())
1145 return true; /* complete */
1147 /* else relaxed write; check modification order for contiguous subsequence
1148 * -> rf must be same thread as release */
1149 int tid = id_to_int(rf->get_tid());
1150 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1151 action_list_t *list = &(*thrd_lists)[tid];
1152 action_list_t::const_reverse_iterator rit;
1154 /* Find rf in the thread list */
1155 rit = std::find(list->rbegin(), list->rend(), rf);
1156 ASSERT(rit != list->rend());
1158 /* Find the last write/release */
1159 for (; rit != list->rend(); rit++)
1160 if ((*rit)->is_release())
1162 if (rit == list->rend()) {
1163 /* No write-release in this thread */
1164 return true; /* complete */
1166 ModelAction *release = *rit;
1168 ASSERT(rf->same_thread(release));
1170 bool certain = true;
1171 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1172 if (id_to_int(rf->get_tid()) == (int)i)
1174 list = &(*thrd_lists)[i];
1176 /* Can we ensure no future writes from this thread may break
1177 * the release seq? */
1178 bool future_ordered = false;
1180 ModelAction *last = get_last_action(int_to_id(i));
1181 if (last && (rf->happens_before(last) ||
1182 last->get_type() == THREAD_FINISH))
1183 future_ordered = true;
1185 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1186 const ModelAction *act = *rit;
1187 /* Reach synchronization -> this thread is complete */
1188 if (act->happens_before(release))
1190 if (rf->happens_before(act)) {
1191 future_ordered = true;
1195 /* Only writes can break release sequences */
1196 if (!act->is_write())
1199 /* Check modification order */
1200 if (mo_graph->checkReachable(rf, act)) {
1201 /* rf --mo--> act */
1202 future_ordered = true;
1205 if (mo_graph->checkReachable(act, release))
1206 /* act --mo--> release */
1208 if (mo_graph->checkReachable(release, act) &&
1209 mo_graph->checkReachable(act, rf)) {
1210 /* release --mo-> act --mo--> rf */
1211 return true; /* complete */
1215 if (!future_ordered)
1216 return false; /* This thread is uncertain */
1220 release_heads->push_back(release);
1225 * A public interface for getting the release sequence head(s) with which a
1226 * given ModelAction must synchronize. This function only returns a non-empty
1227 * result when it can locate a release sequence head with certainty. Otherwise,
1228 * it may mark the internal state of the ModelChecker so that it will handle
1229 * the release sequence at a later time, causing @a act to update its
1230 * synchronization at some later point in execution.
1231 * @param act The 'acquire' action that may read from a release sequence
1232 * @param release_heads A pass-by-reference return parameter. Will be filled
1233 * with the head(s) of the release sequence(s), if they exists with certainty.
1234 * @see ModelChecker::release_seq_head
1236 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1238 const ModelAction *rf = act->get_reads_from();
1240 complete = release_seq_head(rf, release_heads);
1242 /* add act to 'lazy checking' list */
1243 pending_acq_rel_seq->push_back(act);
1248 * Attempt to resolve all stashed operations that might synchronize with a
1249 * release sequence for a given location. This implements the "lazy" portion of
1250 * determining whether or not a release sequence was contiguous, since not all
1251 * modification order information is present at the time an action occurs.
1253 * @param location The location/object that should be checked for release
1254 * sequence resolutions. A NULL value means to check all locations.
1255 * @param work_queue The work queue to which to add work items as they are
1257 * @return True if any updates occurred (new synchronization, new mo_graph
1260 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1262 bool updated = false;
1263 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1264 while (it != pending_acq_rel_seq->end()) {
1265 ModelAction *act = *it;
1267 /* Only resolve sequences on the given location, if provided */
1268 if (location && act->get_location() != location) {
1273 const ModelAction *rf = act->get_reads_from();
1274 rel_heads_list_t release_heads;
1276 complete = release_seq_head(rf, &release_heads);
1277 for (unsigned int i = 0; i < release_heads.size(); i++) {
1278 if (!act->has_synchronized_with(release_heads[i])) {
1280 act->synchronize_with(release_heads[i]);
1285 /* Re-check act for mo_graph edges */
1286 work_queue->push_back(MOEdgeWorkEntry(act));
1288 /* propagate synchronization to later actions */
1289 action_list_t::reverse_iterator rit = action_trace->rbegin();
1290 for (; (*rit) != act; rit++) {
1291 ModelAction *propagate = *rit;
1292 if (act->happens_before(propagate)) {
1293 propagate->synchronize_with(act);
1294 /* Re-check 'propagate' for mo_graph edges */
1295 work_queue->push_back(MOEdgeWorkEntry(propagate));
1300 it = pending_acq_rel_seq->erase(it);
1305 // If we resolved promises or data races, see if we have realized a data race.
1306 if (checkDataRaces()) {
1314 * Performs various bookkeeping operations for the current ModelAction. For
1315 * instance, adds action to the per-object, per-thread action vector and to the
1316 * action trace list of all thread actions.
1318 * @param act is the ModelAction to add.
1320 void ModelChecker::add_action_to_lists(ModelAction *act)
1322 int tid = id_to_int(act->get_tid());
1323 action_trace->push_back(act);
1325 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1327 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1328 if (tid >= (int)vec->size())
1329 vec->resize(priv->next_thread_id);
1330 (*vec)[tid].push_back(act);
1332 if ((int)thrd_last_action->size() <= tid)
1333 thrd_last_action->resize(get_num_threads());
1334 (*thrd_last_action)[tid] = act;
1338 * @brief Get the last action performed by a particular Thread
1339 * @param tid The thread ID of the Thread in question
1340 * @return The last action in the thread
1342 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1344 int threadid = id_to_int(tid);
1345 if (threadid < (int)thrd_last_action->size())
1346 return (*thrd_last_action)[id_to_int(tid)];
1352 * Gets the last memory_order_seq_cst write (in the total global sequence)
1353 * performed on a particular object (i.e., memory location), not including the
1355 * @param curr The current ModelAction; also denotes the object location to
1357 * @return The last seq_cst write
1359 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1361 void *location = curr->get_location();
1362 action_list_t *list = obj_map->get_safe_ptr(location);
1363 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1364 action_list_t::reverse_iterator rit;
1365 for (rit = list->rbegin(); rit != list->rend(); rit++)
1366 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1372 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1373 * location). This function identifies the mutex according to the current
1374 * action, which is presumed to perform on the same mutex.
1375 * @param curr The current ModelAction; also denotes the object location to
1377 * @return The last unlock operation
1379 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1381 void *location = curr->get_location();
1382 action_list_t *list = obj_map->get_safe_ptr(location);
1383 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1384 action_list_t::reverse_iterator rit;
1385 for (rit = list->rbegin(); rit != list->rend(); rit++)
1386 if ((*rit)->is_unlock())
1391 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1393 ModelAction *parent = get_last_action(tid);
1395 parent = get_thread(tid)->get_creation();
1400 * Returns the clock vector for a given thread.
1401 * @param tid The thread whose clock vector we want
1402 * @return Desired clock vector
1404 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1406 return get_parent_action(tid)->get_cv();
1410 * Resolve a set of Promises with a current write. The set is provided in the
1411 * Node corresponding to @a write.
1412 * @param write The ModelAction that is fulfilling Promises
1413 * @return True if promises were resolved; false otherwise
1415 bool ModelChecker::resolve_promises(ModelAction *write)
1417 bool resolved = false;
1419 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1420 Promise *promise = (*promises)[promise_index];
1421 if (write->get_node()->get_promise(i)) {
1422 ModelAction *read = promise->get_action();
1423 if (read->is_rmw()) {
1424 mo_graph->addRMWEdge(write, read);
1426 read->read_from(write);
1427 //First fix up the modification order for actions that happened
1429 r_modification_order(read, write);
1430 //Next fix up the modification order for actions that happened
1432 post_r_modification_order(read, write);
1434 promises->erase(promises->begin() + promise_index);
1443 * Compute the set of promises that could potentially be satisfied by this
1444 * action. Note that the set computation actually appears in the Node, not in
1446 * @param curr The ModelAction that may satisfy promises
1448 void ModelChecker::compute_promises(ModelAction *curr)
1450 for (unsigned int i = 0; i < promises->size(); i++) {
1451 Promise *promise = (*promises)[i];
1452 const ModelAction *act = promise->get_action();
1453 if (!act->happens_before(curr) &&
1455 !act->is_synchronizing(curr) &&
1456 !act->same_thread(curr) &&
1457 promise->get_value() == curr->get_value()) {
1458 curr->get_node()->set_promise(i);
1463 /** Checks promises in response to change in ClockVector Threads. */
1464 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1466 for (unsigned int i = 0; i < promises->size(); i++) {
1467 Promise *promise = (*promises)[i];
1468 const ModelAction *act = promise->get_action();
1469 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1470 merge_cv->synchronized_since(act)) {
1471 //This thread is no longer able to send values back to satisfy the promise
1472 int num_synchronized_threads = promise->increment_threads();
1473 if (num_synchronized_threads == get_num_threads()) {
1474 //Promise has failed
1475 failed_promise = true;
1483 * Build up an initial set of all past writes that this 'read' action may read
1484 * from. This set is determined by the clock vector's "happens before"
1486 * @param curr is the current ModelAction that we are exploring; it must be a
1489 void ModelChecker::build_reads_from_past(ModelAction *curr)
1491 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1493 ASSERT(curr->is_read());
1495 ModelAction *last_seq_cst = NULL;
1497 /* Track whether this object has been initialized */
1498 bool initialized = false;
1500 if (curr->is_seqcst()) {
1501 last_seq_cst = get_last_seq_cst(curr);
1502 /* We have to at least see the last sequentially consistent write,
1503 so we are initialized. */
1504 if (last_seq_cst != NULL)
1508 /* Iterate over all threads */
1509 for (i = 0; i < thrd_lists->size(); i++) {
1510 /* Iterate over actions in thread, starting from most recent */
1511 action_list_t *list = &(*thrd_lists)[i];
1512 action_list_t::reverse_iterator rit;
1513 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1514 ModelAction *act = *rit;
1516 /* Only consider 'write' actions */
1517 if (!act->is_write() || act == curr)
1520 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1521 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1522 DEBUG("Adding action to may_read_from:\n");
1523 if (DBG_ENABLED()) {
1527 curr->get_node()->add_read_from(act);
1530 /* Include at most one act per-thread that "happens before" curr */
1531 if (act->happens_before(curr)) {
1539 /** @todo Need a more informative way of reporting errors. */
1540 printf("ERROR: may read from uninitialized atomic\n");
1543 if (DBG_ENABLED() || !initialized) {
1544 printf("Reached read action:\n");
1546 printf("Printing may_read_from\n");
1547 curr->get_node()->print_may_read_from();
1548 printf("End printing may_read_from\n");
1551 ASSERT(initialized);
1554 static void print_list(action_list_t *list)
1556 action_list_t::iterator it;
1558 printf("---------------------------------------------------------------------\n");
1561 for (it = list->begin(); it != list->end(); it++) {
1564 printf("---------------------------------------------------------------------\n");
1567 void ModelChecker::print_summary()
1570 printf("Number of executions: %d\n", num_executions);
1571 printf("Number of feasible executions: %d\n", num_feasible_executions);
1572 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1574 #if SUPPORT_MOD_ORDER_DUMP
1576 char buffername[100];
1577 sprintf(buffername, "exec%04u", num_executions);
1578 mo_graph->dumpGraphToFile(buffername);
1581 if (!isfinalfeasible())
1582 printf("INFEASIBLE EXECUTION!\n");
1583 print_list(action_trace);
1588 * Add a Thread to the system for the first time. Should only be called once
1590 * @param t The Thread to add
1592 void ModelChecker::add_thread(Thread *t)
1594 thread_map->put(id_to_int(t->get_id()), t);
1595 scheduler->add_thread(t);
1599 * Removes a thread from the scheduler.
1600 * @param the thread to remove.
1602 void ModelChecker::remove_thread(Thread *t)
1604 scheduler->remove_thread(t);
1608 * Switch from a user-context to the "master thread" context (a.k.a. system
1609 * context). This switch is made with the intention of exploring a particular
1610 * model-checking action (described by a ModelAction object). Must be called
1611 * from a user-thread context.
1612 * @param act The current action that will be explored. Must not be NULL.
1613 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1615 int ModelChecker::switch_to_master(ModelAction *act)
1618 Thread *old = thread_current();
1619 set_current_action(act);
1620 old->set_state(THREAD_READY);
1621 return Thread::swap(old, &system_context);
1625 * Takes the next step in the execution, if possible.
1626 * @return Returns true (success) if a step was taken and false otherwise.
1628 bool ModelChecker::take_step() {
1632 Thread * curr = thread_current();
1634 if (curr->get_state() == THREAD_READY) {
1635 ASSERT(priv->current_action);
1637 if (priv->current_action->get_seq_number()>600)
1639 priv->nextThread = check_current_action(priv->current_action);
1640 priv->current_action = NULL;
1641 if (curr->is_blocked() || curr->is_complete())
1642 scheduler->remove_thread(curr);
1647 Thread * next = scheduler->next_thread(priv->nextThread);
1649 /* Infeasible -> don't take any more steps */
1654 next->set_state(THREAD_RUNNING);
1655 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1657 /* next == NULL -> don't take any more steps */
1661 if ( next->get_pending() != NULL ) {
1662 //restart a pending action
1663 set_current_action(next->get_pending());
1664 next->set_pending(NULL);
1665 next->set_state(THREAD_READY);
1669 /* Return false only if swap fails with an error */
1670 return (Thread::swap(&system_context, next) == 0);
1673 /** Runs the current execution until threre are no more steps to take. */
1674 void ModelChecker::finish_execution() {
1677 while (take_step());