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 lazy_sync_with_release(new HashTable<void *, action_list_t, uintptr_t, 4>()),
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;
48 lazy_sync_size = &priv->lazy_sync_size;
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
54 for (int i = 0; i < get_num_threads(); i++)
55 delete thread_map->get(i);
60 delete lock_waiters_map;
63 for (unsigned int i = 0; i < promises->size(); i++)
64 delete (*promises)[i];
67 delete lazy_sync_with_release;
69 delete thrd_last_action;
76 * Restores user program to initial state and resets all model-checker data
79 void ModelChecker::reset_to_initial_state()
81 DEBUG("+++ Resetting to initial state +++\n");
82 node_stack->reset_execution();
83 failed_promise = false;
84 too_many_reads = false;
86 snapshotObject->backTrackBeforeStep(0);
89 /** @returns a thread ID for a new Thread */
90 thread_id_t ModelChecker::get_next_id()
92 return priv->next_thread_id++;
95 /** @returns the number of user threads created during this execution */
96 int ModelChecker::get_num_threads()
98 return priv->next_thread_id;
101 /** @returns a sequence number for a new ModelAction */
102 modelclock_t ModelChecker::get_next_seq_num()
104 return ++priv->used_sequence_numbers;
108 * @brief Choose the next thread to execute.
110 * This function chooses the next thread that should execute. It can force the
111 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
112 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
113 * The model-checker may have no preference regarding the next thread (i.e.,
114 * when exploring a new execution ordering), in which case this will return
116 * @param curr The current ModelAction. This action might guide the choice of
118 * @return The next thread to run. If the model-checker has no preference, NULL.
120 Thread * ModelChecker::get_next_thread(ModelAction *curr)
125 /* Do not split atomic actions. */
127 return thread_current();
128 /* The THREAD_CREATE action points to the created Thread */
129 else if (curr->get_type() == THREAD_CREATE)
130 return (Thread *)curr->get_location();
133 /* Have we completed exploring the preselected path? */
137 /* Else, we are trying to replay an execution */
138 ModelAction *next = node_stack->get_next()->get_action();
140 if (next == diverge) {
141 Node *nextnode = next->get_node();
142 /* Reached divergence point */
143 if (nextnode->increment_promise()) {
144 /* The next node will try to satisfy a different set of promises. */
145 tid = next->get_tid();
146 node_stack->pop_restofstack(2);
147 } else if (nextnode->increment_read_from()) {
148 /* The next node will read from a different value. */
149 tid = next->get_tid();
150 node_stack->pop_restofstack(2);
151 } else if (nextnode->increment_future_value()) {
152 /* The next node will try to read from a different future value. */
153 tid = next->get_tid();
154 node_stack->pop_restofstack(2);
156 /* Make a different thread execute for next step */
157 Node *node = nextnode->get_parent();
158 tid = node->get_next_backtrack();
159 node_stack->pop_restofstack(1);
161 DEBUG("*** Divergence point ***\n");
164 tid = next->get_tid();
166 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
167 ASSERT(tid != THREAD_ID_T_NONE);
168 return thread_map->get(id_to_int(tid));
172 * Queries the model-checker for more executions to explore and, if one
173 * exists, resets the model-checker state to execute a new execution.
175 * @return If there are more executions to explore, return true. Otherwise,
178 bool ModelChecker::next_execution()
183 if (isfinalfeasible())
184 num_feasible_executions++;
186 if (isfinalfeasible() || DBG_ENABLED())
189 if ((diverge = get_next_backtrack()) == NULL)
193 printf("Next execution will diverge at:\n");
197 reset_to_initial_state();
201 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
203 action_type type = act->get_type();
205 if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
206 /* linear search: from most recent to oldest */
207 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
208 action_list_t::reverse_iterator rit;
209 for (rit = list->rbegin(); rit != list->rend(); rit++) {
210 ModelAction *prev = *rit;
211 if (act->is_synchronizing(prev))
214 } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
215 /* linear search: from most recent to oldest */
216 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
217 action_list_t::reverse_iterator rit;
218 for (rit = list->rbegin(); rit != list->rend(); rit++) {
219 ModelAction *prev = *rit;
220 if (prev->is_success_lock())
223 } else if (type==ATOMIC_UNLOCK) {
224 /* linear search: from most recent to oldest */
225 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
226 action_list_t::reverse_iterator rit;
227 for (rit = list->rbegin(); rit != list->rend(); rit++) {
228 ModelAction *prev = *rit;
229 if (prev->is_failed_trylock())
236 void ModelChecker::set_backtracking(ModelAction *act)
240 Thread *t = get_thread(act);
242 prev = get_last_conflict(act);
246 node = prev->get_node()->get_parent();
248 while (!node->is_enabled(t))
251 /* Check if this has been explored already */
252 if (node->has_been_explored(t->get_id()))
255 /* Cache the latest backtracking point */
256 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
257 priv->next_backtrack = prev;
259 /* If this is a new backtracking point, mark the tree */
260 if (!node->set_backtrack(t->get_id()))
262 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
263 prev->get_tid(), t->get_id());
271 * Returns last backtracking point. The model checker will explore a different
272 * path for this point in the next execution.
273 * @return The ModelAction at which the next execution should diverge.
275 ModelAction * ModelChecker::get_next_backtrack()
277 ModelAction *next = priv->next_backtrack;
278 priv->next_backtrack = NULL;
283 * Processes a read or rmw model action.
284 * @param curr is the read model action to process.
285 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
286 * @return True if processing this read updates the mo_graph.
288 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
291 bool updated = false;
293 const ModelAction *reads_from = curr->get_node()->get_read_from();
294 if (reads_from != NULL) {
295 mo_graph->startChanges();
297 value = reads_from->get_value();
298 bool r_status = false;
300 if (!second_part_of_rmw) {
302 r_status = r_modification_order(curr, reads_from);
306 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
307 mo_graph->rollbackChanges();
308 too_many_reads = false;
312 curr->read_from(reads_from);
313 mo_graph->commitChanges();
315 } else if (!second_part_of_rmw) {
316 /* Read from future value */
317 value = curr->get_node()->get_future_value();
318 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
319 curr->read_from(NULL);
320 Promise *valuepromise = new Promise(curr, value, expiration);
321 promises->push_back(valuepromise);
323 get_thread(curr)->set_return_value(value);
328 void ModelChecker::process_mutex(ModelAction *curr) {
329 std::mutex * mutex=(std::mutex *) curr->get_location();
330 struct std::mutex_state * state=mutex->get_state();
331 switch(curr->get_type()) {
332 case ATOMIC_TRYLOCK: {
333 bool success=!state->islocked;
334 curr->set_try_lock(success);
336 get_thread(curr)->set_return_value(0);
339 get_thread(curr)->set_return_value(1);
341 //otherwise fall into the lock case
343 if (curr->get_cv()->getClock(state->alloc_tid)<=state->alloc_clock) {
344 printf("Lock access before initialization\n");
347 state->islocked=true;
348 ModelAction *unlock=get_last_unlock(curr);
349 //synchronize with the previous unlock statement
350 if ( unlock != NULL )
351 curr->synchronize_with(unlock);
354 case ATOMIC_UNLOCK: {
356 state->islocked=false;
357 //wake up the other threads
358 action_list_t * waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
359 //activate all the waiting threads
360 for(action_list_t::iterator rit = waiters->begin(); rit!=waiters->end(); rit++) {
361 add_thread(get_thread((*rit)->get_tid()));
373 * Process a write ModelAction
374 * @param curr The ModelAction to process
375 * @return True if the mo_graph was updated or promises were resolved
377 bool ModelChecker::process_write(ModelAction *curr)
379 bool updated_mod_order = w_modification_order(curr);
380 bool updated_promises = resolve_promises(curr);
382 if (promises->size() == 0) {
383 for (unsigned int i = 0; i<futurevalues->size(); i++) {
384 struct PendingFutureValue pfv = (*futurevalues)[i];
385 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
386 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
387 priv->next_backtrack = pfv.act;
389 futurevalues->resize(0);
392 mo_graph->commitChanges();
393 get_thread(curr)->set_return_value(VALUE_NONE);
394 return updated_mod_order || updated_promises;
398 * Initialize the current action by performing one or more of the following
399 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
400 * in the NodeStack, manipulating backtracking sets, allocating and
401 * initializing clock vectors, and computing the promises to fulfill.
403 * @param curr The current action, as passed from the user context; may be
404 * freed/invalidated after the execution of this function
405 * @return The current action, as processed by the ModelChecker. Is only the
406 * same as the parameter @a curr if this is a newly-explored action.
408 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
410 ModelAction *newcurr;
412 if (curr->is_rmwc() || curr->is_rmw()) {
413 newcurr = process_rmw(curr);
415 compute_promises(newcurr);
419 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
421 /* First restore type and order in case of RMW operation */
423 newcurr->copy_typeandorder(curr);
425 ASSERT(curr->get_location()==newcurr->get_location());
427 /* Discard duplicate ModelAction; use action from NodeStack */
430 /* If we have diverged, we need to reset the clock vector. */
432 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
436 * Perform one-time actions when pushing new ModelAction onto
439 curr->create_cv(get_parent_action(curr->get_tid()));
440 if (curr->is_write())
441 compute_promises(curr);
446 bool ModelChecker::check_action_enabled(ModelAction *curr) {
447 if (curr->is_lock()) {
448 std::mutex * lock=(std::mutex *) curr->get_location();
449 struct std::mutex_state * state = lock->get_state();
450 if (state->islocked) {
451 //Stick the action in the appropriate waiting queue
452 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
461 * This is the heart of the model checker routine. It performs model-checking
462 * actions corresponding to a given "current action." Among other processes, it
463 * calculates reads-from relationships, updates synchronization clock vectors,
464 * forms a memory_order constraints graph, and handles replay/backtrack
465 * execution when running permutations of previously-observed executions.
467 * @param curr The current action to process
468 * @return The next Thread that must be executed. May be NULL if ModelChecker
469 * makes no choice (e.g., according to replay execution, combining RMW actions,
472 Thread * ModelChecker::check_current_action(ModelAction *curr)
476 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
478 if (!check_action_enabled(curr)) {
479 //we'll make the execution look like we chose to run this action
480 //much later...when a lock is actually available to relese
481 get_current_thread()->set_pending(curr);
482 remove_thread(get_current_thread());
483 return get_next_thread(NULL);
486 ModelAction *newcurr = initialize_curr_action(curr);
488 /* Add the action to lists before any other model-checking tasks */
489 if (!second_part_of_rmw)
490 add_action_to_lists(newcurr);
492 /* Build may_read_from set for newly-created actions */
493 if (curr == newcurr && curr->is_read())
494 build_reads_from_past(curr);
497 /* Thread specific actions */
498 switch (curr->get_type()) {
499 case THREAD_CREATE: {
500 Thread *th = (Thread *)curr->get_location();
501 th->set_creation(curr);
505 Thread *waiting, *blocking;
506 waiting = get_thread(curr);
507 blocking = (Thread *)curr->get_location();
508 if (!blocking->is_complete()) {
509 blocking->push_wait_list(curr);
510 scheduler->sleep(waiting);
512 do_complete_join(curr);
516 case THREAD_FINISH: {
517 Thread *th = get_thread(curr);
518 while (!th->wait_list_empty()) {
519 ModelAction *act = th->pop_wait_list();
520 Thread *wake = get_thread(act);
521 scheduler->wake(wake);
522 do_complete_join(act);
528 check_promises(NULL, curr->get_cv());
535 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
537 while (!work_queue.empty()) {
538 WorkQueueEntry work = work_queue.front();
539 work_queue.pop_front();
542 case WORK_CHECK_CURR_ACTION: {
543 ModelAction *act = work.action;
544 bool updated = false;
545 if (act->is_read() && process_read(act, second_part_of_rmw))
548 if (act->is_write() && process_write(act))
551 if (act->is_mutex_op())
555 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
558 case WORK_CHECK_RELEASE_SEQ:
559 resolve_release_sequences(work.location, &work_queue);
561 case WORK_CHECK_MO_EDGES: {
562 /** @todo Complete verification of work_queue */
563 ModelAction *act = work.action;
564 bool updated = false;
566 if (act->is_read()) {
567 if (r_modification_order(act, act->get_reads_from()))
570 if (act->is_write()) {
571 if (w_modification_order(act))
576 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
585 check_curr_backtracking(curr);
587 set_backtracking(curr);
589 return get_next_thread(curr);
593 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
594 * operation from the Thread it is joining with. Must be called after the
595 * completion of the Thread in question.
596 * @param join The THREAD_JOIN action
598 void ModelChecker::do_complete_join(ModelAction *join)
600 Thread *blocking = (Thread *)join->get_location();
601 ModelAction *act = get_last_action(blocking->get_id());
602 join->synchronize_with(act);
605 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
606 Node *currnode = curr->get_node();
607 Node *parnode = currnode->get_parent();
609 if ((!parnode->backtrack_empty() ||
610 !currnode->read_from_empty() ||
611 !currnode->future_value_empty() ||
612 !currnode->promise_empty())
613 && (!priv->next_backtrack ||
614 *curr > *priv->next_backtrack)) {
615 priv->next_backtrack = curr;
619 bool ModelChecker::promises_expired() {
620 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
621 Promise *promise = (*promises)[promise_index];
622 if (promise->get_expiration()<priv->used_sequence_numbers) {
629 /** @returns whether the current partial trace must be a prefix of a
631 bool ModelChecker::isfeasibleprefix() {
632 return promises->size() == 0 && *lazy_sync_size == 0;
635 /** @returns whether the current partial trace is feasible. */
636 bool ModelChecker::isfeasible() {
637 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
640 /** @returns whether the current partial trace is feasible other than
641 * multiple RMW reading from the same store. */
642 bool ModelChecker::isfeasibleotherthanRMW() {
644 if (mo_graph->checkForCycles())
645 DEBUG("Infeasible: modification order cycles\n");
647 DEBUG("Infeasible: failed promise\n");
649 DEBUG("Infeasible: too many reads\n");
650 if (promises_expired())
651 DEBUG("Infeasible: promises expired\n");
653 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
656 /** Returns whether the current completed trace is feasible. */
657 bool ModelChecker::isfinalfeasible() {
658 if (DBG_ENABLED() && promises->size() != 0)
659 DEBUG("Infeasible: unrevolved promises\n");
661 return isfeasible() && promises->size() == 0;
664 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
665 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
666 int tid = id_to_int(act->get_tid());
667 ModelAction *lastread = get_last_action(tid);
668 lastread->process_rmw(act);
669 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
670 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
671 mo_graph->commitChanges();
677 * Checks whether a thread has read from the same write for too many times
678 * without seeing the effects of a later write.
681 * 1) there must a different write that we could read from that would satisfy the modification order,
682 * 2) we must have read from the same value in excess of maxreads times, and
683 * 3) that other write must have been in the reads_from set for maxreads times.
685 * If so, we decide that the execution is no longer feasible.
687 void ModelChecker::check_recency(ModelAction *curr) {
688 if (params.maxreads != 0) {
689 if (curr->get_node()->get_read_from_size() <= 1)
692 //Must make sure that execution is currently feasible... We could
693 //accidentally clear by rolling back
697 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
698 int tid = id_to_int(curr->get_tid());
701 if ((int)thrd_lists->size() <= tid)
704 action_list_t *list = &(*thrd_lists)[tid];
706 action_list_t::reverse_iterator rit = list->rbegin();
708 for (; (*rit) != curr; rit++)
710 /* go past curr now */
713 action_list_t::reverse_iterator ritcopy = rit;
714 //See if we have enough reads from the same value
716 for (; count < params.maxreads; rit++,count++) {
717 if (rit==list->rend())
719 ModelAction *act = *rit;
722 if (act->get_reads_from() != curr->get_reads_from())
724 if (act->get_node()->get_read_from_size() <= 1)
728 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
730 const ModelAction * write = curr->get_node()->get_read_from_at(i);
731 //Need a different write
732 if (write==curr->get_reads_from())
735 /* Test to see whether this is a feasible write to read from*/
736 mo_graph->startChanges();
737 r_modification_order(curr, write);
738 bool feasiblereadfrom = isfeasible();
739 mo_graph->rollbackChanges();
741 if (!feasiblereadfrom)
745 bool feasiblewrite = true;
746 //new we need to see if this write works for everyone
748 for (int loop = count; loop>0; loop--,rit++) {
749 ModelAction *act=*rit;
750 bool foundvalue = false;
751 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
752 if (act->get_node()->get_read_from_at(i)==write) {
758 feasiblewrite = false;
763 too_many_reads = true;
771 * Updates the mo_graph with the constraints imposed from the current
774 * Basic idea is the following: Go through each other thread and find
775 * the lastest action that happened before our read. Two cases:
777 * (1) The action is a write => that write must either occur before
778 * the write we read from or be the write we read from.
780 * (2) The action is a read => the write that that action read from
781 * must occur before the write we read from or be the same write.
783 * @param curr The current action. Must be a read.
784 * @param rf The action that curr reads from. Must be a write.
785 * @return True if modification order edges were added; false otherwise
787 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
789 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
792 ASSERT(curr->is_read());
794 /* Iterate over all threads */
795 for (i = 0; i < thrd_lists->size(); i++) {
796 /* Iterate over actions in thread, starting from most recent */
797 action_list_t *list = &(*thrd_lists)[i];
798 action_list_t::reverse_iterator rit;
799 for (rit = list->rbegin(); rit != list->rend(); rit++) {
800 ModelAction *act = *rit;
803 * Include at most one act per-thread that "happens
804 * before" curr. Don't consider reflexively.
806 if (act->happens_before(curr) && act != curr) {
807 if (act->is_write()) {
809 mo_graph->addEdge(act, rf);
813 const ModelAction *prevreadfrom = act->get_reads_from();
814 if (prevreadfrom != NULL && rf != prevreadfrom) {
815 mo_graph->addEdge(prevreadfrom, rf);
827 /** This method fixes up the modification order when we resolve a
828 * promises. The basic problem is that actions that occur after the
829 * read curr could not property add items to the modification order
832 * So for each thread, we find the earliest item that happens after
833 * the read curr. This is the item we have to fix up with additional
834 * constraints. If that action is write, we add a MO edge between
835 * the Action rf and that action. If the action is a read, we add a
836 * MO edge between the Action rf, and whatever the read accessed.
838 * @param curr is the read ModelAction that we are fixing up MO edges for.
839 * @param rf is the write ModelAction that curr reads from.
843 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
845 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
847 ASSERT(curr->is_read());
849 /* Iterate over all threads */
850 for (i = 0; i < thrd_lists->size(); i++) {
851 /* Iterate over actions in thread, starting from most recent */
852 action_list_t *list = &(*thrd_lists)[i];
853 action_list_t::reverse_iterator rit;
854 ModelAction *lastact = NULL;
856 /* Find last action that happens after curr */
857 for (rit = list->rbegin(); rit != list->rend(); rit++) {
858 ModelAction *act = *rit;
859 if (curr->happens_before(act)) {
865 /* Include at most one act per-thread that "happens before" curr */
866 if (lastact != NULL) {
867 if (lastact->is_read()) {
868 const ModelAction *postreadfrom = lastact->get_reads_from();
869 if (postreadfrom != NULL&&rf != postreadfrom)
870 mo_graph->addEdge(rf, postreadfrom);
871 } else if (rf != lastact) {
872 mo_graph->addEdge(rf, lastact);
880 * Updates the mo_graph with the constraints imposed from the current write.
882 * Basic idea is the following: Go through each other thread and find
883 * the lastest action that happened before our write. Two cases:
885 * (1) The action is a write => that write must occur before
888 * (2) The action is a read => the write that that action read from
889 * must occur before the current write.
891 * This method also handles two other issues:
893 * (I) Sequential Consistency: Making sure that if the current write is
894 * seq_cst, that it occurs after the previous seq_cst write.
896 * (II) Sending the write back to non-synchronizing reads.
898 * @param curr The current action. Must be a write.
899 * @return True if modification order edges were added; false otherwise
901 bool ModelChecker::w_modification_order(ModelAction *curr)
903 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
906 ASSERT(curr->is_write());
908 if (curr->is_seqcst()) {
909 /* We have to at least see the last sequentially consistent write,
910 so we are initialized. */
911 ModelAction *last_seq_cst = get_last_seq_cst(curr);
912 if (last_seq_cst != NULL) {
913 mo_graph->addEdge(last_seq_cst, curr);
918 /* Iterate over all threads */
919 for (i = 0; i < thrd_lists->size(); i++) {
920 /* Iterate over actions in thread, starting from most recent */
921 action_list_t *list = &(*thrd_lists)[i];
922 action_list_t::reverse_iterator rit;
923 for (rit = list->rbegin(); rit != list->rend(); rit++) {
924 ModelAction *act = *rit;
927 * If RMW, we already have all relevant edges,
928 * so just skip to next thread.
929 * If normal write, we need to look at earlier
930 * actions, so continue processing list.
939 * Include at most one act per-thread that "happens
942 if (act->happens_before(curr)) {
944 * Note: if act is RMW, just add edge:
946 * The following edge should be handled elsewhere:
947 * readfrom(act) --mo--> act
950 mo_graph->addEdge(act, curr);
951 else if (act->is_read() && act->get_reads_from() != NULL)
952 mo_graph->addEdge(act->get_reads_from(), curr);
955 } else if (act->is_read() && !act->is_synchronizing(curr) &&
956 !act->same_thread(curr)) {
957 /* We have an action that:
958 (1) did not happen before us
959 (2) is a read and we are a write
960 (3) cannot synchronize with us
961 (4) is in a different thread
963 that read could potentially read from our write.
965 if (thin_air_constraint_may_allow(curr, act)) {
967 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
968 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
969 futurevalues->push_back(pfv);
979 /** Arbitrary reads from the future are not allowed. Section 29.3
980 * part 9 places some constraints. This method checks one result of constraint
981 * constraint. Others require compiler support. */
983 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
984 if (!writer->is_rmw())
987 if (!reader->is_rmw())
990 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
993 if (search->get_tid() == reader->get_tid() &&
994 search->happens_before(reader))
1002 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1003 * The ModelAction under consideration is expected to be taking part in
1004 * release/acquire synchronization as an object of the "reads from" relation.
1005 * Note that this can only provide release sequence support for RMW chains
1006 * which do not read from the future, as those actions cannot be traced until
1007 * their "promise" is fulfilled. Similarly, we may not even establish the
1008 * presence of a release sequence with certainty, as some modification order
1009 * constraints may be decided further in the future. Thus, this function
1010 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1011 * and a boolean representing certainty.
1013 * @todo Finish lazy updating, when promises are fulfilled in the future
1014 * @param rf The action that might be part of a release sequence. Must be a
1016 * @param release_heads A pass-by-reference style return parameter. After
1017 * execution of this function, release_heads will contain the heads of all the
1018 * relevant release sequences, if any exists
1019 * @return true, if the ModelChecker is certain that release_heads is complete;
1022 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1025 /* read from future: need to settle this later */
1026 return false; /* incomplete */
1029 ASSERT(rf->is_write());
1031 if (rf->is_release())
1032 release_heads->push_back(rf);
1034 /* We need a RMW action that is both an acquire and release to stop */
1035 /** @todo Need to be smarter here... In the linux lock
1036 * example, this will run to the beginning of the program for
1038 if (rf->is_acquire() && rf->is_release())
1039 return true; /* complete */
1040 return release_seq_head(rf->get_reads_from(), release_heads);
1042 if (rf->is_release())
1043 return true; /* complete */
1045 /* else relaxed write; check modification order for contiguous subsequence
1046 * -> rf must be same thread as release */
1047 int tid = id_to_int(rf->get_tid());
1048 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1049 action_list_t *list = &(*thrd_lists)[tid];
1050 action_list_t::const_reverse_iterator rit;
1052 /* Find rf in the thread list */
1053 rit = std::find(list->rbegin(), list->rend(), rf);
1054 ASSERT(rit != list->rend());
1056 /* Find the last write/release */
1057 for (; rit != list->rend(); rit++)
1058 if ((*rit)->is_release())
1060 if (rit == list->rend()) {
1061 /* No write-release in this thread */
1062 return true; /* complete */
1064 ModelAction *release = *rit;
1066 ASSERT(rf->same_thread(release));
1068 bool certain = true;
1069 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1070 if (id_to_int(rf->get_tid()) == (int)i)
1072 list = &(*thrd_lists)[i];
1074 /* Can we ensure no future writes from this thread may break
1075 * the release seq? */
1076 bool future_ordered = false;
1078 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1079 const ModelAction *act = *rit;
1080 if (!act->is_write())
1082 /* Reach synchronization -> this thread is complete */
1083 if (act->happens_before(release))
1085 if (rf->happens_before(act)) {
1086 future_ordered = true;
1090 /* Check modification order */
1091 if (mo_graph->checkReachable(rf, act)) {
1092 /* rf --mo--> act */
1093 future_ordered = true;
1096 if (mo_graph->checkReachable(act, release))
1097 /* act --mo--> release */
1099 if (mo_graph->checkReachable(release, act) &&
1100 mo_graph->checkReachable(act, rf)) {
1101 /* release --mo-> act --mo--> rf */
1102 return true; /* complete */
1106 if (!future_ordered)
1107 return false; /* This thread is uncertain */
1111 release_heads->push_back(release);
1116 * A public interface for getting the release sequence head(s) with which a
1117 * given ModelAction must synchronize. This function only returns a non-empty
1118 * result when it can locate a release sequence head with certainty. Otherwise,
1119 * it may mark the internal state of the ModelChecker so that it will handle
1120 * the release sequence at a later time, causing @a act to update its
1121 * synchronization at some later point in execution.
1122 * @param act The 'acquire' action that may read from a release sequence
1123 * @param release_heads A pass-by-reference return parameter. Will be filled
1124 * with the head(s) of the release sequence(s), if they exists with certainty.
1125 * @see ModelChecker::release_seq_head
1127 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1129 const ModelAction *rf = act->get_reads_from();
1131 complete = release_seq_head(rf, release_heads);
1133 /* add act to 'lazy checking' list */
1134 action_list_t *list;
1135 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1136 list->push_back(act);
1137 (*lazy_sync_size)++;
1142 * Attempt to resolve all stashed operations that might synchronize with a
1143 * release sequence for a given location. This implements the "lazy" portion of
1144 * determining whether or not a release sequence was contiguous, since not all
1145 * modification order information is present at the time an action occurs.
1147 * @param location The location/object that should be checked for release
1148 * sequence resolutions
1149 * @param work_queue The work queue to which to add work items as they are
1151 * @return True if any updates occurred (new synchronization, new mo_graph
1154 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1156 action_list_t *list;
1157 list = lazy_sync_with_release->getptr(location);
1161 bool updated = false;
1162 action_list_t::iterator it = list->begin();
1163 while (it != list->end()) {
1164 ModelAction *act = *it;
1165 const ModelAction *rf = act->get_reads_from();
1166 rel_heads_list_t release_heads;
1168 complete = release_seq_head(rf, &release_heads);
1169 for (unsigned int i = 0; i < release_heads.size(); i++) {
1170 if (!act->has_synchronized_with(release_heads[i])) {
1172 act->synchronize_with(release_heads[i]);
1177 /* Re-check act for mo_graph edges */
1178 work_queue->push_back(MOEdgeWorkEntry(act));
1180 /* propagate synchronization to later actions */
1181 action_list_t::reverse_iterator it = action_trace->rbegin();
1182 while ((*it) != act) {
1183 ModelAction *propagate = *it;
1184 if (act->happens_before(propagate)) {
1185 propagate->synchronize_with(act);
1186 /* Re-check 'propagate' for mo_graph edges */
1187 work_queue->push_back(MOEdgeWorkEntry(propagate));
1192 it = list->erase(it);
1193 (*lazy_sync_size)--;
1198 // If we resolved promises or data races, see if we have realized a data race.
1199 if (checkDataRaces()) {
1207 * Performs various bookkeeping operations for the current ModelAction. For
1208 * instance, adds action to the per-object, per-thread action vector and to the
1209 * action trace list of all thread actions.
1211 * @param act is the ModelAction to add.
1213 void ModelChecker::add_action_to_lists(ModelAction *act)
1215 int tid = id_to_int(act->get_tid());
1216 action_trace->push_back(act);
1218 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1220 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1221 if (tid >= (int)vec->size())
1222 vec->resize(priv->next_thread_id);
1223 (*vec)[tid].push_back(act);
1225 if ((int)thrd_last_action->size() <= tid)
1226 thrd_last_action->resize(get_num_threads());
1227 (*thrd_last_action)[tid] = act;
1230 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1232 int threadid=id_to_int(tid);
1233 if (threadid<(int)thrd_last_action->size())
1234 return (*thrd_last_action)[id_to_int(tid)];
1240 * Gets the last memory_order_seq_cst write (in the total global sequence)
1241 * performed on a particular object (i.e., memory location), not including the
1243 * @param curr The current ModelAction; also denotes the object location to
1245 * @return The last seq_cst write
1247 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1249 void *location = curr->get_location();
1250 action_list_t *list = obj_map->get_safe_ptr(location);
1251 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1252 action_list_t::reverse_iterator rit;
1253 for (rit = list->rbegin(); rit != list->rend(); rit++)
1254 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1259 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr)
1261 void *location = curr->get_location();
1262 action_list_t *list = obj_map->get_safe_ptr(location);
1263 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1264 action_list_t::reverse_iterator rit;
1265 for (rit = list->rbegin(); rit != list->rend(); rit++)
1266 if ((*rit)->is_unlock())
1271 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1273 ModelAction *parent = get_last_action(tid);
1275 parent = get_thread(tid)->get_creation();
1280 * Returns the clock vector for a given thread.
1281 * @param tid The thread whose clock vector we want
1282 * @return Desired clock vector
1284 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1286 return get_parent_action(tid)->get_cv();
1290 * Resolve a set of Promises with a current write. The set is provided in the
1291 * Node corresponding to @a write.
1292 * @param write The ModelAction that is fulfilling Promises
1293 * @return True if promises were resolved; false otherwise
1295 bool ModelChecker::resolve_promises(ModelAction *write)
1297 bool resolved = false;
1299 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1300 Promise *promise = (*promises)[promise_index];
1301 if (write->get_node()->get_promise(i)) {
1302 ModelAction *read = promise->get_action();
1303 read->read_from(write);
1304 if (read->is_rmw()) {
1305 mo_graph->addRMWEdge(write, read);
1307 //First fix up the modification order for actions that happened
1309 r_modification_order(read, write);
1310 //Next fix up the modification order for actions that happened
1312 post_r_modification_order(read, write);
1313 promises->erase(promises->begin() + promise_index);
1322 * Compute the set of promises that could potentially be satisfied by this
1323 * action. Note that the set computation actually appears in the Node, not in
1325 * @param curr The ModelAction that may satisfy promises
1327 void ModelChecker::compute_promises(ModelAction *curr)
1329 for (unsigned int i = 0; i < promises->size(); i++) {
1330 Promise *promise = (*promises)[i];
1331 const ModelAction *act = promise->get_action();
1332 if (!act->happens_before(curr) &&
1334 !act->is_synchronizing(curr) &&
1335 !act->same_thread(curr) &&
1336 promise->get_value() == curr->get_value()) {
1337 curr->get_node()->set_promise(i);
1342 /** Checks promises in response to change in ClockVector Threads. */
1343 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1345 for (unsigned int i = 0; i < promises->size(); i++) {
1346 Promise *promise = (*promises)[i];
1347 const ModelAction *act = promise->get_action();
1348 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1349 merge_cv->synchronized_since(act)) {
1350 //This thread is no longer able to send values back to satisfy the promise
1351 int num_synchronized_threads = promise->increment_threads();
1352 if (num_synchronized_threads == get_num_threads()) {
1353 //Promise has failed
1354 failed_promise = true;
1362 * Build up an initial set of all past writes that this 'read' action may read
1363 * from. This set is determined by the clock vector's "happens before"
1365 * @param curr is the current ModelAction that we are exploring; it must be a
1368 void ModelChecker::build_reads_from_past(ModelAction *curr)
1370 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1372 ASSERT(curr->is_read());
1374 ModelAction *last_seq_cst = NULL;
1376 /* Track whether this object has been initialized */
1377 bool initialized = false;
1379 if (curr->is_seqcst()) {
1380 last_seq_cst = get_last_seq_cst(curr);
1381 /* We have to at least see the last sequentially consistent write,
1382 so we are initialized. */
1383 if (last_seq_cst != NULL)
1387 /* Iterate over all threads */
1388 for (i = 0; i < thrd_lists->size(); i++) {
1389 /* Iterate over actions in thread, starting from most recent */
1390 action_list_t *list = &(*thrd_lists)[i];
1391 action_list_t::reverse_iterator rit;
1392 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1393 ModelAction *act = *rit;
1395 /* Only consider 'write' actions */
1396 if (!act->is_write() || act == curr)
1399 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1400 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1401 DEBUG("Adding action to may_read_from:\n");
1402 if (DBG_ENABLED()) {
1406 curr->get_node()->add_read_from(act);
1409 /* Include at most one act per-thread that "happens before" curr */
1410 if (act->happens_before(curr)) {
1418 /** @todo Need a more informative way of reporting errors. */
1419 printf("ERROR: may read from uninitialized atomic\n");
1422 if (DBG_ENABLED() || !initialized) {
1423 printf("Reached read action:\n");
1425 printf("Printing may_read_from\n");
1426 curr->get_node()->print_may_read_from();
1427 printf("End printing may_read_from\n");
1430 ASSERT(initialized);
1433 static void print_list(action_list_t *list)
1435 action_list_t::iterator it;
1437 printf("---------------------------------------------------------------------\n");
1440 for (it = list->begin(); it != list->end(); it++) {
1443 printf("---------------------------------------------------------------------\n");
1446 void ModelChecker::print_summary()
1449 printf("Number of executions: %d\n", num_executions);
1450 printf("Number of feasible executions: %d\n", num_feasible_executions);
1451 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1453 #if SUPPORT_MOD_ORDER_DUMP
1455 char buffername[100];
1456 sprintf(buffername, "exec%u",num_executions);
1457 mo_graph->dumpGraphToFile(buffername);
1460 if (!isfinalfeasible())
1461 printf("INFEASIBLE EXECUTION!\n");
1462 print_list(action_trace);
1467 * Add a Thread to the system for the first time. Should only be called once
1469 * @param t The Thread to add
1471 void ModelChecker::add_thread(Thread *t)
1473 thread_map->put(id_to_int(t->get_id()), t);
1474 scheduler->add_thread(t);
1477 void ModelChecker::remove_thread(Thread *t)
1479 scheduler->remove_thread(t);
1483 * Switch from a user-context to the "master thread" context (a.k.a. system
1484 * context). This switch is made with the intention of exploring a particular
1485 * model-checking action (described by a ModelAction object). Must be called
1486 * from a user-thread context.
1487 * @param act The current action that will be explored. Must not be NULL.
1488 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1490 int ModelChecker::switch_to_master(ModelAction *act)
1493 Thread *old = thread_current();
1494 set_current_action(act);
1495 old->set_state(THREAD_READY);
1496 return Thread::swap(old, &system_context);
1500 * Takes the next step in the execution, if possible.
1501 * @return Returns true (success) if a step was taken and false otherwise.
1503 bool ModelChecker::take_step() {
1507 Thread * curr = thread_current();
1509 if (curr->get_state() == THREAD_READY) {
1510 ASSERT(priv->current_action);
1512 priv->nextThread = check_current_action(priv->current_action);
1513 priv->current_action = NULL;
1514 if (curr->is_blocked() || curr->is_complete())
1515 scheduler->remove_thread(curr);
1520 Thread * next = scheduler->next_thread(priv->nextThread);
1522 /* Infeasible -> don't take any more steps */
1527 next->set_state(THREAD_RUNNING);
1528 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1530 /* next == NULL -> don't take any more steps */
1534 if ( next->get_pending() != NULL ) {
1535 //restart a pending action
1536 set_current_action(next->get_pending());
1537 next->set_pending(NULL);
1538 next->set_state(THREAD_READY);
1542 /* Return false only if swap fails with an error */
1543 return (Thread::swap(&system_context, next) == 0);
1546 /** Runs the current execution until threre are no more steps to take. */
1547 void ModelChecker::finish_execution() {
1550 while (take_step());