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 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 /** @return a thread ID for a new Thread */
90 thread_id_t ModelChecker::get_next_id()
92 return priv->next_thread_id++;
95 /** @return the number of user threads created during this execution */
96 int ModelChecker::get_num_threads()
98 return priv->next_thread_id;
101 /** @return 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 switch (act->get_type()) {
207 /* linear search: from most recent to oldest */
208 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
209 action_list_t::reverse_iterator rit;
210 for (rit = list->rbegin(); rit != list->rend(); rit++) {
211 ModelAction *prev = *rit;
212 if (act->is_synchronizing(prev))
218 case ATOMIC_TRYLOCK: {
219 /* linear search: from most recent to oldest */
220 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
221 action_list_t::reverse_iterator rit;
222 for (rit = list->rbegin(); rit != list->rend(); rit++) {
223 ModelAction *prev = *rit;
224 if (act->is_conflicting_lock(prev))
229 case ATOMIC_UNLOCK: {
230 /* linear search: from most recent to oldest */
231 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
232 action_list_t::reverse_iterator rit;
233 for (rit = list->rbegin(); rit != list->rend(); rit++) {
234 ModelAction *prev = *rit;
235 if (!act->same_thread(prev)&&prev->is_failed_trylock())
246 /** This method find backtracking points where we should try to
247 * reorder the parameter ModelAction against.
249 * @param the ModelAction to find backtracking points for.
253 void ModelChecker::set_backtracking(ModelAction *act)
255 Thread *t = get_thread(act);
256 ModelAction * prev = get_last_conflict(act);
260 Node * node = prev->get_node()->get_parent();
262 int low_tid, high_tid;
263 if (node->is_enabled(t)) {
264 low_tid = id_to_int(act->get_tid());
265 high_tid = low_tid+1;
268 high_tid = get_num_threads();
271 for(int i = low_tid; i < high_tid; i++) {
272 thread_id_t tid = int_to_id(i);
273 if (!node->is_enabled(tid))
276 /* Check if this has been explored already */
277 if (node->has_been_explored(tid))
280 /* See if fairness allows */
281 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
283 for(int t=0;t<node->get_num_threads();t++) {
284 thread_id_t tother=int_to_id(t);
285 if (node->is_enabled(tother) && node->has_priority(tother)) {
294 /* Cache the latest backtracking point */
295 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
296 priv->next_backtrack = prev;
298 /* If this is a new backtracking point, mark the tree */
299 if (!node->set_backtrack(tid))
301 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
302 prev->get_tid(), t->get_id());
311 * Returns last backtracking point. The model checker will explore a different
312 * path for this point in the next execution.
313 * @return The ModelAction at which the next execution should diverge.
315 ModelAction * ModelChecker::get_next_backtrack()
317 ModelAction *next = priv->next_backtrack;
318 priv->next_backtrack = NULL;
323 * Processes a read or rmw model action.
324 * @param curr is the read model action to process.
325 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
326 * @return True if processing this read updates the mo_graph.
328 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
331 bool updated = false;
333 const ModelAction *reads_from = curr->get_node()->get_read_from();
334 if (reads_from != NULL) {
335 mo_graph->startChanges();
337 value = reads_from->get_value();
338 bool r_status = false;
340 if (!second_part_of_rmw) {
342 r_status = r_modification_order(curr, reads_from);
346 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
347 mo_graph->rollbackChanges();
348 too_many_reads = false;
352 curr->read_from(reads_from);
353 mo_graph->commitChanges();
355 } else if (!second_part_of_rmw) {
356 /* Read from future value */
357 value = curr->get_node()->get_future_value();
358 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
359 curr->read_from(NULL);
360 Promise *valuepromise = new Promise(curr, value, expiration);
361 promises->push_back(valuepromise);
363 get_thread(curr)->set_return_value(value);
369 * Processes a lock, trylock, or unlock model action. @param curr is
370 * the read model action to process.
372 * The try lock operation checks whether the lock is taken. If not,
373 * it falls to the normal lock operation case. If so, it returns
376 * The lock operation has already been checked that it is enabled, so
377 * it just grabs the lock and synchronizes with the previous unlock.
379 * The unlock operation has to re-enable all of the threads that are
380 * waiting on the lock.
382 void ModelChecker::process_mutex(ModelAction *curr) {
383 std::mutex *mutex = (std::mutex *)curr->get_location();
384 struct std::mutex_state *state = mutex->get_state();
385 switch (curr->get_type()) {
386 case ATOMIC_TRYLOCK: {
387 bool success = !state->islocked;
388 curr->set_try_lock(success);
390 get_thread(curr)->set_return_value(0);
393 get_thread(curr)->set_return_value(1);
395 //otherwise fall into the lock case
397 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
398 printf("Lock access before initialization\n");
401 state->islocked = true;
402 ModelAction *unlock = get_last_unlock(curr);
403 //synchronize with the previous unlock statement
405 curr->synchronize_with(unlock);
408 case ATOMIC_UNLOCK: {
410 state->islocked = false;
411 //wake up the other threads
412 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
413 //activate all the waiting threads
414 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
415 scheduler->add_thread(get_thread((*rit)->get_tid()));
426 * Process a write ModelAction
427 * @param curr The ModelAction to process
428 * @return True if the mo_graph was updated or promises were resolved
430 bool ModelChecker::process_write(ModelAction *curr)
432 bool updated_mod_order = w_modification_order(curr);
433 bool updated_promises = resolve_promises(curr);
435 if (promises->size() == 0) {
436 for (unsigned int i = 0; i < futurevalues->size(); i++) {
437 struct PendingFutureValue pfv = (*futurevalues)[i];
438 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
439 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
440 priv->next_backtrack = pfv.act;
442 futurevalues->resize(0);
445 mo_graph->commitChanges();
446 get_thread(curr)->set_return_value(VALUE_NONE);
447 return updated_mod_order || updated_promises;
451 * Initialize the current action by performing one or more of the following
452 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
453 * in the NodeStack, manipulating backtracking sets, allocating and
454 * initializing clock vectors, and computing the promises to fulfill.
456 * @param curr The current action, as passed from the user context; may be
457 * freed/invalidated after the execution of this function
458 * @return The current action, as processed by the ModelChecker. Is only the
459 * same as the parameter @a curr if this is a newly-explored action.
461 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
463 ModelAction *newcurr;
465 if (curr->is_rmwc() || curr->is_rmw()) {
466 newcurr = process_rmw(curr);
468 compute_promises(newcurr);
472 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
474 /* First restore type and order in case of RMW operation */
476 newcurr->copy_typeandorder(curr);
478 ASSERT(curr->get_location() == newcurr->get_location());
479 newcurr->copy_from_new(curr);
481 /* Discard duplicate ModelAction; use action from NodeStack */
484 /* If we have diverged, we need to reset the clock vector. */
486 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
490 * Perform one-time actions when pushing new ModelAction onto
493 curr->create_cv(get_parent_action(curr->get_tid()));
494 if (curr->is_write())
495 compute_promises(curr);
501 * This method checks whether a model action is enabled at the given point.
502 * At this point, it checks whether a lock operation would be successful at this point.
503 * If not, it puts the thread in a waiter list.
504 * @param curr is the ModelAction to check whether it is enabled.
505 * @return a bool that indicates whether the action is enabled.
508 bool ModelChecker::check_action_enabled(ModelAction *curr) {
509 if (curr->is_lock()) {
510 std::mutex * lock = (std::mutex *)curr->get_location();
511 struct std::mutex_state * state = lock->get_state();
512 if (state->islocked) {
513 //Stick the action in the appropriate waiting queue
514 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
523 * This is the heart of the model checker routine. It performs model-checking
524 * actions corresponding to a given "current action." Among other processes, it
525 * calculates reads-from relationships, updates synchronization clock vectors,
526 * forms a memory_order constraints graph, and handles replay/backtrack
527 * execution when running permutations of previously-observed executions.
529 * @param curr The current action to process
530 * @return The next Thread that must be executed. May be NULL if ModelChecker
531 * makes no choice (e.g., according to replay execution, combining RMW actions,
534 Thread * ModelChecker::check_current_action(ModelAction *curr)
538 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
540 if (!check_action_enabled(curr)) {
541 //we'll make the execution look like we chose to run this action
542 //much later...when a lock is actually available to relese
543 get_current_thread()->set_pending(curr);
544 remove_thread(get_current_thread());
545 return get_next_thread(NULL);
548 ModelAction *newcurr = initialize_curr_action(curr);
550 /* Add the action to lists before any other model-checking tasks */
551 if (!second_part_of_rmw)
552 add_action_to_lists(newcurr);
554 /* Build may_read_from set for newly-created actions */
555 if (curr == newcurr && curr->is_read())
556 build_reads_from_past(curr);
559 /* Thread specific actions */
560 switch (curr->get_type()) {
561 case THREAD_CREATE: {
562 Thread *th = (Thread *)curr->get_location();
563 th->set_creation(curr);
567 Thread *waiting, *blocking;
568 waiting = get_thread(curr);
569 blocking = (Thread *)curr->get_location();
570 if (!blocking->is_complete()) {
571 blocking->push_wait_list(curr);
572 scheduler->sleep(waiting);
574 do_complete_join(curr);
578 case THREAD_FINISH: {
579 Thread *th = get_thread(curr);
580 while (!th->wait_list_empty()) {
581 ModelAction *act = th->pop_wait_list();
582 Thread *wake = get_thread(act);
583 scheduler->wake(wake);
584 do_complete_join(act);
590 check_promises(NULL, curr->get_cv());
597 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
599 while (!work_queue.empty()) {
600 WorkQueueEntry work = work_queue.front();
601 work_queue.pop_front();
604 case WORK_CHECK_CURR_ACTION: {
605 ModelAction *act = work.action;
606 bool updated = false;
607 if (act->is_read() && process_read(act, second_part_of_rmw))
610 if (act->is_write() && process_write(act))
613 if (act->is_mutex_op())
617 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
620 case WORK_CHECK_RELEASE_SEQ:
621 resolve_release_sequences(work.location, &work_queue);
623 case WORK_CHECK_MO_EDGES: {
624 /** @todo Complete verification of work_queue */
625 ModelAction *act = work.action;
626 bool updated = false;
628 if (act->is_read()) {
629 if (r_modification_order(act, act->get_reads_from()))
632 if (act->is_write()) {
633 if (w_modification_order(act))
638 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
647 check_curr_backtracking(curr);
649 set_backtracking(curr);
651 return get_next_thread(curr);
655 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
656 * operation from the Thread it is joining with. Must be called after the
657 * completion of the Thread in question.
658 * @param join The THREAD_JOIN action
660 void ModelChecker::do_complete_join(ModelAction *join)
662 Thread *blocking = (Thread *)join->get_location();
663 ModelAction *act = get_last_action(blocking->get_id());
664 join->synchronize_with(act);
667 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
668 Node *currnode = curr->get_node();
669 Node *parnode = currnode->get_parent();
671 if ((!parnode->backtrack_empty() ||
672 !currnode->read_from_empty() ||
673 !currnode->future_value_empty() ||
674 !currnode->promise_empty())
675 && (!priv->next_backtrack ||
676 *curr > *priv->next_backtrack)) {
677 priv->next_backtrack = curr;
681 bool ModelChecker::promises_expired() {
682 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
683 Promise *promise = (*promises)[promise_index];
684 if (promise->get_expiration()<priv->used_sequence_numbers) {
691 /** @return whether the current partial trace must be a prefix of a
693 bool ModelChecker::isfeasibleprefix() {
694 return promises->size() == 0 && *lazy_sync_size == 0;
697 /** @return whether the current partial trace is feasible. */
698 bool ModelChecker::isfeasible() {
699 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
702 /** @return whether the current partial trace is feasible other than
703 * multiple RMW reading from the same store. */
704 bool ModelChecker::isfeasibleotherthanRMW() {
706 if (mo_graph->checkForCycles())
707 DEBUG("Infeasible: modification order cycles\n");
709 DEBUG("Infeasible: failed promise\n");
711 DEBUG("Infeasible: too many reads\n");
712 if (promises_expired())
713 DEBUG("Infeasible: promises expired\n");
715 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
718 /** Returns whether the current completed trace is feasible. */
719 bool ModelChecker::isfinalfeasible() {
720 if (DBG_ENABLED() && promises->size() != 0)
721 DEBUG("Infeasible: unrevolved promises\n");
723 return isfeasible() && promises->size() == 0;
726 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
727 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
728 int tid = id_to_int(act->get_tid());
729 ModelAction *lastread = get_last_action(tid);
730 lastread->process_rmw(act);
731 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
732 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
733 mo_graph->commitChanges();
739 * Checks whether a thread has read from the same write for too many times
740 * without seeing the effects of a later write.
743 * 1) there must a different write that we could read from that would satisfy the modification order,
744 * 2) we must have read from the same value in excess of maxreads times, and
745 * 3) that other write must have been in the reads_from set for maxreads times.
747 * If so, we decide that the execution is no longer feasible.
749 void ModelChecker::check_recency(ModelAction *curr) {
750 if (params.maxreads != 0) {
751 if (curr->get_node()->get_read_from_size() <= 1)
754 //Must make sure that execution is currently feasible... We could
755 //accidentally clear by rolling back
759 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
760 int tid = id_to_int(curr->get_tid());
763 if ((int)thrd_lists->size() <= tid)
766 action_list_t *list = &(*thrd_lists)[tid];
768 action_list_t::reverse_iterator rit = list->rbegin();
770 for (; (*rit) != curr; rit++)
772 /* go past curr now */
775 action_list_t::reverse_iterator ritcopy = rit;
776 //See if we have enough reads from the same value
778 for (; count < params.maxreads; rit++,count++) {
779 if (rit==list->rend())
781 ModelAction *act = *rit;
784 if (act->get_reads_from() != curr->get_reads_from())
786 if (act->get_node()->get_read_from_size() <= 1)
790 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
792 const ModelAction * write = curr->get_node()->get_read_from_at(i);
793 //Need a different write
794 if (write==curr->get_reads_from())
797 /* Test to see whether this is a feasible write to read from*/
798 mo_graph->startChanges();
799 r_modification_order(curr, write);
800 bool feasiblereadfrom = isfeasible();
801 mo_graph->rollbackChanges();
803 if (!feasiblereadfrom)
807 bool feasiblewrite = true;
808 //new we need to see if this write works for everyone
810 for (int loop = count; loop>0; loop--,rit++) {
811 ModelAction *act=*rit;
812 bool foundvalue = false;
813 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
814 if (act->get_node()->get_read_from_at(i)==write) {
820 feasiblewrite = false;
825 too_many_reads = true;
833 * Updates the mo_graph with the constraints imposed from the current
836 * Basic idea is the following: Go through each other thread and find
837 * the lastest action that happened before our read. Two cases:
839 * (1) The action is a write => that write must either occur before
840 * the write we read from or be the write we read from.
842 * (2) The action is a read => the write that that action read from
843 * must occur before the write we read from or be the same write.
845 * @param curr The current action. Must be a read.
846 * @param rf The action that curr reads from. Must be a write.
847 * @return True if modification order edges were added; false otherwise
849 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
851 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
854 ASSERT(curr->is_read());
856 /* Iterate over all threads */
857 for (i = 0; i < thrd_lists->size(); i++) {
858 /* Iterate over actions in thread, starting from most recent */
859 action_list_t *list = &(*thrd_lists)[i];
860 action_list_t::reverse_iterator rit;
861 for (rit = list->rbegin(); rit != list->rend(); rit++) {
862 ModelAction *act = *rit;
865 * Include at most one act per-thread that "happens
866 * before" curr. Don't consider reflexively.
868 if (act->happens_before(curr) && act != curr) {
869 if (act->is_write()) {
871 mo_graph->addEdge(act, rf);
875 const ModelAction *prevreadfrom = act->get_reads_from();
876 if (prevreadfrom != NULL && rf != prevreadfrom) {
877 mo_graph->addEdge(prevreadfrom, rf);
889 /** This method fixes up the modification order when we resolve a
890 * promises. The basic problem is that actions that occur after the
891 * read curr could not property add items to the modification order
894 * So for each thread, we find the earliest item that happens after
895 * the read curr. This is the item we have to fix up with additional
896 * constraints. If that action is write, we add a MO edge between
897 * the Action rf and that action. If the action is a read, we add a
898 * MO edge between the Action rf, and whatever the read accessed.
900 * @param curr is the read ModelAction that we are fixing up MO edges for.
901 * @param rf is the write ModelAction that curr reads from.
905 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
907 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
909 ASSERT(curr->is_read());
911 /* Iterate over all threads */
912 for (i = 0; i < thrd_lists->size(); i++) {
913 /* Iterate over actions in thread, starting from most recent */
914 action_list_t *list = &(*thrd_lists)[i];
915 action_list_t::reverse_iterator rit;
916 ModelAction *lastact = NULL;
918 /* Find last action that happens after curr */
919 for (rit = list->rbegin(); rit != list->rend(); rit++) {
920 ModelAction *act = *rit;
921 if (curr->happens_before(act)) {
927 /* Include at most one act per-thread that "happens before" curr */
928 if (lastact != NULL) {
929 if (lastact->is_read()) {
930 const ModelAction *postreadfrom = lastact->get_reads_from();
931 if (postreadfrom != NULL&&rf != postreadfrom)
932 mo_graph->addEdge(rf, postreadfrom);
933 } else if (rf != lastact) {
934 mo_graph->addEdge(rf, lastact);
942 * Updates the mo_graph with the constraints imposed from the current write.
944 * Basic idea is the following: Go through each other thread and find
945 * the lastest action that happened before our write. Two cases:
947 * (1) The action is a write => that write must occur before
950 * (2) The action is a read => the write that that action read from
951 * must occur before the current write.
953 * This method also handles two other issues:
955 * (I) Sequential Consistency: Making sure that if the current write is
956 * seq_cst, that it occurs after the previous seq_cst write.
958 * (II) Sending the write back to non-synchronizing reads.
960 * @param curr The current action. Must be a write.
961 * @return True if modification order edges were added; false otherwise
963 bool ModelChecker::w_modification_order(ModelAction *curr)
965 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
968 ASSERT(curr->is_write());
970 if (curr->is_seqcst()) {
971 /* We have to at least see the last sequentially consistent write,
972 so we are initialized. */
973 ModelAction *last_seq_cst = get_last_seq_cst(curr);
974 if (last_seq_cst != NULL) {
975 mo_graph->addEdge(last_seq_cst, curr);
980 /* Iterate over all threads */
981 for (i = 0; i < thrd_lists->size(); i++) {
982 /* Iterate over actions in thread, starting from most recent */
983 action_list_t *list = &(*thrd_lists)[i];
984 action_list_t::reverse_iterator rit;
985 for (rit = list->rbegin(); rit != list->rend(); rit++) {
986 ModelAction *act = *rit;
989 * If RMW, we already have all relevant edges,
990 * so just skip to next thread.
991 * If normal write, we need to look at earlier
992 * actions, so continue processing list.
1001 * Include at most one act per-thread that "happens
1004 if (act->happens_before(curr)) {
1006 * Note: if act is RMW, just add edge:
1008 * The following edge should be handled elsewhere:
1009 * readfrom(act) --mo--> act
1011 if (act->is_write())
1012 mo_graph->addEdge(act, curr);
1013 else if (act->is_read() && act->get_reads_from() != NULL)
1014 mo_graph->addEdge(act->get_reads_from(), curr);
1017 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1018 !act->same_thread(curr)) {
1019 /* We have an action that:
1020 (1) did not happen before us
1021 (2) is a read and we are a write
1022 (3) cannot synchronize with us
1023 (4) is in a different thread
1025 that read could potentially read from our write.
1027 if (thin_air_constraint_may_allow(curr, act)) {
1029 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1030 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1031 futurevalues->push_back(pfv);
1041 /** Arbitrary reads from the future are not allowed. Section 29.3
1042 * part 9 places some constraints. This method checks one result of constraint
1043 * constraint. Others require compiler support. */
1045 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1046 if (!writer->is_rmw())
1049 if (!reader->is_rmw())
1052 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1053 if (search == reader)
1055 if (search->get_tid() == reader->get_tid() &&
1056 search->happens_before(reader))
1064 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1065 * The ModelAction under consideration is expected to be taking part in
1066 * release/acquire synchronization as an object of the "reads from" relation.
1067 * Note that this can only provide release sequence support for RMW chains
1068 * which do not read from the future, as those actions cannot be traced until
1069 * their "promise" is fulfilled. Similarly, we may not even establish the
1070 * presence of a release sequence with certainty, as some modification order
1071 * constraints may be decided further in the future. Thus, this function
1072 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1073 * and a boolean representing certainty.
1075 * @todo Finish lazy updating, when promises are fulfilled in the future
1076 * @param rf The action that might be part of a release sequence. Must be a
1078 * @param release_heads A pass-by-reference style return parameter. After
1079 * execution of this function, release_heads will contain the heads of all the
1080 * relevant release sequences, if any exists
1081 * @return true, if the ModelChecker is certain that release_heads is complete;
1084 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1087 /* read from future: need to settle this later */
1088 return false; /* incomplete */
1091 ASSERT(rf->is_write());
1093 if (rf->is_release())
1094 release_heads->push_back(rf);
1096 /* We need a RMW action that is both an acquire and release to stop */
1097 /** @todo Need to be smarter here... In the linux lock
1098 * example, this will run to the beginning of the program for
1100 if (rf->is_acquire() && rf->is_release())
1101 return true; /* complete */
1102 return release_seq_head(rf->get_reads_from(), release_heads);
1104 if (rf->is_release())
1105 return true; /* complete */
1107 /* else relaxed write; check modification order for contiguous subsequence
1108 * -> rf must be same thread as release */
1109 int tid = id_to_int(rf->get_tid());
1110 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1111 action_list_t *list = &(*thrd_lists)[tid];
1112 action_list_t::const_reverse_iterator rit;
1114 /* Find rf in the thread list */
1115 rit = std::find(list->rbegin(), list->rend(), rf);
1116 ASSERT(rit != list->rend());
1118 /* Find the last write/release */
1119 for (; rit != list->rend(); rit++)
1120 if ((*rit)->is_release())
1122 if (rit == list->rend()) {
1123 /* No write-release in this thread */
1124 return true; /* complete */
1126 ModelAction *release = *rit;
1128 ASSERT(rf->same_thread(release));
1130 bool certain = true;
1131 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1132 if (id_to_int(rf->get_tid()) == (int)i)
1134 list = &(*thrd_lists)[i];
1136 /* Can we ensure no future writes from this thread may break
1137 * the release seq? */
1138 bool future_ordered = false;
1140 ModelAction *last = get_last_action(int_to_id(i));
1141 if (last && rf->happens_before(last))
1142 future_ordered = true;
1144 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1145 const ModelAction *act = *rit;
1146 /* Reach synchronization -> this thread is complete */
1147 if (act->happens_before(release))
1149 if (rf->happens_before(act)) {
1150 future_ordered = true;
1154 /* Only writes can break release sequences */
1155 if (!act->is_write())
1158 /* Check modification order */
1159 if (mo_graph->checkReachable(rf, act)) {
1160 /* rf --mo--> act */
1161 future_ordered = true;
1164 if (mo_graph->checkReachable(act, release))
1165 /* act --mo--> release */
1167 if (mo_graph->checkReachable(release, act) &&
1168 mo_graph->checkReachable(act, rf)) {
1169 /* release --mo-> act --mo--> rf */
1170 return true; /* complete */
1174 if (!future_ordered)
1175 return false; /* This thread is uncertain */
1179 release_heads->push_back(release);
1184 * A public interface for getting the release sequence head(s) with which a
1185 * given ModelAction must synchronize. This function only returns a non-empty
1186 * result when it can locate a release sequence head with certainty. Otherwise,
1187 * it may mark the internal state of the ModelChecker so that it will handle
1188 * the release sequence at a later time, causing @a act to update its
1189 * synchronization at some later point in execution.
1190 * @param act The 'acquire' action that may read from a release sequence
1191 * @param release_heads A pass-by-reference return parameter. Will be filled
1192 * with the head(s) of the release sequence(s), if they exists with certainty.
1193 * @see ModelChecker::release_seq_head
1195 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1197 const ModelAction *rf = act->get_reads_from();
1199 complete = release_seq_head(rf, release_heads);
1201 /* add act to 'lazy checking' list */
1202 action_list_t *list;
1203 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1204 list->push_back(act);
1205 (*lazy_sync_size)++;
1210 * Attempt to resolve all stashed operations that might synchronize with a
1211 * release sequence for a given location. This implements the "lazy" portion of
1212 * determining whether or not a release sequence was contiguous, since not all
1213 * modification order information is present at the time an action occurs.
1215 * @param location The location/object that should be checked for release
1216 * sequence resolutions
1217 * @param work_queue The work queue to which to add work items as they are
1219 * @return True if any updates occurred (new synchronization, new mo_graph
1222 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1224 action_list_t *list;
1225 list = lazy_sync_with_release->getptr(location);
1229 bool updated = false;
1230 action_list_t::iterator it = list->begin();
1231 while (it != list->end()) {
1232 ModelAction *act = *it;
1233 const ModelAction *rf = act->get_reads_from();
1234 rel_heads_list_t release_heads;
1236 complete = release_seq_head(rf, &release_heads);
1237 for (unsigned int i = 0; i < release_heads.size(); i++) {
1238 if (!act->has_synchronized_with(release_heads[i])) {
1240 act->synchronize_with(release_heads[i]);
1245 /* Re-check act for mo_graph edges */
1246 work_queue->push_back(MOEdgeWorkEntry(act));
1248 /* propagate synchronization to later actions */
1249 action_list_t::reverse_iterator it = action_trace->rbegin();
1250 for (; (*it) != act; it++) {
1251 ModelAction *propagate = *it;
1252 if (act->happens_before(propagate)) {
1253 propagate->synchronize_with(act);
1254 /* Re-check 'propagate' for mo_graph edges */
1255 work_queue->push_back(MOEdgeWorkEntry(propagate));
1260 it = list->erase(it);
1261 (*lazy_sync_size)--;
1266 // If we resolved promises or data races, see if we have realized a data race.
1267 if (checkDataRaces()) {
1275 * Performs various bookkeeping operations for the current ModelAction. For
1276 * instance, adds action to the per-object, per-thread action vector and to the
1277 * action trace list of all thread actions.
1279 * @param act is the ModelAction to add.
1281 void ModelChecker::add_action_to_lists(ModelAction *act)
1283 int tid = id_to_int(act->get_tid());
1284 action_trace->push_back(act);
1286 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1288 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1289 if (tid >= (int)vec->size())
1290 vec->resize(priv->next_thread_id);
1291 (*vec)[tid].push_back(act);
1293 if ((int)thrd_last_action->size() <= tid)
1294 thrd_last_action->resize(get_num_threads());
1295 (*thrd_last_action)[tid] = act;
1299 * @brief Get the last action performed by a particular Thread
1300 * @param tid The thread ID of the Thread in question
1301 * @return The last action in the thread
1303 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1305 int threadid = id_to_int(tid);
1306 if (threadid < (int)thrd_last_action->size())
1307 return (*thrd_last_action)[id_to_int(tid)];
1313 * Gets the last memory_order_seq_cst write (in the total global sequence)
1314 * performed on a particular object (i.e., memory location), not including the
1316 * @param curr The current ModelAction; also denotes the object location to
1318 * @return The last seq_cst write
1320 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1322 void *location = curr->get_location();
1323 action_list_t *list = obj_map->get_safe_ptr(location);
1324 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1325 action_list_t::reverse_iterator rit;
1326 for (rit = list->rbegin(); rit != list->rend(); rit++)
1327 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1333 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1334 * location). This function identifies the mutex according to the current
1335 * action, which is presumed to perform on the same mutex.
1336 * @param curr The current ModelAction; also denotes the object location to
1338 * @return The last unlock operation
1340 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1342 void *location = curr->get_location();
1343 action_list_t *list = obj_map->get_safe_ptr(location);
1344 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1345 action_list_t::reverse_iterator rit;
1346 for (rit = list->rbegin(); rit != list->rend(); rit++)
1347 if ((*rit)->is_unlock())
1352 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1354 ModelAction *parent = get_last_action(tid);
1356 parent = get_thread(tid)->get_creation();
1361 * Returns the clock vector for a given thread.
1362 * @param tid The thread whose clock vector we want
1363 * @return Desired clock vector
1365 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1367 return get_parent_action(tid)->get_cv();
1371 * Resolve a set of Promises with a current write. The set is provided in the
1372 * Node corresponding to @a write.
1373 * @param write The ModelAction that is fulfilling Promises
1374 * @return True if promises were resolved; false otherwise
1376 bool ModelChecker::resolve_promises(ModelAction *write)
1378 bool resolved = false;
1380 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1381 Promise *promise = (*promises)[promise_index];
1382 if (write->get_node()->get_promise(i)) {
1383 ModelAction *read = promise->get_action();
1384 read->read_from(write);
1385 if (read->is_rmw()) {
1386 mo_graph->addRMWEdge(write, read);
1388 //First fix up the modification order for actions that happened
1390 r_modification_order(read, write);
1391 //Next fix up the modification order for actions that happened
1393 post_r_modification_order(read, write);
1394 promises->erase(promises->begin() + promise_index);
1403 * Compute the set of promises that could potentially be satisfied by this
1404 * action. Note that the set computation actually appears in the Node, not in
1406 * @param curr The ModelAction that may satisfy promises
1408 void ModelChecker::compute_promises(ModelAction *curr)
1410 for (unsigned int i = 0; i < promises->size(); i++) {
1411 Promise *promise = (*promises)[i];
1412 const ModelAction *act = promise->get_action();
1413 if (!act->happens_before(curr) &&
1415 !act->is_synchronizing(curr) &&
1416 !act->same_thread(curr) &&
1417 promise->get_value() == curr->get_value()) {
1418 curr->get_node()->set_promise(i);
1423 /** Checks promises in response to change in ClockVector Threads. */
1424 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1426 for (unsigned int i = 0; i < promises->size(); i++) {
1427 Promise *promise = (*promises)[i];
1428 const ModelAction *act = promise->get_action();
1429 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1430 merge_cv->synchronized_since(act)) {
1431 //This thread is no longer able to send values back to satisfy the promise
1432 int num_synchronized_threads = promise->increment_threads();
1433 if (num_synchronized_threads == get_num_threads()) {
1434 //Promise has failed
1435 failed_promise = true;
1443 * Build up an initial set of all past writes that this 'read' action may read
1444 * from. This set is determined by the clock vector's "happens before"
1446 * @param curr is the current ModelAction that we are exploring; it must be a
1449 void ModelChecker::build_reads_from_past(ModelAction *curr)
1451 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1453 ASSERT(curr->is_read());
1455 ModelAction *last_seq_cst = NULL;
1457 /* Track whether this object has been initialized */
1458 bool initialized = false;
1460 if (curr->is_seqcst()) {
1461 last_seq_cst = get_last_seq_cst(curr);
1462 /* We have to at least see the last sequentially consistent write,
1463 so we are initialized. */
1464 if (last_seq_cst != NULL)
1468 /* Iterate over all threads */
1469 for (i = 0; i < thrd_lists->size(); i++) {
1470 /* Iterate over actions in thread, starting from most recent */
1471 action_list_t *list = &(*thrd_lists)[i];
1472 action_list_t::reverse_iterator rit;
1473 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1474 ModelAction *act = *rit;
1476 /* Only consider 'write' actions */
1477 if (!act->is_write() || act == curr)
1480 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1481 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1482 DEBUG("Adding action to may_read_from:\n");
1483 if (DBG_ENABLED()) {
1487 curr->get_node()->add_read_from(act);
1490 /* Include at most one act per-thread that "happens before" curr */
1491 if (act->happens_before(curr)) {
1499 /** @todo Need a more informative way of reporting errors. */
1500 printf("ERROR: may read from uninitialized atomic\n");
1503 if (DBG_ENABLED() || !initialized) {
1504 printf("Reached read action:\n");
1506 printf("Printing may_read_from\n");
1507 curr->get_node()->print_may_read_from();
1508 printf("End printing may_read_from\n");
1511 ASSERT(initialized);
1514 static void print_list(action_list_t *list)
1516 action_list_t::iterator it;
1518 printf("---------------------------------------------------------------------\n");
1521 for (it = list->begin(); it != list->end(); it++) {
1524 printf("---------------------------------------------------------------------\n");
1527 void ModelChecker::print_summary()
1530 printf("Number of executions: %d\n", num_executions);
1531 printf("Number of feasible executions: %d\n", num_feasible_executions);
1532 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1534 #if SUPPORT_MOD_ORDER_DUMP
1536 char buffername[100];
1537 sprintf(buffername, "exec%04u", num_executions);
1538 mo_graph->dumpGraphToFile(buffername);
1541 if (!isfinalfeasible())
1542 printf("INFEASIBLE EXECUTION!\n");
1543 print_list(action_trace);
1548 * Add a Thread to the system for the first time. Should only be called once
1550 * @param t The Thread to add
1552 void ModelChecker::add_thread(Thread *t)
1554 thread_map->put(id_to_int(t->get_id()), t);
1555 scheduler->add_thread(t);
1559 * Removes a thread from the scheduler.
1560 * @param the thread to remove.
1563 void ModelChecker::remove_thread(Thread *t)
1565 scheduler->remove_thread(t);
1569 * Switch from a user-context to the "master thread" context (a.k.a. system
1570 * context). This switch is made with the intention of exploring a particular
1571 * model-checking action (described by a ModelAction object). Must be called
1572 * from a user-thread context.
1573 * @param act The current action that will be explored. Must not be NULL.
1574 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1576 int ModelChecker::switch_to_master(ModelAction *act)
1579 Thread *old = thread_current();
1580 set_current_action(act);
1581 old->set_state(THREAD_READY);
1582 return Thread::swap(old, &system_context);
1586 * Takes the next step in the execution, if possible.
1587 * @return Returns true (success) if a step was taken and false otherwise.
1589 bool ModelChecker::take_step() {
1593 Thread * curr = thread_current();
1595 if (curr->get_state() == THREAD_READY) {
1596 ASSERT(priv->current_action);
1598 priv->nextThread = check_current_action(priv->current_action);
1599 priv->current_action = NULL;
1600 if (curr->is_blocked() || curr->is_complete())
1601 scheduler->remove_thread(curr);
1606 Thread * next = scheduler->next_thread(priv->nextThread);
1608 /* Infeasible -> don't take any more steps */
1613 next->set_state(THREAD_RUNNING);
1614 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1616 /* next == NULL -> don't take any more steps */
1620 if ( next->get_pending() != NULL ) {
1621 //restart a pending action
1622 set_current_action(next->get_pending());
1623 next->set_pending(NULL);
1624 next->set_state(THREAD_READY);
1628 /* Return false only if swap fails with an error */
1629 return (Thread::swap(&system_context, next) == 0);
1632 /** Runs the current execution until threre are no more steps to take. */
1633 void ModelChecker::finish_execution() {
1636 while (take_step());