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 * Initialize the current action by performing one or more of the following
450 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
451 * in the NodeStack, manipulating backtracking sets, allocating and
452 * initializing clock vectors, and computing the promises to fulfill.
454 * @param curr The current action, as passed from the user context; may be
455 * freed/invalidated after the execution of this function
456 * @return The current action, as processed by the ModelChecker. Is only the
457 * same as the parameter @a curr if this is a newly-explored action.
459 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
461 ModelAction *newcurr;
463 if (curr->is_rmwc() || curr->is_rmw()) {
464 newcurr = process_rmw(curr);
466 compute_promises(newcurr);
470 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
472 /* First restore type and order in case of RMW operation */
474 newcurr->copy_typeandorder(curr);
476 ASSERT(curr->get_location() == newcurr->get_location());
477 newcurr->copy_from_new(curr);
479 /* Discard duplicate ModelAction; use action from NodeStack */
482 /* If we have diverged, we need to reset the clock vector. */
484 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
488 * Perform one-time actions when pushing new ModelAction onto
491 curr->create_cv(get_parent_action(curr->get_tid()));
492 if (curr->is_write())
493 compute_promises(curr);
499 * This method checks whether a model action is enabled at the given point.
500 * At this point, it checks whether a lock operation would be successful at this point.
501 * If not, it puts the thread in a waiter list.
502 * @param curr is the ModelAction to check whether it is enabled.
503 * @return a bool that indicates whether the action is enabled.
506 bool ModelChecker::check_action_enabled(ModelAction *curr) {
507 if (curr->is_lock()) {
508 std::mutex * lock = (std::mutex *)curr->get_location();
509 struct std::mutex_state * state = lock->get_state();
510 if (state->islocked) {
511 //Stick the action in the appropriate waiting queue
512 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
521 * This is the heart of the model checker routine. It performs model-checking
522 * actions corresponding to a given "current action." Among other processes, it
523 * calculates reads-from relationships, updates synchronization clock vectors,
524 * forms a memory_order constraints graph, and handles replay/backtrack
525 * execution when running permutations of previously-observed executions.
527 * @param curr The current action to process
528 * @return The next Thread that must be executed. May be NULL if ModelChecker
529 * makes no choice (e.g., according to replay execution, combining RMW actions,
532 Thread * ModelChecker::check_current_action(ModelAction *curr)
536 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
538 if (!check_action_enabled(curr)) {
539 //we'll make the execution look like we chose to run this action
540 //much later...when a lock is actually available to relese
541 get_current_thread()->set_pending(curr);
542 remove_thread(get_current_thread());
543 return get_next_thread(NULL);
546 ModelAction *newcurr = initialize_curr_action(curr);
548 /* Add the action to lists before any other model-checking tasks */
549 if (!second_part_of_rmw)
550 add_action_to_lists(newcurr);
552 /* Build may_read_from set for newly-created actions */
553 if (curr == newcurr && curr->is_read())
554 build_reads_from_past(curr);
557 /* Thread specific actions */
558 switch (curr->get_type()) {
559 case THREAD_CREATE: {
560 Thread *th = (Thread *)curr->get_location();
561 th->set_creation(curr);
565 Thread *waiting, *blocking;
566 waiting = get_thread(curr);
567 blocking = (Thread *)curr->get_location();
568 if (!blocking->is_complete()) {
569 blocking->push_wait_list(curr);
570 scheduler->sleep(waiting);
572 do_complete_join(curr);
576 case THREAD_FINISH: {
577 Thread *th = get_thread(curr);
578 while (!th->wait_list_empty()) {
579 ModelAction *act = th->pop_wait_list();
580 Thread *wake = get_thread(act);
581 scheduler->wake(wake);
582 do_complete_join(act);
588 check_promises(NULL, curr->get_cv());
595 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
597 while (!work_queue.empty()) {
598 WorkQueueEntry work = work_queue.front();
599 work_queue.pop_front();
602 case WORK_CHECK_CURR_ACTION: {
603 ModelAction *act = work.action;
604 bool updated = false;
605 if (act->is_read() && process_read(act, second_part_of_rmw))
608 if (act->is_write() && process_write(act))
611 if (act->is_mutex_op())
615 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
618 case WORK_CHECK_RELEASE_SEQ:
619 resolve_release_sequences(work.location, &work_queue);
621 case WORK_CHECK_MO_EDGES: {
622 /** @todo Complete verification of work_queue */
623 ModelAction *act = work.action;
624 bool updated = false;
626 if (act->is_read()) {
627 if (r_modification_order(act, act->get_reads_from()))
630 if (act->is_write()) {
631 if (w_modification_order(act))
636 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
645 check_curr_backtracking(curr);
647 set_backtracking(curr);
649 return get_next_thread(curr);
653 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
654 * operation from the Thread it is joining with. Must be called after the
655 * completion of the Thread in question.
656 * @param join The THREAD_JOIN action
658 void ModelChecker::do_complete_join(ModelAction *join)
660 Thread *blocking = (Thread *)join->get_location();
661 ModelAction *act = get_last_action(blocking->get_id());
662 join->synchronize_with(act);
665 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
666 Node *currnode = curr->get_node();
667 Node *parnode = currnode->get_parent();
669 if ((!parnode->backtrack_empty() ||
670 !currnode->read_from_empty() ||
671 !currnode->future_value_empty() ||
672 !currnode->promise_empty())
673 && (!priv->next_backtrack ||
674 *curr > *priv->next_backtrack)) {
675 priv->next_backtrack = curr;
679 bool ModelChecker::promises_expired() {
680 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
681 Promise *promise = (*promises)[promise_index];
682 if (promise->get_expiration()<priv->used_sequence_numbers) {
689 /** @return whether the current partial trace must be a prefix of a
691 bool ModelChecker::isfeasibleprefix() {
692 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
695 /** @return whether the current partial trace is feasible. */
696 bool ModelChecker::isfeasible() {
697 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
700 /** @return whether the current partial trace is feasible other than
701 * multiple RMW reading from the same store. */
702 bool ModelChecker::isfeasibleotherthanRMW() {
704 if (mo_graph->checkForCycles())
705 DEBUG("Infeasible: modification order cycles\n");
707 DEBUG("Infeasible: failed promise\n");
709 DEBUG("Infeasible: too many reads\n");
710 if (promises_expired())
711 DEBUG("Infeasible: promises expired\n");
713 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
716 /** Returns whether the current completed trace is feasible. */
717 bool ModelChecker::isfinalfeasible() {
718 if (DBG_ENABLED() && promises->size() != 0)
719 DEBUG("Infeasible: unrevolved promises\n");
721 return isfeasible() && promises->size() == 0;
724 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
725 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
726 int tid = id_to_int(act->get_tid());
727 ModelAction *lastread = get_last_action(tid);
728 lastread->process_rmw(act);
729 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
730 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
731 mo_graph->commitChanges();
737 * Checks whether a thread has read from the same write for too many times
738 * without seeing the effects of a later write.
741 * 1) there must a different write that we could read from that would satisfy the modification order,
742 * 2) we must have read from the same value in excess of maxreads times, and
743 * 3) that other write must have been in the reads_from set for maxreads times.
745 * If so, we decide that the execution is no longer feasible.
747 void ModelChecker::check_recency(ModelAction *curr) {
748 if (params.maxreads != 0) {
749 if (curr->get_node()->get_read_from_size() <= 1)
752 //Must make sure that execution is currently feasible... We could
753 //accidentally clear by rolling back
757 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
758 int tid = id_to_int(curr->get_tid());
761 if ((int)thrd_lists->size() <= tid)
764 action_list_t *list = &(*thrd_lists)[tid];
766 action_list_t::reverse_iterator rit = list->rbegin();
768 for (; (*rit) != curr; rit++)
770 /* go past curr now */
773 action_list_t::reverse_iterator ritcopy = rit;
774 //See if we have enough reads from the same value
776 for (; count < params.maxreads; rit++,count++) {
777 if (rit==list->rend())
779 ModelAction *act = *rit;
782 if (act->get_reads_from() != curr->get_reads_from())
784 if (act->get_node()->get_read_from_size() <= 1)
788 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
790 const ModelAction * write = curr->get_node()->get_read_from_at(i);
791 //Need a different write
792 if (write==curr->get_reads_from())
795 /* Test to see whether this is a feasible write to read from*/
796 mo_graph->startChanges();
797 r_modification_order(curr, write);
798 bool feasiblereadfrom = isfeasible();
799 mo_graph->rollbackChanges();
801 if (!feasiblereadfrom)
805 bool feasiblewrite = true;
806 //new we need to see if this write works for everyone
808 for (int loop = count; loop>0; loop--,rit++) {
809 ModelAction *act=*rit;
810 bool foundvalue = false;
811 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
812 if (act->get_node()->get_read_from_at(i)==write) {
818 feasiblewrite = false;
823 too_many_reads = true;
831 * Updates the mo_graph with the constraints imposed from the current
834 * Basic idea is the following: Go through each other thread and find
835 * the lastest action that happened before our read. Two cases:
837 * (1) The action is a write => that write must either occur before
838 * the write we read from or be the write we read from.
840 * (2) The action is a read => the write that that action read from
841 * must occur before the write we read from or be the same write.
843 * @param curr The current action. Must be a read.
844 * @param rf The action that curr reads from. Must be a write.
845 * @return True if modification order edges were added; false otherwise
847 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
849 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
852 ASSERT(curr->is_read());
854 /* Iterate over all threads */
855 for (i = 0; i < thrd_lists->size(); i++) {
856 /* Iterate over actions in thread, starting from most recent */
857 action_list_t *list = &(*thrd_lists)[i];
858 action_list_t::reverse_iterator rit;
859 for (rit = list->rbegin(); rit != list->rend(); rit++) {
860 ModelAction *act = *rit;
863 * Include at most one act per-thread that "happens
864 * before" curr. Don't consider reflexively.
866 if (act->happens_before(curr) && act != curr) {
867 if (act->is_write()) {
869 mo_graph->addEdge(act, rf);
873 const ModelAction *prevreadfrom = act->get_reads_from();
874 if (prevreadfrom != NULL && rf != prevreadfrom) {
875 mo_graph->addEdge(prevreadfrom, rf);
887 /** This method fixes up the modification order when we resolve a
888 * promises. The basic problem is that actions that occur after the
889 * read curr could not property add items to the modification order
892 * So for each thread, we find the earliest item that happens after
893 * the read curr. This is the item we have to fix up with additional
894 * constraints. If that action is write, we add a MO edge between
895 * the Action rf and that action. If the action is a read, we add a
896 * MO edge between the Action rf, and whatever the read accessed.
898 * @param curr is the read ModelAction that we are fixing up MO edges for.
899 * @param rf is the write ModelAction that curr reads from.
903 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
905 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
907 ASSERT(curr->is_read());
909 /* Iterate over all threads */
910 for (i = 0; i < thrd_lists->size(); i++) {
911 /* Iterate over actions in thread, starting from most recent */
912 action_list_t *list = &(*thrd_lists)[i];
913 action_list_t::reverse_iterator rit;
914 ModelAction *lastact = NULL;
916 /* Find last action that happens after curr */
917 for (rit = list->rbegin(); rit != list->rend(); rit++) {
918 ModelAction *act = *rit;
919 if (curr->happens_before(act)) {
925 /* Include at most one act per-thread that "happens before" curr */
926 if (lastact != NULL) {
927 if (lastact->is_read()) {
928 const ModelAction *postreadfrom = lastact->get_reads_from();
929 if (postreadfrom != NULL&&rf != postreadfrom)
930 mo_graph->addEdge(rf, postreadfrom);
931 } else if (rf != lastact) {
932 mo_graph->addEdge(rf, lastact);
940 * Updates the mo_graph with the constraints imposed from the current write.
942 * Basic idea is the following: Go through each other thread and find
943 * the lastest action that happened before our write. Two cases:
945 * (1) The action is a write => that write must occur before
948 * (2) The action is a read => the write that that action read from
949 * must occur before the current write.
951 * This method also handles two other issues:
953 * (I) Sequential Consistency: Making sure that if the current write is
954 * seq_cst, that it occurs after the previous seq_cst write.
956 * (II) Sending the write back to non-synchronizing reads.
958 * @param curr The current action. Must be a write.
959 * @return True if modification order edges were added; false otherwise
961 bool ModelChecker::w_modification_order(ModelAction *curr)
963 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
966 ASSERT(curr->is_write());
968 if (curr->is_seqcst()) {
969 /* We have to at least see the last sequentially consistent write,
970 so we are initialized. */
971 ModelAction *last_seq_cst = get_last_seq_cst(curr);
972 if (last_seq_cst != NULL) {
973 mo_graph->addEdge(last_seq_cst, curr);
978 /* Iterate over all threads */
979 for (i = 0; i < thrd_lists->size(); i++) {
980 /* Iterate over actions in thread, starting from most recent */
981 action_list_t *list = &(*thrd_lists)[i];
982 action_list_t::reverse_iterator rit;
983 for (rit = list->rbegin(); rit != list->rend(); rit++) {
984 ModelAction *act = *rit;
987 * If RMW, we already have all relevant edges,
988 * so just skip to next thread.
989 * If normal write, we need to look at earlier
990 * actions, so continue processing list.
999 * Include at most one act per-thread that "happens
1002 if (act->happens_before(curr)) {
1004 * Note: if act is RMW, just add edge:
1006 * The following edge should be handled elsewhere:
1007 * readfrom(act) --mo--> act
1009 if (act->is_write())
1010 mo_graph->addEdge(act, curr);
1011 else if (act->is_read() && act->get_reads_from() != NULL)
1012 mo_graph->addEdge(act->get_reads_from(), curr);
1015 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1016 !act->same_thread(curr)) {
1017 /* We have an action that:
1018 (1) did not happen before us
1019 (2) is a read and we are a write
1020 (3) cannot synchronize with us
1021 (4) is in a different thread
1023 that read could potentially read from our write.
1025 if (thin_air_constraint_may_allow(curr, act)) {
1027 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1028 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1029 futurevalues->push_back(pfv);
1039 /** Arbitrary reads from the future are not allowed. Section 29.3
1040 * part 9 places some constraints. This method checks one result of constraint
1041 * constraint. Others require compiler support. */
1043 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1044 if (!writer->is_rmw())
1047 if (!reader->is_rmw())
1050 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1051 if (search == reader)
1053 if (search->get_tid() == reader->get_tid() &&
1054 search->happens_before(reader))
1062 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1063 * The ModelAction under consideration is expected to be taking part in
1064 * release/acquire synchronization as an object of the "reads from" relation.
1065 * Note that this can only provide release sequence support for RMW chains
1066 * which do not read from the future, as those actions cannot be traced until
1067 * their "promise" is fulfilled. Similarly, we may not even establish the
1068 * presence of a release sequence with certainty, as some modification order
1069 * constraints may be decided further in the future. Thus, this function
1070 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1071 * and a boolean representing certainty.
1073 * @todo Finish lazy updating, when promises are fulfilled in the future
1074 * @param rf The action that might be part of a release sequence. Must be a
1076 * @param release_heads A pass-by-reference style return parameter. After
1077 * execution of this function, release_heads will contain the heads of all the
1078 * relevant release sequences, if any exists
1079 * @return true, if the ModelChecker is certain that release_heads is complete;
1082 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1085 ASSERT(rf->is_write());
1087 if (rf->is_release())
1088 release_heads->push_back(rf);
1090 break; /* End of RMW chain */
1092 /** @todo Need to be smarter here... In the linux lock
1093 * example, this will run to the beginning of the program for
1095 /** @todo The way to be smarter here is to keep going until 1
1096 * thread has a release preceded by an acquire and you've seen
1099 /* acq_rel RMW is a sufficient stopping condition */
1100 if (rf->is_acquire() && rf->is_release())
1101 return true; /* complete */
1103 rf = rf->get_reads_from();
1106 /* read from future: need to settle this later */
1107 return false; /* incomplete */
1110 if (rf->is_release())
1111 return true; /* complete */
1113 /* else relaxed write; check modification order for contiguous subsequence
1114 * -> rf must be same thread as release */
1115 int tid = id_to_int(rf->get_tid());
1116 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1117 action_list_t *list = &(*thrd_lists)[tid];
1118 action_list_t::const_reverse_iterator rit;
1120 /* Find rf in the thread list */
1121 rit = std::find(list->rbegin(), list->rend(), rf);
1122 ASSERT(rit != list->rend());
1124 /* Find the last write/release */
1125 for (; rit != list->rend(); rit++)
1126 if ((*rit)->is_release())
1128 if (rit == list->rend()) {
1129 /* No write-release in this thread */
1130 return true; /* complete */
1132 ModelAction *release = *rit;
1134 ASSERT(rf->same_thread(release));
1136 bool certain = true;
1137 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1138 if (id_to_int(rf->get_tid()) == (int)i)
1140 list = &(*thrd_lists)[i];
1142 /* Can we ensure no future writes from this thread may break
1143 * the release seq? */
1144 bool future_ordered = false;
1146 ModelAction *last = get_last_action(int_to_id(i));
1147 if (last && rf->happens_before(last))
1148 future_ordered = true;
1150 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1151 const ModelAction *act = *rit;
1152 /* Reach synchronization -> this thread is complete */
1153 if (act->happens_before(release))
1155 if (rf->happens_before(act)) {
1156 future_ordered = true;
1160 /* Only writes can break release sequences */
1161 if (!act->is_write())
1164 /* Check modification order */
1165 if (mo_graph->checkReachable(rf, act)) {
1166 /* rf --mo--> act */
1167 future_ordered = true;
1170 if (mo_graph->checkReachable(act, release))
1171 /* act --mo--> release */
1173 if (mo_graph->checkReachable(release, act) &&
1174 mo_graph->checkReachable(act, rf)) {
1175 /* release --mo-> act --mo--> rf */
1176 return true; /* complete */
1180 if (!future_ordered)
1181 return false; /* This thread is uncertain */
1185 release_heads->push_back(release);
1190 * A public interface for getting the release sequence head(s) with which a
1191 * given ModelAction must synchronize. This function only returns a non-empty
1192 * result when it can locate a release sequence head with certainty. Otherwise,
1193 * it may mark the internal state of the ModelChecker so that it will handle
1194 * the release sequence at a later time, causing @a act to update its
1195 * synchronization at some later point in execution.
1196 * @param act The 'acquire' action that may read from a release sequence
1197 * @param release_heads A pass-by-reference return parameter. Will be filled
1198 * with the head(s) of the release sequence(s), if they exists with certainty.
1199 * @see ModelChecker::release_seq_head
1201 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1203 const ModelAction *rf = act->get_reads_from();
1205 complete = release_seq_head(rf, release_heads);
1207 /* add act to 'lazy checking' list */
1208 pending_acq_rel_seq->push_back(act);
1213 * Attempt to resolve all stashed operations that might synchronize with a
1214 * release sequence for a given location. This implements the "lazy" portion of
1215 * determining whether or not a release sequence was contiguous, since not all
1216 * modification order information is present at the time an action occurs.
1218 * @param location The location/object that should be checked for release
1219 * sequence resolutions. A NULL value means to check all locations.
1220 * @param work_queue The work queue to which to add work items as they are
1222 * @return True if any updates occurred (new synchronization, new mo_graph
1225 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1227 bool updated = false;
1228 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1229 while (it != pending_acq_rel_seq->end()) {
1230 ModelAction *act = *it;
1232 /* Only resolve sequences on the given location, if provided */
1233 if (location && act->get_location() != location) {
1238 const ModelAction *rf = act->get_reads_from();
1239 rel_heads_list_t release_heads;
1241 complete = release_seq_head(rf, &release_heads);
1242 for (unsigned int i = 0; i < release_heads.size(); i++) {
1243 if (!act->has_synchronized_with(release_heads[i])) {
1245 act->synchronize_with(release_heads[i]);
1250 /* Re-check act for mo_graph edges */
1251 work_queue->push_back(MOEdgeWorkEntry(act));
1253 /* propagate synchronization to later actions */
1254 action_list_t::reverse_iterator it = action_trace->rbegin();
1255 for (; (*it) != act; it++) {
1256 ModelAction *propagate = *it;
1257 if (act->happens_before(propagate)) {
1258 propagate->synchronize_with(act);
1259 /* Re-check 'propagate' for mo_graph edges */
1260 work_queue->push_back(MOEdgeWorkEntry(propagate));
1265 it = pending_acq_rel_seq->erase(it);
1270 // If we resolved promises or data races, see if we have realized a data race.
1271 if (checkDataRaces()) {
1279 * Performs various bookkeeping operations for the current ModelAction. For
1280 * instance, adds action to the per-object, per-thread action vector and to the
1281 * action trace list of all thread actions.
1283 * @param act is the ModelAction to add.
1285 void ModelChecker::add_action_to_lists(ModelAction *act)
1287 int tid = id_to_int(act->get_tid());
1288 action_trace->push_back(act);
1290 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1292 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1293 if (tid >= (int)vec->size())
1294 vec->resize(priv->next_thread_id);
1295 (*vec)[tid].push_back(act);
1297 if ((int)thrd_last_action->size() <= tid)
1298 thrd_last_action->resize(get_num_threads());
1299 (*thrd_last_action)[tid] = act;
1303 * @brief Get the last action performed by a particular Thread
1304 * @param tid The thread ID of the Thread in question
1305 * @return The last action in the thread
1307 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1309 int threadid = id_to_int(tid);
1310 if (threadid < (int)thrd_last_action->size())
1311 return (*thrd_last_action)[id_to_int(tid)];
1317 * Gets the last memory_order_seq_cst write (in the total global sequence)
1318 * performed on a particular object (i.e., memory location), not including the
1320 * @param curr The current ModelAction; also denotes the object location to
1322 * @return The last seq_cst write
1324 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1326 void *location = curr->get_location();
1327 action_list_t *list = obj_map->get_safe_ptr(location);
1328 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1329 action_list_t::reverse_iterator rit;
1330 for (rit = list->rbegin(); rit != list->rend(); rit++)
1331 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1337 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1338 * location). This function identifies the mutex according to the current
1339 * action, which is presumed to perform on the same mutex.
1340 * @param curr The current ModelAction; also denotes the object location to
1342 * @return The last unlock operation
1344 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1346 void *location = curr->get_location();
1347 action_list_t *list = obj_map->get_safe_ptr(location);
1348 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1349 action_list_t::reverse_iterator rit;
1350 for (rit = list->rbegin(); rit != list->rend(); rit++)
1351 if ((*rit)->is_unlock())
1356 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1358 ModelAction *parent = get_last_action(tid);
1360 parent = get_thread(tid)->get_creation();
1365 * Returns the clock vector for a given thread.
1366 * @param tid The thread whose clock vector we want
1367 * @return Desired clock vector
1369 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1371 return get_parent_action(tid)->get_cv();
1375 * Resolve a set of Promises with a current write. The set is provided in the
1376 * Node corresponding to @a write.
1377 * @param write The ModelAction that is fulfilling Promises
1378 * @return True if promises were resolved; false otherwise
1380 bool ModelChecker::resolve_promises(ModelAction *write)
1382 bool resolved = false;
1384 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1385 Promise *promise = (*promises)[promise_index];
1386 if (write->get_node()->get_promise(i)) {
1387 ModelAction *read = promise->get_action();
1388 read->read_from(write);
1389 if (read->is_rmw()) {
1390 mo_graph->addRMWEdge(write, read);
1392 //First fix up the modification order for actions that happened
1394 r_modification_order(read, write);
1395 //Next fix up the modification order for actions that happened
1397 post_r_modification_order(read, write);
1398 promises->erase(promises->begin() + promise_index);
1407 * Compute the set of promises that could potentially be satisfied by this
1408 * action. Note that the set computation actually appears in the Node, not in
1410 * @param curr The ModelAction that may satisfy promises
1412 void ModelChecker::compute_promises(ModelAction *curr)
1414 for (unsigned int i = 0; i < promises->size(); i++) {
1415 Promise *promise = (*promises)[i];
1416 const ModelAction *act = promise->get_action();
1417 if (!act->happens_before(curr) &&
1419 !act->is_synchronizing(curr) &&
1420 !act->same_thread(curr) &&
1421 promise->get_value() == curr->get_value()) {
1422 curr->get_node()->set_promise(i);
1427 /** Checks promises in response to change in ClockVector Threads. */
1428 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1430 for (unsigned int i = 0; i < promises->size(); i++) {
1431 Promise *promise = (*promises)[i];
1432 const ModelAction *act = promise->get_action();
1433 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1434 merge_cv->synchronized_since(act)) {
1435 //This thread is no longer able to send values back to satisfy the promise
1436 int num_synchronized_threads = promise->increment_threads();
1437 if (num_synchronized_threads == get_num_threads()) {
1438 //Promise has failed
1439 failed_promise = true;
1447 * Build up an initial set of all past writes that this 'read' action may read
1448 * from. This set is determined by the clock vector's "happens before"
1450 * @param curr is the current ModelAction that we are exploring; it must be a
1453 void ModelChecker::build_reads_from_past(ModelAction *curr)
1455 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1457 ASSERT(curr->is_read());
1459 ModelAction *last_seq_cst = NULL;
1461 /* Track whether this object has been initialized */
1462 bool initialized = false;
1464 if (curr->is_seqcst()) {
1465 last_seq_cst = get_last_seq_cst(curr);
1466 /* We have to at least see the last sequentially consistent write,
1467 so we are initialized. */
1468 if (last_seq_cst != NULL)
1472 /* Iterate over all threads */
1473 for (i = 0; i < thrd_lists->size(); i++) {
1474 /* Iterate over actions in thread, starting from most recent */
1475 action_list_t *list = &(*thrd_lists)[i];
1476 action_list_t::reverse_iterator rit;
1477 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1478 ModelAction *act = *rit;
1480 /* Only consider 'write' actions */
1481 if (!act->is_write() || act == curr)
1484 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1485 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1486 DEBUG("Adding action to may_read_from:\n");
1487 if (DBG_ENABLED()) {
1491 curr->get_node()->add_read_from(act);
1494 /* Include at most one act per-thread that "happens before" curr */
1495 if (act->happens_before(curr)) {
1503 /** @todo Need a more informative way of reporting errors. */
1504 printf("ERROR: may read from uninitialized atomic\n");
1507 if (DBG_ENABLED() || !initialized) {
1508 printf("Reached read action:\n");
1510 printf("Printing may_read_from\n");
1511 curr->get_node()->print_may_read_from();
1512 printf("End printing may_read_from\n");
1515 ASSERT(initialized);
1518 static void print_list(action_list_t *list)
1520 action_list_t::iterator it;
1522 printf("---------------------------------------------------------------------\n");
1525 for (it = list->begin(); it != list->end(); it++) {
1528 printf("---------------------------------------------------------------------\n");
1531 void ModelChecker::print_summary()
1534 printf("Number of executions: %d\n", num_executions);
1535 printf("Number of feasible executions: %d\n", num_feasible_executions);
1536 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1538 #if SUPPORT_MOD_ORDER_DUMP
1540 char buffername[100];
1541 sprintf(buffername, "exec%04u", num_executions);
1542 mo_graph->dumpGraphToFile(buffername);
1545 if (!isfinalfeasible())
1546 printf("INFEASIBLE EXECUTION!\n");
1547 print_list(action_trace);
1552 * Add a Thread to the system for the first time. Should only be called once
1554 * @param t The Thread to add
1556 void ModelChecker::add_thread(Thread *t)
1558 thread_map->put(id_to_int(t->get_id()), t);
1559 scheduler->add_thread(t);
1563 * Removes a thread from the scheduler.
1564 * @param the thread to remove.
1567 void ModelChecker::remove_thread(Thread *t)
1569 scheduler->remove_thread(t);
1573 * Switch from a user-context to the "master thread" context (a.k.a. system
1574 * context). This switch is made with the intention of exploring a particular
1575 * model-checking action (described by a ModelAction object). Must be called
1576 * from a user-thread context.
1577 * @param act The current action that will be explored. Must not be NULL.
1578 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1580 int ModelChecker::switch_to_master(ModelAction *act)
1583 Thread *old = thread_current();
1584 set_current_action(act);
1585 old->set_state(THREAD_READY);
1586 return Thread::swap(old, &system_context);
1590 * Takes the next step in the execution, if possible.
1591 * @return Returns true (success) if a step was taken and false otherwise.
1593 bool ModelChecker::take_step() {
1597 Thread * curr = thread_current();
1599 if (curr->get_state() == THREAD_READY) {
1600 ASSERT(priv->current_action);
1602 priv->nextThread = check_current_action(priv->current_action);
1603 priv->current_action = NULL;
1604 if (curr->is_blocked() || curr->is_complete())
1605 scheduler->remove_thread(curr);
1610 Thread * next = scheduler->next_thread(priv->nextThread);
1612 /* Infeasible -> don't take any more steps */
1617 next->set_state(THREAD_RUNNING);
1618 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1620 /* next == NULL -> don't take any more steps */
1624 if ( next->get_pending() != NULL ) {
1625 //restart a pending action
1626 set_current_action(next->get_pending());
1627 next->set_pending(NULL);
1628 next->set_state(THREAD_READY);
1632 /* Return false only if swap fails with an error */
1633 return (Thread::swap(&system_context, next) == 0);
1636 /** Runs the current execution until threre are no more steps to take. */
1637 void ModelChecker::finish_execution() {
1640 while (take_step());