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.
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 /* See if fairness allows */
279 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
281 for(int t=0;t<node->get_num_threads();t++) {
282 thread_id_t tother=int_to_id(t);
283 if (node->is_enabled(tother) && node->has_priority(tother)) {
292 /* Cache the latest backtracking point */
293 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
294 priv->next_backtrack = prev;
296 /* If this is a new backtracking point, mark the tree */
297 if (!node->set_backtrack(tid))
299 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
300 prev->get_tid(), t->get_id());
309 * Returns last backtracking point. The model checker will explore a different
310 * path for this point in the next execution.
311 * @return The ModelAction at which the next execution should diverge.
313 ModelAction * ModelChecker::get_next_backtrack()
315 ModelAction *next = priv->next_backtrack;
316 priv->next_backtrack = NULL;
321 * Processes a read or rmw model action.
322 * @param curr is the read model action to process.
323 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
324 * @return True if processing this read updates the mo_graph.
326 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
329 bool updated = false;
331 const ModelAction *reads_from = curr->get_node()->get_read_from();
332 if (reads_from != NULL) {
333 mo_graph->startChanges();
335 value = reads_from->get_value();
336 bool r_status = false;
338 if (!second_part_of_rmw) {
340 r_status = r_modification_order(curr, reads_from);
344 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
345 mo_graph->rollbackChanges();
346 too_many_reads = false;
350 curr->read_from(reads_from);
351 mo_graph->commitChanges();
353 } else if (!second_part_of_rmw) {
354 /* Read from future value */
355 value = curr->get_node()->get_future_value();
356 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
357 curr->read_from(NULL);
358 Promise *valuepromise = new Promise(curr, value, expiration);
359 promises->push_back(valuepromise);
361 get_thread(curr)->set_return_value(value);
367 * Processes a lock, trylock, or unlock model action. @param curr is
368 * the read model action to process.
370 * The try lock operation checks whether the lock is taken. If not,
371 * it falls to the normal lock operation case. If so, it returns
374 * The lock operation has already been checked that it is enabled, so
375 * it just grabs the lock and synchronizes with the previous unlock.
377 * The unlock operation has to re-enable all of the threads that are
378 * waiting on the lock.
380 void 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
403 curr->synchronize_with(unlock);
406 case ATOMIC_UNLOCK: {
408 state->islocked = false;
409 //wake up the other threads
410 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
411 //activate all the waiting threads
412 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
413 scheduler->add_thread(get_thread((*rit)->get_tid()));
424 * Process a write ModelAction
425 * @param curr The ModelAction to process
426 * @return True if the mo_graph was updated or promises were resolved
428 bool ModelChecker::process_write(ModelAction *curr)
430 bool updated_mod_order = w_modification_order(curr);
431 bool updated_promises = resolve_promises(curr);
433 if (promises->size() == 0) {
434 for (unsigned int i = 0; i < futurevalues->size(); i++) {
435 struct PendingFutureValue pfv = (*futurevalues)[i];
436 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
437 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
438 priv->next_backtrack = pfv.act;
440 futurevalues->resize(0);
443 mo_graph->commitChanges();
444 get_thread(curr)->set_return_value(VALUE_NONE);
445 return updated_mod_order || updated_promises;
449 * @brief Process the current action for thread-related activity
451 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
452 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
453 * synchronization, etc. This function is a no-op for non-THREAD actions
454 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
456 * @param curr The current action
457 * @return True if synchronization was updated
459 bool ModelChecker::process_thread_action(ModelAction *curr)
461 bool synchronized = false;
463 switch (curr->get_type()) {
464 case THREAD_CREATE: {
465 Thread *th = (Thread *)curr->get_location();
466 th->set_creation(curr);
470 Thread *waiting, *blocking;
471 waiting = get_thread(curr);
472 blocking = (Thread *)curr->get_location();
473 if (!blocking->is_complete()) {
474 blocking->push_wait_list(curr);
475 scheduler->sleep(waiting);
477 do_complete_join(curr);
482 case THREAD_FINISH: {
483 Thread *th = get_thread(curr);
484 while (!th->wait_list_empty()) {
485 ModelAction *act = th->pop_wait_list();
486 Thread *wake = get_thread(act);
487 scheduler->wake(wake);
488 do_complete_join(act);
495 check_promises(NULL, curr->get_cv());
506 * Initialize the current action by performing one or more of the following
507 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
508 * in the NodeStack, manipulating backtracking sets, allocating and
509 * initializing clock vectors, and computing the promises to fulfill.
511 * @param curr The current action, as passed from the user context; may be
512 * freed/invalidated after the execution of this function
513 * @return The current action, as processed by the ModelChecker. Is only the
514 * same as the parameter @a curr if this is a newly-explored action.
516 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
518 ModelAction *newcurr;
520 if (curr->is_rmwc() || curr->is_rmw()) {
521 newcurr = process_rmw(curr);
523 compute_promises(newcurr);
527 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
529 /* First restore type and order in case of RMW operation */
531 newcurr->copy_typeandorder(curr);
533 ASSERT(curr->get_location() == newcurr->get_location());
534 newcurr->copy_from_new(curr);
536 /* Discard duplicate ModelAction; use action from NodeStack */
539 /* If we have diverged, we need to reset the clock vector. */
541 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
545 * Perform one-time actions when pushing new ModelAction onto
548 curr->create_cv(get_parent_action(curr->get_tid()));
549 if (curr->is_write())
550 compute_promises(curr);
556 * This method checks whether a model action is enabled at the given point.
557 * At this point, it checks whether a lock operation would be successful at this point.
558 * If not, it puts the thread in a waiter list.
559 * @param curr is the ModelAction to check whether it is enabled.
560 * @return a bool that indicates whether the action is enabled.
563 bool ModelChecker::check_action_enabled(ModelAction *curr) {
564 if (curr->is_lock()) {
565 std::mutex * lock = (std::mutex *)curr->get_location();
566 struct std::mutex_state * state = lock->get_state();
567 if (state->islocked) {
568 //Stick the action in the appropriate waiting queue
569 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
578 * This is the heart of the model checker routine. It performs model-checking
579 * actions corresponding to a given "current action." Among other processes, it
580 * calculates reads-from relationships, updates synchronization clock vectors,
581 * forms a memory_order constraints graph, and handles replay/backtrack
582 * execution when running permutations of previously-observed executions.
584 * @param curr The current action to process
585 * @return The next Thread that must be executed. May be NULL if ModelChecker
586 * makes no choice (e.g., according to replay execution, combining RMW actions,
589 Thread * ModelChecker::check_current_action(ModelAction *curr)
593 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
595 if (!check_action_enabled(curr)) {
596 //we'll make the execution look like we chose to run this action
597 //much later...when a lock is actually available to relese
598 get_current_thread()->set_pending(curr);
599 remove_thread(get_current_thread());
600 return get_next_thread(NULL);
603 ModelAction *newcurr = initialize_curr_action(curr);
605 /* Add the action to lists before any other model-checking tasks */
606 if (!second_part_of_rmw)
607 add_action_to_lists(newcurr);
609 /* Build may_read_from set for newly-created actions */
610 if (curr == newcurr && curr->is_read())
611 build_reads_from_past(curr);
614 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
616 while (!work_queue.empty()) {
617 WorkQueueEntry work = work_queue.front();
618 work_queue.pop_front();
621 case WORK_CHECK_CURR_ACTION: {
622 ModelAction *act = work.action;
623 bool updated = false;
625 process_thread_action(curr);
627 if (act->is_read() && process_read(act, second_part_of_rmw))
630 if (act->is_write() && process_write(act))
633 if (act->is_mutex_op())
637 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
640 case WORK_CHECK_RELEASE_SEQ:
641 resolve_release_sequences(work.location, &work_queue);
643 case WORK_CHECK_MO_EDGES: {
644 /** @todo Complete verification of work_queue */
645 ModelAction *act = work.action;
646 bool updated = false;
648 if (act->is_read()) {
649 if (r_modification_order(act, act->get_reads_from()))
652 if (act->is_write()) {
653 if (w_modification_order(act))
658 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
667 check_curr_backtracking(curr);
669 set_backtracking(curr);
671 return get_next_thread(curr);
675 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
676 * operation from the Thread it is joining with. Must be called after the
677 * completion of the Thread in question.
678 * @param join The THREAD_JOIN action
680 void ModelChecker::do_complete_join(ModelAction *join)
682 Thread *blocking = (Thread *)join->get_location();
683 ModelAction *act = get_last_action(blocking->get_id());
684 join->synchronize_with(act);
687 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
688 Node *currnode = curr->get_node();
689 Node *parnode = currnode->get_parent();
691 if ((!parnode->backtrack_empty() ||
692 !currnode->read_from_empty() ||
693 !currnode->future_value_empty() ||
694 !currnode->promise_empty())
695 && (!priv->next_backtrack ||
696 *curr > *priv->next_backtrack)) {
697 priv->next_backtrack = curr;
701 bool ModelChecker::promises_expired() {
702 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
703 Promise *promise = (*promises)[promise_index];
704 if (promise->get_expiration()<priv->used_sequence_numbers) {
711 /** @return whether the current partial trace must be a prefix of a
713 bool ModelChecker::isfeasibleprefix() {
714 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
717 /** @return whether the current partial trace is feasible. */
718 bool ModelChecker::isfeasible() {
719 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
722 /** @return whether the current partial trace is feasible other than
723 * multiple RMW reading from the same store. */
724 bool ModelChecker::isfeasibleotherthanRMW() {
726 if (mo_graph->checkForCycles())
727 DEBUG("Infeasible: modification order cycles\n");
729 DEBUG("Infeasible: failed promise\n");
731 DEBUG("Infeasible: too many reads\n");
732 if (promises_expired())
733 DEBUG("Infeasible: promises expired\n");
735 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
738 /** Returns whether the current completed trace is feasible. */
739 bool ModelChecker::isfinalfeasible() {
740 if (DBG_ENABLED() && promises->size() != 0)
741 DEBUG("Infeasible: unrevolved promises\n");
743 return isfeasible() && promises->size() == 0;
746 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
747 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
748 int tid = id_to_int(act->get_tid());
749 ModelAction *lastread = get_last_action(tid);
750 lastread->process_rmw(act);
751 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
752 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
753 mo_graph->commitChanges();
759 * Checks whether a thread has read from the same write for too many times
760 * without seeing the effects of a later write.
763 * 1) there must a different write that we could read from that would satisfy the modification order,
764 * 2) we must have read from the same value in excess of maxreads times, and
765 * 3) that other write must have been in the reads_from set for maxreads times.
767 * If so, we decide that the execution is no longer feasible.
769 void ModelChecker::check_recency(ModelAction *curr) {
770 if (params.maxreads != 0) {
771 if (curr->get_node()->get_read_from_size() <= 1)
774 //Must make sure that execution is currently feasible... We could
775 //accidentally clear by rolling back
779 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
780 int tid = id_to_int(curr->get_tid());
783 if ((int)thrd_lists->size() <= tid)
786 action_list_t *list = &(*thrd_lists)[tid];
788 action_list_t::reverse_iterator rit = list->rbegin();
790 for (; (*rit) != curr; rit++)
792 /* go past curr now */
795 action_list_t::reverse_iterator ritcopy = rit;
796 //See if we have enough reads from the same value
798 for (; count < params.maxreads; rit++,count++) {
799 if (rit==list->rend())
801 ModelAction *act = *rit;
804 if (act->get_reads_from() != curr->get_reads_from())
806 if (act->get_node()->get_read_from_size() <= 1)
810 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
812 const ModelAction * write = curr->get_node()->get_read_from_at(i);
813 //Need a different write
814 if (write==curr->get_reads_from())
817 /* Test to see whether this is a feasible write to read from*/
818 mo_graph->startChanges();
819 r_modification_order(curr, write);
820 bool feasiblereadfrom = isfeasible();
821 mo_graph->rollbackChanges();
823 if (!feasiblereadfrom)
827 bool feasiblewrite = true;
828 //new we need to see if this write works for everyone
830 for (int loop = count; loop>0; loop--,rit++) {
831 ModelAction *act=*rit;
832 bool foundvalue = false;
833 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
834 if (act->get_node()->get_read_from_at(i)==write) {
840 feasiblewrite = false;
845 too_many_reads = true;
853 * Updates the mo_graph with the constraints imposed from the current
856 * Basic idea is the following: Go through each other thread and find
857 * the lastest action that happened before our read. Two cases:
859 * (1) The action is a write => that write must either occur before
860 * the write we read from or be the write we read from.
862 * (2) The action is a read => the write that that action read from
863 * must occur before the write we read from or be the same write.
865 * @param curr The current action. Must be a read.
866 * @param rf The action that curr reads from. Must be a write.
867 * @return True if modification order edges were added; false otherwise
869 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
871 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
874 ASSERT(curr->is_read());
876 /* Iterate over all threads */
877 for (i = 0; i < thrd_lists->size(); i++) {
878 /* Iterate over actions in thread, starting from most recent */
879 action_list_t *list = &(*thrd_lists)[i];
880 action_list_t::reverse_iterator rit;
881 for (rit = list->rbegin(); rit != list->rend(); rit++) {
882 ModelAction *act = *rit;
885 * Include at most one act per-thread that "happens
886 * before" curr. Don't consider reflexively.
888 if (act->happens_before(curr) && act != curr) {
889 if (act->is_write()) {
891 mo_graph->addEdge(act, rf);
895 const ModelAction *prevreadfrom = act->get_reads_from();
896 if (prevreadfrom != NULL && rf != prevreadfrom) {
897 mo_graph->addEdge(prevreadfrom, rf);
909 /** This method fixes up the modification order when we resolve a
910 * promises. The basic problem is that actions that occur after the
911 * read curr could not property add items to the modification order
914 * So for each thread, we find the earliest item that happens after
915 * the read curr. This is the item we have to fix up with additional
916 * constraints. If that action is write, we add a MO edge between
917 * the Action rf and that action. If the action is a read, we add a
918 * MO edge between the Action rf, and whatever the read accessed.
920 * @param curr is the read ModelAction that we are fixing up MO edges for.
921 * @param rf is the write ModelAction that curr reads from.
925 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
927 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
929 ASSERT(curr->is_read());
931 /* Iterate over all threads */
932 for (i = 0; i < thrd_lists->size(); i++) {
933 /* Iterate over actions in thread, starting from most recent */
934 action_list_t *list = &(*thrd_lists)[i];
935 action_list_t::reverse_iterator rit;
936 ModelAction *lastact = NULL;
938 /* Find last action that happens after curr */
939 for (rit = list->rbegin(); rit != list->rend(); rit++) {
940 ModelAction *act = *rit;
941 if (curr->happens_before(act)) {
947 /* Include at most one act per-thread that "happens before" curr */
948 if (lastact != NULL) {
949 if (lastact->is_read()) {
950 const ModelAction *postreadfrom = lastact->get_reads_from();
951 if (postreadfrom != NULL&&rf != postreadfrom)
952 mo_graph->addEdge(rf, postreadfrom);
953 } else if (rf != lastact) {
954 mo_graph->addEdge(rf, lastact);
962 * Updates the mo_graph with the constraints imposed from the current write.
964 * Basic idea is the following: Go through each other thread and find
965 * the lastest action that happened before our write. Two cases:
967 * (1) The action is a write => that write must occur before
970 * (2) The action is a read => the write that that action read from
971 * must occur before the current write.
973 * This method also handles two other issues:
975 * (I) Sequential Consistency: Making sure that if the current write is
976 * seq_cst, that it occurs after the previous seq_cst write.
978 * (II) Sending the write back to non-synchronizing reads.
980 * @param curr The current action. Must be a write.
981 * @return True if modification order edges were added; false otherwise
983 bool ModelChecker::w_modification_order(ModelAction *curr)
985 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
988 ASSERT(curr->is_write());
990 if (curr->is_seqcst()) {
991 /* We have to at least see the last sequentially consistent write,
992 so we are initialized. */
993 ModelAction *last_seq_cst = get_last_seq_cst(curr);
994 if (last_seq_cst != NULL) {
995 mo_graph->addEdge(last_seq_cst, curr);
1000 /* Iterate over all threads */
1001 for (i = 0; i < thrd_lists->size(); i++) {
1002 /* Iterate over actions in thread, starting from most recent */
1003 action_list_t *list = &(*thrd_lists)[i];
1004 action_list_t::reverse_iterator rit;
1005 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1006 ModelAction *act = *rit;
1009 * If RMW, we already have all relevant edges,
1010 * so just skip to next thread.
1011 * If normal write, we need to look at earlier
1012 * actions, so continue processing list.
1021 * Include at most one act per-thread that "happens
1024 if (act->happens_before(curr)) {
1026 * Note: if act is RMW, just add edge:
1028 * The following edge should be handled elsewhere:
1029 * readfrom(act) --mo--> act
1031 if (act->is_write())
1032 mo_graph->addEdge(act, curr);
1033 else if (act->is_read() && act->get_reads_from() != NULL)
1034 mo_graph->addEdge(act->get_reads_from(), curr);
1037 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1038 !act->same_thread(curr)) {
1039 /* We have an action that:
1040 (1) did not happen before us
1041 (2) is a read and we are a write
1042 (3) cannot synchronize with us
1043 (4) is in a different thread
1045 that read could potentially read from our write.
1047 if (thin_air_constraint_may_allow(curr, act)) {
1049 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1050 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1051 futurevalues->push_back(pfv);
1061 /** Arbitrary reads from the future are not allowed. Section 29.3
1062 * part 9 places some constraints. This method checks one result of constraint
1063 * constraint. Others require compiler support. */
1065 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1066 if (!writer->is_rmw())
1069 if (!reader->is_rmw())
1072 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1073 if (search == reader)
1075 if (search->get_tid() == reader->get_tid() &&
1076 search->happens_before(reader))
1084 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1085 * The ModelAction under consideration is expected to be taking part in
1086 * release/acquire synchronization as an object of the "reads from" relation.
1087 * Note that this can only provide release sequence support for RMW chains
1088 * which do not read from the future, as those actions cannot be traced until
1089 * their "promise" is fulfilled. Similarly, we may not even establish the
1090 * presence of a release sequence with certainty, as some modification order
1091 * constraints may be decided further in the future. Thus, this function
1092 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1093 * and a boolean representing certainty.
1095 * @todo Finish lazy updating, when promises are fulfilled in the future
1096 * @param rf The action that might be part of a release sequence. Must be a
1098 * @param release_heads A pass-by-reference style return parameter. After
1099 * execution of this function, release_heads will contain the heads of all the
1100 * relevant release sequences, if any exists
1101 * @return true, if the ModelChecker is certain that release_heads is complete;
1104 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1107 ASSERT(rf->is_write());
1109 if (rf->is_release())
1110 release_heads->push_back(rf);
1112 break; /* End of RMW chain */
1114 /** @todo Need to be smarter here... In the linux lock
1115 * example, this will run to the beginning of the program for
1117 /** @todo The way to be smarter here is to keep going until 1
1118 * thread has a release preceded by an acquire and you've seen
1121 /* acq_rel RMW is a sufficient stopping condition */
1122 if (rf->is_acquire() && rf->is_release())
1123 return true; /* complete */
1125 rf = rf->get_reads_from();
1128 /* read from future: need to settle this later */
1129 return false; /* incomplete */
1132 if (rf->is_release())
1133 return true; /* complete */
1135 /* else relaxed write; check modification order for contiguous subsequence
1136 * -> rf must be same thread as release */
1137 int tid = id_to_int(rf->get_tid());
1138 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1139 action_list_t *list = &(*thrd_lists)[tid];
1140 action_list_t::const_reverse_iterator rit;
1142 /* Find rf in the thread list */
1143 rit = std::find(list->rbegin(), list->rend(), rf);
1144 ASSERT(rit != list->rend());
1146 /* Find the last write/release */
1147 for (; rit != list->rend(); rit++)
1148 if ((*rit)->is_release())
1150 if (rit == list->rend()) {
1151 /* No write-release in this thread */
1152 return true; /* complete */
1154 ModelAction *release = *rit;
1156 ASSERT(rf->same_thread(release));
1158 bool certain = true;
1159 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1160 if (id_to_int(rf->get_tid()) == (int)i)
1162 list = &(*thrd_lists)[i];
1164 /* Can we ensure no future writes from this thread may break
1165 * the release seq? */
1166 bool future_ordered = false;
1168 ModelAction *last = get_last_action(int_to_id(i));
1169 if (last && rf->happens_before(last))
1170 future_ordered = true;
1172 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1173 const ModelAction *act = *rit;
1174 /* Reach synchronization -> this thread is complete */
1175 if (act->happens_before(release))
1177 if (rf->happens_before(act)) {
1178 future_ordered = true;
1182 /* Only writes can break release sequences */
1183 if (!act->is_write())
1186 /* Check modification order */
1187 if (mo_graph->checkReachable(rf, act)) {
1188 /* rf --mo--> act */
1189 future_ordered = true;
1192 if (mo_graph->checkReachable(act, release))
1193 /* act --mo--> release */
1195 if (mo_graph->checkReachable(release, act) &&
1196 mo_graph->checkReachable(act, rf)) {
1197 /* release --mo-> act --mo--> rf */
1198 return true; /* complete */
1202 if (!future_ordered)
1203 return false; /* This thread is uncertain */
1207 release_heads->push_back(release);
1212 * A public interface for getting the release sequence head(s) with which a
1213 * given ModelAction must synchronize. This function only returns a non-empty
1214 * result when it can locate a release sequence head with certainty. Otherwise,
1215 * it may mark the internal state of the ModelChecker so that it will handle
1216 * the release sequence at a later time, causing @a act to update its
1217 * synchronization at some later point in execution.
1218 * @param act The 'acquire' action that may read from a release sequence
1219 * @param release_heads A pass-by-reference return parameter. Will be filled
1220 * with the head(s) of the release sequence(s), if they exists with certainty.
1221 * @see ModelChecker::release_seq_head
1223 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1225 const ModelAction *rf = act->get_reads_from();
1227 complete = release_seq_head(rf, release_heads);
1229 /* add act to 'lazy checking' list */
1230 pending_acq_rel_seq->push_back(act);
1235 * Attempt to resolve all stashed operations that might synchronize with a
1236 * release sequence for a given location. This implements the "lazy" portion of
1237 * determining whether or not a release sequence was contiguous, since not all
1238 * modification order information is present at the time an action occurs.
1240 * @param location The location/object that should be checked for release
1241 * sequence resolutions. A NULL value means to check all locations.
1242 * @param work_queue The work queue to which to add work items as they are
1244 * @return True if any updates occurred (new synchronization, new mo_graph
1247 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1249 bool updated = false;
1250 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1251 while (it != pending_acq_rel_seq->end()) {
1252 ModelAction *act = *it;
1254 /* Only resolve sequences on the given location, if provided */
1255 if (location && act->get_location() != location) {
1260 const ModelAction *rf = act->get_reads_from();
1261 rel_heads_list_t release_heads;
1263 complete = release_seq_head(rf, &release_heads);
1264 for (unsigned int i = 0; i < release_heads.size(); i++) {
1265 if (!act->has_synchronized_with(release_heads[i])) {
1267 act->synchronize_with(release_heads[i]);
1272 /* Re-check act for mo_graph edges */
1273 work_queue->push_back(MOEdgeWorkEntry(act));
1275 /* propagate synchronization to later actions */
1276 action_list_t::reverse_iterator it = action_trace->rbegin();
1277 for (; (*it) != act; it++) {
1278 ModelAction *propagate = *it;
1279 if (act->happens_before(propagate)) {
1280 propagate->synchronize_with(act);
1281 /* Re-check 'propagate' for mo_graph edges */
1282 work_queue->push_back(MOEdgeWorkEntry(propagate));
1287 it = pending_acq_rel_seq->erase(it);
1292 // If we resolved promises or data races, see if we have realized a data race.
1293 if (checkDataRaces()) {
1301 * Performs various bookkeeping operations for the current ModelAction. For
1302 * instance, adds action to the per-object, per-thread action vector and to the
1303 * action trace list of all thread actions.
1305 * @param act is the ModelAction to add.
1307 void ModelChecker::add_action_to_lists(ModelAction *act)
1309 int tid = id_to_int(act->get_tid());
1310 action_trace->push_back(act);
1312 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1314 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1315 if (tid >= (int)vec->size())
1316 vec->resize(priv->next_thread_id);
1317 (*vec)[tid].push_back(act);
1319 if ((int)thrd_last_action->size() <= tid)
1320 thrd_last_action->resize(get_num_threads());
1321 (*thrd_last_action)[tid] = act;
1325 * @brief Get the last action performed by a particular Thread
1326 * @param tid The thread ID of the Thread in question
1327 * @return The last action in the thread
1329 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1331 int threadid = id_to_int(tid);
1332 if (threadid < (int)thrd_last_action->size())
1333 return (*thrd_last_action)[id_to_int(tid)];
1339 * Gets the last memory_order_seq_cst write (in the total global sequence)
1340 * performed on a particular object (i.e., memory location), not including the
1342 * @param curr The current ModelAction; also denotes the object location to
1344 * @return The last seq_cst write
1346 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1348 void *location = curr->get_location();
1349 action_list_t *list = obj_map->get_safe_ptr(location);
1350 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1351 action_list_t::reverse_iterator rit;
1352 for (rit = list->rbegin(); rit != list->rend(); rit++)
1353 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1359 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1360 * location). This function identifies the mutex according to the current
1361 * action, which is presumed to perform on the same mutex.
1362 * @param curr The current ModelAction; also denotes the object location to
1364 * @return The last unlock operation
1366 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1368 void *location = curr->get_location();
1369 action_list_t *list = obj_map->get_safe_ptr(location);
1370 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1371 action_list_t::reverse_iterator rit;
1372 for (rit = list->rbegin(); rit != list->rend(); rit++)
1373 if ((*rit)->is_unlock())
1378 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1380 ModelAction *parent = get_last_action(tid);
1382 parent = get_thread(tid)->get_creation();
1387 * Returns the clock vector for a given thread.
1388 * @param tid The thread whose clock vector we want
1389 * @return Desired clock vector
1391 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1393 return get_parent_action(tid)->get_cv();
1397 * Resolve a set of Promises with a current write. The set is provided in the
1398 * Node corresponding to @a write.
1399 * @param write The ModelAction that is fulfilling Promises
1400 * @return True if promises were resolved; false otherwise
1402 bool ModelChecker::resolve_promises(ModelAction *write)
1404 bool resolved = false;
1406 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1407 Promise *promise = (*promises)[promise_index];
1408 if (write->get_node()->get_promise(i)) {
1409 ModelAction *read = promise->get_action();
1410 read->read_from(write);
1411 if (read->is_rmw()) {
1412 mo_graph->addRMWEdge(write, read);
1414 //First fix up the modification order for actions that happened
1416 r_modification_order(read, write);
1417 //Next fix up the modification order for actions that happened
1419 post_r_modification_order(read, write);
1420 promises->erase(promises->begin() + promise_index);
1429 * Compute the set of promises that could potentially be satisfied by this
1430 * action. Note that the set computation actually appears in the Node, not in
1432 * @param curr The ModelAction that may satisfy promises
1434 void ModelChecker::compute_promises(ModelAction *curr)
1436 for (unsigned int i = 0; i < promises->size(); i++) {
1437 Promise *promise = (*promises)[i];
1438 const ModelAction *act = promise->get_action();
1439 if (!act->happens_before(curr) &&
1441 !act->is_synchronizing(curr) &&
1442 !act->same_thread(curr) &&
1443 promise->get_value() == curr->get_value()) {
1444 curr->get_node()->set_promise(i);
1449 /** Checks promises in response to change in ClockVector Threads. */
1450 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1452 for (unsigned int i = 0; i < promises->size(); i++) {
1453 Promise *promise = (*promises)[i];
1454 const ModelAction *act = promise->get_action();
1455 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1456 merge_cv->synchronized_since(act)) {
1457 //This thread is no longer able to send values back to satisfy the promise
1458 int num_synchronized_threads = promise->increment_threads();
1459 if (num_synchronized_threads == get_num_threads()) {
1460 //Promise has failed
1461 failed_promise = true;
1469 * Build up an initial set of all past writes that this 'read' action may read
1470 * from. This set is determined by the clock vector's "happens before"
1472 * @param curr is the current ModelAction that we are exploring; it must be a
1475 void ModelChecker::build_reads_from_past(ModelAction *curr)
1477 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1479 ASSERT(curr->is_read());
1481 ModelAction *last_seq_cst = NULL;
1483 /* Track whether this object has been initialized */
1484 bool initialized = false;
1486 if (curr->is_seqcst()) {
1487 last_seq_cst = get_last_seq_cst(curr);
1488 /* We have to at least see the last sequentially consistent write,
1489 so we are initialized. */
1490 if (last_seq_cst != NULL)
1494 /* Iterate over all threads */
1495 for (i = 0; i < thrd_lists->size(); i++) {
1496 /* Iterate over actions in thread, starting from most recent */
1497 action_list_t *list = &(*thrd_lists)[i];
1498 action_list_t::reverse_iterator rit;
1499 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1500 ModelAction *act = *rit;
1502 /* Only consider 'write' actions */
1503 if (!act->is_write() || act == curr)
1506 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1507 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1508 DEBUG("Adding action to may_read_from:\n");
1509 if (DBG_ENABLED()) {
1513 curr->get_node()->add_read_from(act);
1516 /* Include at most one act per-thread that "happens before" curr */
1517 if (act->happens_before(curr)) {
1525 /** @todo Need a more informative way of reporting errors. */
1526 printf("ERROR: may read from uninitialized atomic\n");
1529 if (DBG_ENABLED() || !initialized) {
1530 printf("Reached read action:\n");
1532 printf("Printing may_read_from\n");
1533 curr->get_node()->print_may_read_from();
1534 printf("End printing may_read_from\n");
1537 ASSERT(initialized);
1540 static void print_list(action_list_t *list)
1542 action_list_t::iterator it;
1544 printf("---------------------------------------------------------------------\n");
1547 for (it = list->begin(); it != list->end(); it++) {
1550 printf("---------------------------------------------------------------------\n");
1553 void ModelChecker::print_summary()
1556 printf("Number of executions: %d\n", num_executions);
1557 printf("Number of feasible executions: %d\n", num_feasible_executions);
1558 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1560 #if SUPPORT_MOD_ORDER_DUMP
1562 char buffername[100];
1563 sprintf(buffername, "exec%04u", num_executions);
1564 mo_graph->dumpGraphToFile(buffername);
1567 if (!isfinalfeasible())
1568 printf("INFEASIBLE EXECUTION!\n");
1569 print_list(action_trace);
1574 * Add a Thread to the system for the first time. Should only be called once
1576 * @param t The Thread to add
1578 void ModelChecker::add_thread(Thread *t)
1580 thread_map->put(id_to_int(t->get_id()), t);
1581 scheduler->add_thread(t);
1585 * Removes a thread from the scheduler.
1586 * @param the thread to remove.
1589 void ModelChecker::remove_thread(Thread *t)
1591 scheduler->remove_thread(t);
1595 * Switch from a user-context to the "master thread" context (a.k.a. system
1596 * context). This switch is made with the intention of exploring a particular
1597 * model-checking action (described by a ModelAction object). Must be called
1598 * from a user-thread context.
1599 * @param act The current action that will be explored. Must not be NULL.
1600 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1602 int ModelChecker::switch_to_master(ModelAction *act)
1605 Thread *old = thread_current();
1606 set_current_action(act);
1607 old->set_state(THREAD_READY);
1608 return Thread::swap(old, &system_context);
1612 * Takes the next step in the execution, if possible.
1613 * @return Returns true (success) if a step was taken and false otherwise.
1615 bool ModelChecker::take_step() {
1619 Thread * curr = thread_current();
1621 if (curr->get_state() == THREAD_READY) {
1622 ASSERT(priv->current_action);
1624 priv->nextThread = check_current_action(priv->current_action);
1625 priv->current_action = NULL;
1626 if (curr->is_blocked() || curr->is_complete())
1627 scheduler->remove_thread(curr);
1632 Thread * next = scheduler->next_thread(priv->nextThread);
1634 /* Infeasible -> don't take any more steps */
1639 next->set_state(THREAD_RUNNING);
1640 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1642 /* next == NULL -> don't take any more steps */
1646 if ( next->get_pending() != NULL ) {
1647 //restart a pending action
1648 set_current_action(next->get_pending());
1649 next->set_pending(NULL);
1650 next->set_state(THREAD_READY);
1654 /* Return false only if swap fails with an error */
1655 return (Thread::swap(&system_context, next) == 0);
1658 /** Runs the current execution until threre are no more steps to take. */
1659 void ModelChecker::finish_execution() {
1662 while (take_step());