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 */
23 scheduler(new Scheduler()),
25 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.
251 void ModelChecker::set_backtracking(ModelAction *act)
253 Thread *t = get_thread(act);
254 ModelAction * prev = get_last_conflict(act);
258 Node * node = prev->get_node()->get_parent();
260 int low_tid, high_tid;
261 if (node->is_enabled(t)) {
262 low_tid = id_to_int(act->get_tid());
263 high_tid = low_tid+1;
266 high_tid = get_num_threads();
269 for(int i = low_tid; i < high_tid; i++) {
270 thread_id_t tid = int_to_id(i);
271 if (!node->is_enabled(tid))
274 /* Check if this has been explored already */
275 if (node->has_been_explored(tid))
278 /* Cache the latest backtracking point */
279 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
280 priv->next_backtrack = prev;
282 /* If this is a new backtracking point, mark the tree */
283 if (!node->set_backtrack(tid))
285 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
286 prev->get_tid(), t->get_id());
295 * Returns last backtracking point. The model checker will explore a different
296 * path for this point in the next execution.
297 * @return The ModelAction at which the next execution should diverge.
299 ModelAction * ModelChecker::get_next_backtrack()
301 ModelAction *next = priv->next_backtrack;
302 priv->next_backtrack = NULL;
307 * Processes a read or rmw model action.
308 * @param curr is the read model action to process.
309 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
310 * @return True if processing this read updates the mo_graph.
312 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
315 bool updated = false;
317 const ModelAction *reads_from = curr->get_node()->get_read_from();
318 if (reads_from != NULL) {
319 mo_graph->startChanges();
321 value = reads_from->get_value();
322 bool r_status = false;
324 if (!second_part_of_rmw) {
326 r_status = r_modification_order(curr, reads_from);
330 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
331 mo_graph->rollbackChanges();
332 too_many_reads = false;
336 curr->read_from(reads_from);
337 mo_graph->commitChanges();
339 } else if (!second_part_of_rmw) {
340 /* Read from future value */
341 value = curr->get_node()->get_future_value();
342 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
343 curr->read_from(NULL);
344 Promise *valuepromise = new Promise(curr, value, expiration);
345 promises->push_back(valuepromise);
347 get_thread(curr)->set_return_value(value);
353 * Processes a lock, trylock, or unlock model action. @param curr is
354 * the read model action to process.
356 * The try lock operation checks whether the lock is taken. If not,
357 * it falls to the normal lock operation case. If so, it returns
360 * The lock operation has already been checked that it is enabled, so
361 * it just grabs the lock and synchronizes with the previous unlock.
363 * The unlock operation has to re-enable all of the threads that are
364 * waiting on the lock.
366 void ModelChecker::process_mutex(ModelAction *curr) {
367 std::mutex *mutex = (std::mutex *)curr->get_location();
368 struct std::mutex_state *state = mutex->get_state();
369 switch (curr->get_type()) {
370 case ATOMIC_TRYLOCK: {
371 bool success = !state->islocked;
372 curr->set_try_lock(success);
374 get_thread(curr)->set_return_value(0);
377 get_thread(curr)->set_return_value(1);
379 //otherwise fall into the lock case
381 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
382 printf("Lock access before initialization\n");
385 state->islocked = true;
386 ModelAction *unlock = get_last_unlock(curr);
387 //synchronize with the previous unlock statement
389 curr->synchronize_with(unlock);
392 case ATOMIC_UNLOCK: {
394 state->islocked = false;
395 //wake up the other threads
396 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
397 //activate all the waiting threads
398 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
399 scheduler->add_thread(get_thread((*rit)->get_tid()));
410 * Process a write ModelAction
411 * @param curr The ModelAction to process
412 * @return True if the mo_graph was updated or promises were resolved
414 bool ModelChecker::process_write(ModelAction *curr)
416 bool updated_mod_order = w_modification_order(curr);
417 bool updated_promises = resolve_promises(curr);
419 if (promises->size() == 0) {
420 for (unsigned int i = 0; i < futurevalues->size(); i++) {
421 struct PendingFutureValue pfv = (*futurevalues)[i];
422 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
423 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
424 priv->next_backtrack = pfv.act;
426 futurevalues->resize(0);
429 mo_graph->commitChanges();
430 get_thread(curr)->set_return_value(VALUE_NONE);
431 return updated_mod_order || updated_promises;
435 * Initialize the current action by performing one or more of the following
436 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
437 * in the NodeStack, manipulating backtracking sets, allocating and
438 * initializing clock vectors, and computing the promises to fulfill.
440 * @param curr The current action, as passed from the user context; may be
441 * freed/invalidated after the execution of this function
442 * @return The current action, as processed by the ModelChecker. Is only the
443 * same as the parameter @a curr if this is a newly-explored action.
445 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
447 ModelAction *newcurr;
449 if (curr->is_rmwc() || curr->is_rmw()) {
450 newcurr = process_rmw(curr);
452 compute_promises(newcurr);
456 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
458 /* First restore type and order in case of RMW operation */
460 newcurr->copy_typeandorder(curr);
462 ASSERT(curr->get_location() == newcurr->get_location());
463 newcurr->copy_from_new(curr);
465 /* Discard duplicate ModelAction; use action from NodeStack */
468 /* If we have diverged, we need to reset the clock vector. */
470 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
474 * Perform one-time actions when pushing new ModelAction onto
477 curr->create_cv(get_parent_action(curr->get_tid()));
478 if (curr->is_write())
479 compute_promises(curr);
485 * This method checks whether a model action is enabled at the given point.
486 * At this point, it checks whether a lock operation would be successful at this point.
487 * If not, it puts the thread in a waiter list.
488 * @param curr is the ModelAction to check whether it is enabled.
489 * @return a bool that indicates whether the action is enabled.
492 bool ModelChecker::check_action_enabled(ModelAction *curr) {
493 if (curr->is_lock()) {
494 std::mutex * lock = (std::mutex *)curr->get_location();
495 struct std::mutex_state * state = lock->get_state();
496 if (state->islocked) {
497 //Stick the action in the appropriate waiting queue
498 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
507 * This is the heart of the model checker routine. It performs model-checking
508 * actions corresponding to a given "current action." Among other processes, it
509 * calculates reads-from relationships, updates synchronization clock vectors,
510 * forms a memory_order constraints graph, and handles replay/backtrack
511 * execution when running permutations of previously-observed executions.
513 * @param curr The current action to process
514 * @return The next Thread that must be executed. May be NULL if ModelChecker
515 * makes no choice (e.g., according to replay execution, combining RMW actions,
518 Thread * ModelChecker::check_current_action(ModelAction *curr)
522 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
524 if (!check_action_enabled(curr)) {
525 //we'll make the execution look like we chose to run this action
526 //much later...when a lock is actually available to relese
527 get_current_thread()->set_pending(curr);
528 remove_thread(get_current_thread());
529 return get_next_thread(NULL);
532 ModelAction *newcurr = initialize_curr_action(curr);
534 /* Add the action to lists before any other model-checking tasks */
535 if (!second_part_of_rmw)
536 add_action_to_lists(newcurr);
538 /* Build may_read_from set for newly-created actions */
539 if (curr == newcurr && curr->is_read())
540 build_reads_from_past(curr);
543 /* Thread specific actions */
544 switch (curr->get_type()) {
545 case THREAD_CREATE: {
546 Thread *th = (Thread *)curr->get_location();
547 th->set_creation(curr);
551 Thread *waiting, *blocking;
552 waiting = get_thread(curr);
553 blocking = (Thread *)curr->get_location();
554 if (!blocking->is_complete()) {
555 blocking->push_wait_list(curr);
556 scheduler->sleep(waiting);
558 do_complete_join(curr);
562 case THREAD_FINISH: {
563 Thread *th = get_thread(curr);
564 while (!th->wait_list_empty()) {
565 ModelAction *act = th->pop_wait_list();
566 Thread *wake = get_thread(act);
567 scheduler->wake(wake);
568 do_complete_join(act);
574 check_promises(NULL, curr->get_cv());
581 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
583 while (!work_queue.empty()) {
584 WorkQueueEntry work = work_queue.front();
585 work_queue.pop_front();
588 case WORK_CHECK_CURR_ACTION: {
589 ModelAction *act = work.action;
590 bool updated = false;
591 if (act->is_read() && process_read(act, second_part_of_rmw))
594 if (act->is_write() && process_write(act))
597 if (act->is_mutex_op())
601 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
604 case WORK_CHECK_RELEASE_SEQ:
605 resolve_release_sequences(work.location, &work_queue);
607 case WORK_CHECK_MO_EDGES: {
608 /** @todo Complete verification of work_queue */
609 ModelAction *act = work.action;
610 bool updated = false;
612 if (act->is_read()) {
613 if (r_modification_order(act, act->get_reads_from()))
616 if (act->is_write()) {
617 if (w_modification_order(act))
622 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
631 check_curr_backtracking(curr);
633 set_backtracking(curr);
635 return get_next_thread(curr);
639 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
640 * operation from the Thread it is joining with. Must be called after the
641 * completion of the Thread in question.
642 * @param join The THREAD_JOIN action
644 void ModelChecker::do_complete_join(ModelAction *join)
646 Thread *blocking = (Thread *)join->get_location();
647 ModelAction *act = get_last_action(blocking->get_id());
648 join->synchronize_with(act);
651 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
652 Node *currnode = curr->get_node();
653 Node *parnode = currnode->get_parent();
655 if ((!parnode->backtrack_empty() ||
656 !currnode->read_from_empty() ||
657 !currnode->future_value_empty() ||
658 !currnode->promise_empty())
659 && (!priv->next_backtrack ||
660 *curr > *priv->next_backtrack)) {
661 priv->next_backtrack = curr;
665 bool ModelChecker::promises_expired() {
666 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
667 Promise *promise = (*promises)[promise_index];
668 if (promise->get_expiration()<priv->used_sequence_numbers) {
675 /** @return whether the current partial trace must be a prefix of a
677 bool ModelChecker::isfeasibleprefix() {
678 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
681 /** @return whether the current partial trace is feasible. */
682 bool ModelChecker::isfeasible() {
683 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
686 /** @return whether the current partial trace is feasible other than
687 * multiple RMW reading from the same store. */
688 bool ModelChecker::isfeasibleotherthanRMW() {
690 if (mo_graph->checkForCycles())
691 DEBUG("Infeasible: modification order cycles\n");
693 DEBUG("Infeasible: failed promise\n");
695 DEBUG("Infeasible: too many reads\n");
696 if (promises_expired())
697 DEBUG("Infeasible: promises expired\n");
699 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
702 /** Returns whether the current completed trace is feasible. */
703 bool ModelChecker::isfinalfeasible() {
704 if (DBG_ENABLED() && promises->size() != 0)
705 DEBUG("Infeasible: unrevolved promises\n");
707 return isfeasible() && promises->size() == 0;
710 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
711 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
712 int tid = id_to_int(act->get_tid());
713 ModelAction *lastread = get_last_action(tid);
714 lastread->process_rmw(act);
715 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
716 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
717 mo_graph->commitChanges();
723 * Checks whether a thread has read from the same write for too many times
724 * without seeing the effects of a later write.
727 * 1) there must a different write that we could read from that would satisfy the modification order,
728 * 2) we must have read from the same value in excess of maxreads times, and
729 * 3) that other write must have been in the reads_from set for maxreads times.
731 * If so, we decide that the execution is no longer feasible.
733 void ModelChecker::check_recency(ModelAction *curr) {
734 if (params.maxreads != 0) {
735 if (curr->get_node()->get_read_from_size() <= 1)
738 //Must make sure that execution is currently feasible... We could
739 //accidentally clear by rolling back
743 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
744 int tid = id_to_int(curr->get_tid());
747 if ((int)thrd_lists->size() <= tid)
750 action_list_t *list = &(*thrd_lists)[tid];
752 action_list_t::reverse_iterator rit = list->rbegin();
754 for (; (*rit) != curr; rit++)
756 /* go past curr now */
759 action_list_t::reverse_iterator ritcopy = rit;
760 //See if we have enough reads from the same value
762 for (; count < params.maxreads; rit++,count++) {
763 if (rit==list->rend())
765 ModelAction *act = *rit;
768 if (act->get_reads_from() != curr->get_reads_from())
770 if (act->get_node()->get_read_from_size() <= 1)
774 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
776 const ModelAction * write = curr->get_node()->get_read_from_at(i);
777 //Need a different write
778 if (write==curr->get_reads_from())
781 /* Test to see whether this is a feasible write to read from*/
782 mo_graph->startChanges();
783 r_modification_order(curr, write);
784 bool feasiblereadfrom = isfeasible();
785 mo_graph->rollbackChanges();
787 if (!feasiblereadfrom)
791 bool feasiblewrite = true;
792 //new we need to see if this write works for everyone
794 for (int loop = count; loop>0; loop--,rit++) {
795 ModelAction *act=*rit;
796 bool foundvalue = false;
797 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
798 if (act->get_node()->get_read_from_at(i)==write) {
804 feasiblewrite = false;
809 too_many_reads = true;
817 * Updates the mo_graph with the constraints imposed from the current
820 * Basic idea is the following: Go through each other thread and find
821 * the lastest action that happened before our read. Two cases:
823 * (1) The action is a write => that write must either occur before
824 * the write we read from or be the write we read from.
826 * (2) The action is a read => the write that that action read from
827 * must occur before the write we read from or be the same write.
829 * @param curr The current action. Must be a read.
830 * @param rf The action that curr reads from. Must be a write.
831 * @return True if modification order edges were added; false otherwise
833 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
835 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
838 ASSERT(curr->is_read());
840 /* Iterate over all threads */
841 for (i = 0; i < thrd_lists->size(); i++) {
842 /* Iterate over actions in thread, starting from most recent */
843 action_list_t *list = &(*thrd_lists)[i];
844 action_list_t::reverse_iterator rit;
845 for (rit = list->rbegin(); rit != list->rend(); rit++) {
846 ModelAction *act = *rit;
849 * Include at most one act per-thread that "happens
850 * before" curr. Don't consider reflexively.
852 if (act->happens_before(curr) && act != curr) {
853 if (act->is_write()) {
855 mo_graph->addEdge(act, rf);
859 const ModelAction *prevreadfrom = act->get_reads_from();
860 if (prevreadfrom != NULL && rf != prevreadfrom) {
861 mo_graph->addEdge(prevreadfrom, rf);
873 /** This method fixes up the modification order when we resolve a
874 * promises. The basic problem is that actions that occur after the
875 * read curr could not property add items to the modification order
878 * So for each thread, we find the earliest item that happens after
879 * the read curr. This is the item we have to fix up with additional
880 * constraints. If that action is write, we add a MO edge between
881 * the Action rf and that action. If the action is a read, we add a
882 * MO edge between the Action rf, and whatever the read accessed.
884 * @param curr is the read ModelAction that we are fixing up MO edges for.
885 * @param rf is the write ModelAction that curr reads from.
889 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
891 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
893 ASSERT(curr->is_read());
895 /* Iterate over all threads */
896 for (i = 0; i < thrd_lists->size(); i++) {
897 /* Iterate over actions in thread, starting from most recent */
898 action_list_t *list = &(*thrd_lists)[i];
899 action_list_t::reverse_iterator rit;
900 ModelAction *lastact = NULL;
902 /* Find last action that happens after curr */
903 for (rit = list->rbegin(); rit != list->rend(); rit++) {
904 ModelAction *act = *rit;
905 if (curr->happens_before(act)) {
911 /* Include at most one act per-thread that "happens before" curr */
912 if (lastact != NULL) {
913 if (lastact->is_read()) {
914 const ModelAction *postreadfrom = lastact->get_reads_from();
915 if (postreadfrom != NULL&&rf != postreadfrom)
916 mo_graph->addEdge(rf, postreadfrom);
917 } else if (rf != lastact) {
918 mo_graph->addEdge(rf, lastact);
926 * Updates the mo_graph with the constraints imposed from the current write.
928 * Basic idea is the following: Go through each other thread and find
929 * the lastest action that happened before our write. Two cases:
931 * (1) The action is a write => that write must occur before
934 * (2) The action is a read => the write that that action read from
935 * must occur before the current write.
937 * This method also handles two other issues:
939 * (I) Sequential Consistency: Making sure that if the current write is
940 * seq_cst, that it occurs after the previous seq_cst write.
942 * (II) Sending the write back to non-synchronizing reads.
944 * @param curr The current action. Must be a write.
945 * @return True if modification order edges were added; false otherwise
947 bool ModelChecker::w_modification_order(ModelAction *curr)
949 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
952 ASSERT(curr->is_write());
954 if (curr->is_seqcst()) {
955 /* We have to at least see the last sequentially consistent write,
956 so we are initialized. */
957 ModelAction *last_seq_cst = get_last_seq_cst(curr);
958 if (last_seq_cst != NULL) {
959 mo_graph->addEdge(last_seq_cst, curr);
964 /* Iterate over all threads */
965 for (i = 0; i < thrd_lists->size(); i++) {
966 /* Iterate over actions in thread, starting from most recent */
967 action_list_t *list = &(*thrd_lists)[i];
968 action_list_t::reverse_iterator rit;
969 for (rit = list->rbegin(); rit != list->rend(); rit++) {
970 ModelAction *act = *rit;
973 * If RMW, we already have all relevant edges,
974 * so just skip to next thread.
975 * If normal write, we need to look at earlier
976 * actions, so continue processing list.
985 * Include at most one act per-thread that "happens
988 if (act->happens_before(curr)) {
990 * Note: if act is RMW, just add edge:
992 * The following edge should be handled elsewhere:
993 * readfrom(act) --mo--> act
996 mo_graph->addEdge(act, curr);
997 else if (act->is_read() && act->get_reads_from() != NULL)
998 mo_graph->addEdge(act->get_reads_from(), curr);
1001 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1002 !act->same_thread(curr)) {
1003 /* We have an action that:
1004 (1) did not happen before us
1005 (2) is a read and we are a write
1006 (3) cannot synchronize with us
1007 (4) is in a different thread
1009 that read could potentially read from our write.
1011 if (thin_air_constraint_may_allow(curr, act)) {
1013 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1014 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1015 futurevalues->push_back(pfv);
1025 /** Arbitrary reads from the future are not allowed. Section 29.3
1026 * part 9 places some constraints. This method checks one result of constraint
1027 * constraint. Others require compiler support. */
1029 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1030 if (!writer->is_rmw())
1033 if (!reader->is_rmw())
1036 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1037 if (search == reader)
1039 if (search->get_tid() == reader->get_tid() &&
1040 search->happens_before(reader))
1048 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1049 * The ModelAction under consideration is expected to be taking part in
1050 * release/acquire synchronization as an object of the "reads from" relation.
1051 * Note that this can only provide release sequence support for RMW chains
1052 * which do not read from the future, as those actions cannot be traced until
1053 * their "promise" is fulfilled. Similarly, we may not even establish the
1054 * presence of a release sequence with certainty, as some modification order
1055 * constraints may be decided further in the future. Thus, this function
1056 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1057 * and a boolean representing certainty.
1059 * @todo Finish lazy updating, when promises are fulfilled in the future
1060 * @param rf The action that might be part of a release sequence. Must be a
1062 * @param release_heads A pass-by-reference style return parameter. After
1063 * execution of this function, release_heads will contain the heads of all the
1064 * relevant release sequences, if any exists
1065 * @return true, if the ModelChecker is certain that release_heads is complete;
1068 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1071 /* read from future: need to settle this later */
1072 return false; /* incomplete */
1075 ASSERT(rf->is_write());
1077 if (rf->is_release())
1078 release_heads->push_back(rf);
1080 /* We need a RMW action that is both an acquire and release to stop */
1081 /** @todo Need to be smarter here... In the linux lock
1082 * example, this will run to the beginning of the program for
1084 if (rf->is_acquire() && rf->is_release())
1085 return true; /* complete */
1086 return release_seq_head(rf->get_reads_from(), release_heads);
1088 if (rf->is_release())
1089 return true; /* complete */
1091 /* else relaxed write; check modification order for contiguous subsequence
1092 * -> rf must be same thread as release */
1093 int tid = id_to_int(rf->get_tid());
1094 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1095 action_list_t *list = &(*thrd_lists)[tid];
1096 action_list_t::const_reverse_iterator rit;
1098 /* Find rf in the thread list */
1099 rit = std::find(list->rbegin(), list->rend(), rf);
1100 ASSERT(rit != list->rend());
1102 /* Find the last write/release */
1103 for (; rit != list->rend(); rit++)
1104 if ((*rit)->is_release())
1106 if (rit == list->rend()) {
1107 /* No write-release in this thread */
1108 return true; /* complete */
1110 ModelAction *release = *rit;
1112 ASSERT(rf->same_thread(release));
1114 bool certain = true;
1115 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1116 if (id_to_int(rf->get_tid()) == (int)i)
1118 list = &(*thrd_lists)[i];
1120 /* Can we ensure no future writes from this thread may break
1121 * the release seq? */
1122 bool future_ordered = false;
1124 ModelAction *last = get_last_action(int_to_id(i));
1125 if (last && rf->happens_before(last))
1126 future_ordered = true;
1128 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1129 const ModelAction *act = *rit;
1130 /* Reach synchronization -> this thread is complete */
1131 if (act->happens_before(release))
1133 if (rf->happens_before(act)) {
1134 future_ordered = true;
1138 /* Only writes can break release sequences */
1139 if (!act->is_write())
1142 /* Check modification order */
1143 if (mo_graph->checkReachable(rf, act)) {
1144 /* rf --mo--> act */
1145 future_ordered = true;
1148 if (mo_graph->checkReachable(act, release))
1149 /* act --mo--> release */
1151 if (mo_graph->checkReachable(release, act) &&
1152 mo_graph->checkReachable(act, rf)) {
1153 /* release --mo-> act --mo--> rf */
1154 return true; /* complete */
1158 if (!future_ordered)
1159 return false; /* This thread is uncertain */
1163 release_heads->push_back(release);
1168 * A public interface for getting the release sequence head(s) with which a
1169 * given ModelAction must synchronize. This function only returns a non-empty
1170 * result when it can locate a release sequence head with certainty. Otherwise,
1171 * it may mark the internal state of the ModelChecker so that it will handle
1172 * the release sequence at a later time, causing @a act to update its
1173 * synchronization at some later point in execution.
1174 * @param act The 'acquire' action that may read from a release sequence
1175 * @param release_heads A pass-by-reference return parameter. Will be filled
1176 * with the head(s) of the release sequence(s), if they exists with certainty.
1177 * @see ModelChecker::release_seq_head
1179 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1181 const ModelAction *rf = act->get_reads_from();
1183 complete = release_seq_head(rf, release_heads);
1185 /* add act to 'lazy checking' list */
1186 pending_acq_rel_seq->push_back(act);
1191 * Attempt to resolve all stashed operations that might synchronize with a
1192 * release sequence for a given location. This implements the "lazy" portion of
1193 * determining whether or not a release sequence was contiguous, since not all
1194 * modification order information is present at the time an action occurs.
1196 * @param location The location/object that should be checked for release
1197 * sequence resolutions. A NULL value means to check all locations.
1198 * @param work_queue The work queue to which to add work items as they are
1200 * @return True if any updates occurred (new synchronization, new mo_graph
1203 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1205 bool updated = false;
1206 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1207 while (it != pending_acq_rel_seq->end()) {
1208 ModelAction *act = *it;
1210 /* Only resolve sequences on the given location, if provided */
1211 if (location && act->get_location() != location) {
1216 const ModelAction *rf = act->get_reads_from();
1217 rel_heads_list_t release_heads;
1219 complete = release_seq_head(rf, &release_heads);
1220 for (unsigned int i = 0; i < release_heads.size(); i++) {
1221 if (!act->has_synchronized_with(release_heads[i])) {
1223 act->synchronize_with(release_heads[i]);
1228 /* Re-check act for mo_graph edges */
1229 work_queue->push_back(MOEdgeWorkEntry(act));
1231 /* propagate synchronization to later actions */
1232 action_list_t::reverse_iterator it = action_trace->rbegin();
1233 for (; (*it) != act; it++) {
1234 ModelAction *propagate = *it;
1235 if (act->happens_before(propagate)) {
1236 propagate->synchronize_with(act);
1237 /* Re-check 'propagate' for mo_graph edges */
1238 work_queue->push_back(MOEdgeWorkEntry(propagate));
1243 it = pending_acq_rel_seq->erase(it);
1248 // If we resolved promises or data races, see if we have realized a data race.
1249 if (checkDataRaces()) {
1257 * Performs various bookkeeping operations for the current ModelAction. For
1258 * instance, adds action to the per-object, per-thread action vector and to the
1259 * action trace list of all thread actions.
1261 * @param act is the ModelAction to add.
1263 void ModelChecker::add_action_to_lists(ModelAction *act)
1265 int tid = id_to_int(act->get_tid());
1266 action_trace->push_back(act);
1268 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1270 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1271 if (tid >= (int)vec->size())
1272 vec->resize(priv->next_thread_id);
1273 (*vec)[tid].push_back(act);
1275 if ((int)thrd_last_action->size() <= tid)
1276 thrd_last_action->resize(get_num_threads());
1277 (*thrd_last_action)[tid] = act;
1281 * @brief Get the last action performed by a particular Thread
1282 * @param tid The thread ID of the Thread in question
1283 * @return The last action in the thread
1285 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1287 int threadid = id_to_int(tid);
1288 if (threadid < (int)thrd_last_action->size())
1289 return (*thrd_last_action)[id_to_int(tid)];
1295 * Gets the last memory_order_seq_cst write (in the total global sequence)
1296 * performed on a particular object (i.e., memory location), not including the
1298 * @param curr The current ModelAction; also denotes the object location to
1300 * @return The last seq_cst write
1302 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1304 void *location = curr->get_location();
1305 action_list_t *list = obj_map->get_safe_ptr(location);
1306 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1307 action_list_t::reverse_iterator rit;
1308 for (rit = list->rbegin(); rit != list->rend(); rit++)
1309 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1315 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1316 * location). This function identifies the mutex according to the current
1317 * action, which is presumed to perform on the same mutex.
1318 * @param curr The current ModelAction; also denotes the object location to
1320 * @return The last unlock operation
1322 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1324 void *location = curr->get_location();
1325 action_list_t *list = obj_map->get_safe_ptr(location);
1326 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1327 action_list_t::reverse_iterator rit;
1328 for (rit = list->rbegin(); rit != list->rend(); rit++)
1329 if ((*rit)->is_unlock())
1334 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1336 ModelAction *parent = get_last_action(tid);
1338 parent = get_thread(tid)->get_creation();
1343 * Returns the clock vector for a given thread.
1344 * @param tid The thread whose clock vector we want
1345 * @return Desired clock vector
1347 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1349 return get_parent_action(tid)->get_cv();
1353 * Resolve a set of Promises with a current write. The set is provided in the
1354 * Node corresponding to @a write.
1355 * @param write The ModelAction that is fulfilling Promises
1356 * @return True if promises were resolved; false otherwise
1358 bool ModelChecker::resolve_promises(ModelAction *write)
1360 bool resolved = false;
1362 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1363 Promise *promise = (*promises)[promise_index];
1364 if (write->get_node()->get_promise(i)) {
1365 ModelAction *read = promise->get_action();
1366 read->read_from(write);
1367 if (read->is_rmw()) {
1368 mo_graph->addRMWEdge(write, read);
1370 //First fix up the modification order for actions that happened
1372 r_modification_order(read, write);
1373 //Next fix up the modification order for actions that happened
1375 post_r_modification_order(read, write);
1376 promises->erase(promises->begin() + promise_index);
1385 * Compute the set of promises that could potentially be satisfied by this
1386 * action. Note that the set computation actually appears in the Node, not in
1388 * @param curr The ModelAction that may satisfy promises
1390 void ModelChecker::compute_promises(ModelAction *curr)
1392 for (unsigned int i = 0; i < promises->size(); i++) {
1393 Promise *promise = (*promises)[i];
1394 const ModelAction *act = promise->get_action();
1395 if (!act->happens_before(curr) &&
1397 !act->is_synchronizing(curr) &&
1398 !act->same_thread(curr) &&
1399 promise->get_value() == curr->get_value()) {
1400 curr->get_node()->set_promise(i);
1405 /** Checks promises in response to change in ClockVector Threads. */
1406 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1408 for (unsigned int i = 0; i < promises->size(); i++) {
1409 Promise *promise = (*promises)[i];
1410 const ModelAction *act = promise->get_action();
1411 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1412 merge_cv->synchronized_since(act)) {
1413 //This thread is no longer able to send values back to satisfy the promise
1414 int num_synchronized_threads = promise->increment_threads();
1415 if (num_synchronized_threads == get_num_threads()) {
1416 //Promise has failed
1417 failed_promise = true;
1425 * Build up an initial set of all past writes that this 'read' action may read
1426 * from. This set is determined by the clock vector's "happens before"
1428 * @param curr is the current ModelAction that we are exploring; it must be a
1431 void ModelChecker::build_reads_from_past(ModelAction *curr)
1433 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1435 ASSERT(curr->is_read());
1437 ModelAction *last_seq_cst = NULL;
1439 /* Track whether this object has been initialized */
1440 bool initialized = false;
1442 if (curr->is_seqcst()) {
1443 last_seq_cst = get_last_seq_cst(curr);
1444 /* We have to at least see the last sequentially consistent write,
1445 so we are initialized. */
1446 if (last_seq_cst != NULL)
1450 /* Iterate over all threads */
1451 for (i = 0; i < thrd_lists->size(); i++) {
1452 /* Iterate over actions in thread, starting from most recent */
1453 action_list_t *list = &(*thrd_lists)[i];
1454 action_list_t::reverse_iterator rit;
1455 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1456 ModelAction *act = *rit;
1458 /* Only consider 'write' actions */
1459 if (!act->is_write() || act == curr)
1462 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1463 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1464 DEBUG("Adding action to may_read_from:\n");
1465 if (DBG_ENABLED()) {
1469 curr->get_node()->add_read_from(act);
1472 /* Include at most one act per-thread that "happens before" curr */
1473 if (act->happens_before(curr)) {
1481 /** @todo Need a more informative way of reporting errors. */
1482 printf("ERROR: may read from uninitialized atomic\n");
1485 if (DBG_ENABLED() || !initialized) {
1486 printf("Reached read action:\n");
1488 printf("Printing may_read_from\n");
1489 curr->get_node()->print_may_read_from();
1490 printf("End printing may_read_from\n");
1493 ASSERT(initialized);
1496 static void print_list(action_list_t *list)
1498 action_list_t::iterator it;
1500 printf("---------------------------------------------------------------------\n");
1503 for (it = list->begin(); it != list->end(); it++) {
1506 printf("---------------------------------------------------------------------\n");
1509 void ModelChecker::print_summary()
1512 printf("Number of executions: %d\n", num_executions);
1513 printf("Number of feasible executions: %d\n", num_feasible_executions);
1514 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1516 #if SUPPORT_MOD_ORDER_DUMP
1518 char buffername[100];
1519 sprintf(buffername, "exec%04u", num_executions);
1520 mo_graph->dumpGraphToFile(buffername);
1523 if (!isfinalfeasible())
1524 printf("INFEASIBLE EXECUTION!\n");
1525 print_list(action_trace);
1530 * Add a Thread to the system for the first time. Should only be called once
1532 * @param t The Thread to add
1534 void ModelChecker::add_thread(Thread *t)
1536 thread_map->put(id_to_int(t->get_id()), t);
1537 scheduler->add_thread(t);
1541 * Removes a thread from the scheduler.
1542 * @param the thread to remove.
1545 void ModelChecker::remove_thread(Thread *t)
1547 scheduler->remove_thread(t);
1551 * Switch from a user-context to the "master thread" context (a.k.a. system
1552 * context). This switch is made with the intention of exploring a particular
1553 * model-checking action (described by a ModelAction object). Must be called
1554 * from a user-thread context.
1555 * @param act The current action that will be explored. Must not be NULL.
1556 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1558 int ModelChecker::switch_to_master(ModelAction *act)
1561 Thread *old = thread_current();
1562 set_current_action(act);
1563 old->set_state(THREAD_READY);
1564 return Thread::swap(old, &system_context);
1568 * Takes the next step in the execution, if possible.
1569 * @return Returns true (success) if a step was taken and false otherwise.
1571 bool ModelChecker::take_step() {
1575 Thread * curr = thread_current();
1577 if (curr->get_state() == THREAD_READY) {
1578 ASSERT(priv->current_action);
1580 priv->nextThread = check_current_action(priv->current_action);
1581 priv->current_action = NULL;
1582 if (curr->is_blocked() || curr->is_complete())
1583 scheduler->remove_thread(curr);
1588 Thread * next = scheduler->next_thread(priv->nextThread);
1590 /* Infeasible -> don't take any more steps */
1595 next->set_state(THREAD_RUNNING);
1596 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1598 /* next == NULL -> don't take any more steps */
1602 if ( next->get_pending() != NULL ) {
1603 //restart a pending action
1604 set_current_action(next->get_pending());
1605 next->set_pending(NULL);
1606 next->set_state(THREAD_READY);
1610 /* Return false only if swap fails with an error */
1611 return (Thread::swap(&system_context, next) == 0);
1614 /** Runs the current execution until threre are no more steps to take. */
1615 void ModelChecker::finish_execution() {
1618 while (take_step());