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 earliest_diverge(NULL),
29 action_trace(new action_list_t()),
30 thread_map(new HashTable<int, Thread *, int>()),
31 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
34 promises(new std::vector<Promise *>()),
35 futurevalues(new std::vector<struct PendingFutureValue>()),
36 pending_acq_rel_seq(new std::vector<ModelAction *>()),
37 thrd_last_action(new std::vector<ModelAction *>(1)),
38 node_stack(new NodeStack()),
39 mo_graph(new CycleGraph()),
40 failed_promise(false),
41 too_many_reads(false),
43 bad_synchronization(false)
45 /* Allocate this "size" on the snapshotting heap */
46 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
47 /* First thread created will have id INITIAL_THREAD_ID */
48 priv->next_thread_id = INITIAL_THREAD_ID;
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 pending_acq_rel_seq;
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;
85 bad_synchronization = false;
87 snapshotObject->backTrackBeforeStep(0);
90 /** @return a thread ID for a new Thread */
91 thread_id_t ModelChecker::get_next_id()
93 return priv->next_thread_id++;
96 /** @return the number of user threads created during this execution */
97 int ModelChecker::get_num_threads()
99 return priv->next_thread_id;
102 /** @return The currently executing Thread. */
103 Thread * ModelChecker::get_current_thread()
105 return scheduler->get_current_thread();
108 /** @return a sequence number for a new ModelAction */
109 modelclock_t ModelChecker::get_next_seq_num()
111 return ++priv->used_sequence_numbers;
115 * @brief Choose the next thread to execute.
117 * This function chooses the next thread that should execute. It can force the
118 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
119 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
120 * The model-checker may have no preference regarding the next thread (i.e.,
121 * when exploring a new execution ordering), in which case this will return
123 * @param curr The current ModelAction. This action might guide the choice of
125 * @return The next thread to run. If the model-checker has no preference, NULL.
127 Thread * ModelChecker::get_next_thread(ModelAction *curr)
132 /* Do not split atomic actions. */
134 return thread_current();
135 /* The THREAD_CREATE action points to the created Thread */
136 else if (curr->get_type() == THREAD_CREATE)
137 return (Thread *)curr->get_location();
140 /* Have we completed exploring the preselected path? */
144 /* Else, we are trying to replay an execution */
145 ModelAction *next = node_stack->get_next()->get_action();
147 if (next == diverge) {
148 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
149 earliest_diverge=diverge;
151 Node *nextnode = next->get_node();
152 /* Reached divergence point */
153 if (nextnode->increment_promise()) {
154 /* The next node will try to satisfy a different set of promises. */
155 tid = next->get_tid();
156 node_stack->pop_restofstack(2);
157 } else if (nextnode->increment_read_from()) {
158 /* The next node will read from a different value. */
159 tid = next->get_tid();
160 node_stack->pop_restofstack(2);
161 } else if (nextnode->increment_future_value()) {
162 /* The next node will try to read from a different future value. */
163 tid = next->get_tid();
164 node_stack->pop_restofstack(2);
166 /* Make a different thread execute for next step */
167 Node *node = nextnode->get_parent();
168 tid = node->get_next_backtrack();
169 node_stack->pop_restofstack(1);
170 if (diverge==earliest_diverge) {
171 earliest_diverge=node->get_action();
174 DEBUG("*** Divergence point ***\n");
178 tid = next->get_tid();
180 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
181 ASSERT(tid != THREAD_ID_T_NONE);
182 return thread_map->get(id_to_int(tid));
186 * Queries the model-checker for more executions to explore and, if one
187 * exists, resets the model-checker state to execute a new execution.
189 * @return If there are more executions to explore, return true. Otherwise,
192 bool ModelChecker::next_execution()
198 if (isfinalfeasible()) {
199 printf("Earliest divergence point since last feasible execution:\n");
200 if (earliest_diverge)
201 earliest_diverge->print(false);
203 printf("(Not set)\n");
205 earliest_diverge = NULL;
206 num_feasible_executions++;
209 DEBUG("Number of acquires waiting on pending release sequences: %lu\n",
210 pending_acq_rel_seq->size());
212 if (isfinalfeasible() || DBG_ENABLED())
215 if ((diverge = get_next_backtrack()) == NULL)
219 printf("Next execution will diverge at:\n");
223 reset_to_initial_state();
227 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
229 switch (act->get_type()) {
233 /* linear search: from most recent to oldest */
234 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
235 action_list_t::reverse_iterator rit;
236 for (rit = list->rbegin(); rit != list->rend(); rit++) {
237 ModelAction *prev = *rit;
238 if (act->is_synchronizing(prev))
244 case ATOMIC_TRYLOCK: {
245 /* linear search: from most recent to oldest */
246 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
247 action_list_t::reverse_iterator rit;
248 for (rit = list->rbegin(); rit != list->rend(); rit++) {
249 ModelAction *prev = *rit;
250 if (act->is_conflicting_lock(prev))
255 case ATOMIC_UNLOCK: {
256 /* linear search: from most recent to oldest */
257 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
258 action_list_t::reverse_iterator rit;
259 for (rit = list->rbegin(); rit != list->rend(); rit++) {
260 ModelAction *prev = *rit;
261 if (!act->same_thread(prev)&&prev->is_failed_trylock())
272 /** This method find backtracking points where we should try to
273 * reorder the parameter ModelAction against.
275 * @param the ModelAction to find backtracking points for.
277 void ModelChecker::set_backtracking(ModelAction *act)
279 Thread *t = get_thread(act);
280 ModelAction * prev = get_last_conflict(act);
284 Node * node = prev->get_node()->get_parent();
286 int low_tid, high_tid;
287 if (node->is_enabled(t)) {
288 low_tid = id_to_int(act->get_tid());
289 high_tid = low_tid+1;
292 high_tid = get_num_threads();
295 for(int i = low_tid; i < high_tid; i++) {
296 thread_id_t tid = int_to_id(i);
297 if (!node->is_enabled(tid))
300 /* Check if this has been explored already */
301 if (node->has_been_explored(tid))
304 /* See if fairness allows */
305 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
307 for(int t=0;t<node->get_num_threads();t++) {
308 thread_id_t tother=int_to_id(t);
309 if (node->is_enabled(tother) && node->has_priority(tother)) {
318 /* Cache the latest backtracking point */
319 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
320 priv->next_backtrack = prev;
322 /* If this is a new backtracking point, mark the tree */
323 if (!node->set_backtrack(tid))
325 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
326 prev->get_tid(), t->get_id());
335 * Returns last backtracking point. The model checker will explore a different
336 * path for this point in the next execution.
337 * @return The ModelAction at which the next execution should diverge.
339 ModelAction * ModelChecker::get_next_backtrack()
341 ModelAction *next = priv->next_backtrack;
342 priv->next_backtrack = NULL;
347 * Processes a read or rmw model action.
348 * @param curr is the read model action to process.
349 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
350 * @return True if processing this read updates the mo_graph.
352 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
355 bool updated = false;
357 const ModelAction *reads_from = curr->get_node()->get_read_from();
358 if (reads_from != NULL) {
359 mo_graph->startChanges();
361 value = reads_from->get_value();
362 bool r_status = false;
364 if (!second_part_of_rmw) {
365 check_recency(curr, reads_from);
366 r_status = r_modification_order(curr, reads_from);
370 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
371 mo_graph->rollbackChanges();
372 too_many_reads = false;
376 curr->read_from(reads_from);
377 mo_graph->commitChanges();
379 } else if (!second_part_of_rmw) {
380 /* Read from future value */
381 value = curr->get_node()->get_future_value();
382 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
383 curr->read_from(NULL);
384 Promise *valuepromise = new Promise(curr, value, expiration);
385 promises->push_back(valuepromise);
387 get_thread(curr)->set_return_value(value);
393 * Processes a lock, trylock, or unlock model action. @param curr is
394 * the read model action to process.
396 * The try lock operation checks whether the lock is taken. If not,
397 * it falls to the normal lock operation case. If so, it returns
400 * The lock operation has already been checked that it is enabled, so
401 * it just grabs the lock and synchronizes with the previous unlock.
403 * The unlock operation has to re-enable all of the threads that are
404 * waiting on the lock.
406 * @return True if synchronization was updated; false otherwise
408 bool ModelChecker::process_mutex(ModelAction *curr) {
409 std::mutex *mutex = (std::mutex *)curr->get_location();
410 struct std::mutex_state *state = mutex->get_state();
411 switch (curr->get_type()) {
412 case ATOMIC_TRYLOCK: {
413 bool success = !state->islocked;
414 curr->set_try_lock(success);
416 get_thread(curr)->set_return_value(0);
419 get_thread(curr)->set_return_value(1);
421 //otherwise fall into the lock case
423 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
424 printf("Lock access before initialization\n");
427 state->islocked = true;
428 ModelAction *unlock = get_last_unlock(curr);
429 //synchronize with the previous unlock statement
430 if (unlock != NULL) {
431 curr->synchronize_with(unlock);
436 case ATOMIC_UNLOCK: {
438 state->islocked = false;
439 //wake up the other threads
440 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
441 //activate all the waiting threads
442 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
443 scheduler->wake(get_thread(*rit));
455 * Process a write ModelAction
456 * @param curr The ModelAction to process
457 * @return True if the mo_graph was updated or promises were resolved
459 bool ModelChecker::process_write(ModelAction *curr)
461 bool updated_mod_order = w_modification_order(curr);
462 bool updated_promises = resolve_promises(curr);
464 if (promises->size() == 0) {
465 for (unsigned int i = 0; i < futurevalues->size(); i++) {
466 struct PendingFutureValue pfv = (*futurevalues)[i];
467 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
468 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
469 priv->next_backtrack = pfv.act;
471 futurevalues->resize(0);
474 mo_graph->commitChanges();
475 get_thread(curr)->set_return_value(VALUE_NONE);
476 return updated_mod_order || updated_promises;
480 * @brief Process the current action for thread-related activity
482 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
483 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
484 * synchronization, etc. This function is a no-op for non-THREAD actions
485 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
487 * @param curr The current action
488 * @return True if synchronization was updated or a thread completed
490 bool ModelChecker::process_thread_action(ModelAction *curr)
492 bool updated = false;
494 switch (curr->get_type()) {
495 case THREAD_CREATE: {
496 Thread *th = (Thread *)curr->get_location();
497 th->set_creation(curr);
501 Thread *waiting, *blocking;
502 waiting = get_thread(curr);
503 blocking = (Thread *)curr->get_location();
504 if (!blocking->is_complete()) {
505 blocking->push_wait_list(curr);
506 scheduler->sleep(waiting);
508 do_complete_join(curr);
509 updated = true; /* trigger rel-seq checks */
513 case THREAD_FINISH: {
514 Thread *th = get_thread(curr);
515 while (!th->wait_list_empty()) {
516 ModelAction *act = th->pop_wait_list();
517 Thread *wake = get_thread(act);
518 scheduler->wake(wake);
519 do_complete_join(act);
520 updated = true; /* trigger rel-seq checks */
523 updated = true; /* trigger rel-seq checks */
527 check_promises(NULL, curr->get_cv());
538 * Initialize the current action by performing one or more of the following
539 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
540 * in the NodeStack, manipulating backtracking sets, allocating and
541 * initializing clock vectors, and computing the promises to fulfill.
543 * @param curr The current action, as passed from the user context; may be
544 * freed/invalidated after the execution of this function
545 * @return The current action, as processed by the ModelChecker. Is only the
546 * same as the parameter @a curr if this is a newly-explored action.
548 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
550 ModelAction *newcurr;
552 if (curr->is_rmwc() || curr->is_rmw()) {
553 newcurr = process_rmw(curr);
556 if (newcurr->is_rmw())
557 compute_promises(newcurr);
561 curr->set_seq_number(get_next_seq_num());
563 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
565 /* First restore type and order in case of RMW operation */
567 newcurr->copy_typeandorder(curr);
569 ASSERT(curr->get_location() == newcurr->get_location());
570 newcurr->copy_from_new(curr);
572 /* Discard duplicate ModelAction; use action from NodeStack */
575 /* Always compute new clock vector */
576 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
580 /* Always compute new clock vector */
581 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
583 * Perform one-time actions when pushing new ModelAction onto
586 if (newcurr->is_write())
587 compute_promises(newcurr);
593 * This method checks whether a model action is enabled at the given point.
594 * At this point, it checks whether a lock operation would be successful at this point.
595 * If not, it puts the thread in a waiter list.
596 * @param curr is the ModelAction to check whether it is enabled.
597 * @return a bool that indicates whether the action is enabled.
599 bool ModelChecker::check_action_enabled(ModelAction *curr) {
600 if (curr->is_lock()) {
601 std::mutex * lock = (std::mutex *)curr->get_location();
602 struct std::mutex_state * state = lock->get_state();
603 if (state->islocked) {
604 //Stick the action in the appropriate waiting queue
605 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
614 * This is the heart of the model checker routine. It performs model-checking
615 * actions corresponding to a given "current action." Among other processes, it
616 * calculates reads-from relationships, updates synchronization clock vectors,
617 * forms a memory_order constraints graph, and handles replay/backtrack
618 * execution when running permutations of previously-observed executions.
620 * @param curr The current action to process
621 * @return The next Thread that must be executed. May be NULL if ModelChecker
622 * makes no choice (e.g., according to replay execution, combining RMW actions,
625 Thread * ModelChecker::check_current_action(ModelAction *curr)
629 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
631 if (!check_action_enabled(curr)) {
632 /* Make the execution look like we chose to run this action
633 * much later, when a lock is actually available to release */
634 get_current_thread()->set_pending(curr);
635 scheduler->sleep(get_current_thread());
636 return get_next_thread(NULL);
639 ModelAction *newcurr = initialize_curr_action(curr);
641 /* Add the action to lists before any other model-checking tasks */
642 if (!second_part_of_rmw)
643 add_action_to_lists(newcurr);
645 /* Build may_read_from set for newly-created actions */
646 if (curr == newcurr && curr->is_read())
647 build_reads_from_past(curr);
650 /* Initialize work_queue with the "current action" work */
651 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
653 while (!work_queue.empty()) {
654 WorkQueueEntry work = work_queue.front();
655 work_queue.pop_front();
658 case WORK_CHECK_CURR_ACTION: {
659 ModelAction *act = work.action;
660 bool update = false; /* update this location's release seq's */
661 bool update_all = false; /* update all release seq's */
663 if (process_thread_action(curr))
666 if (act->is_read() && process_read(act, second_part_of_rmw))
669 if (act->is_write() && process_write(act))
672 if (act->is_mutex_op() && process_mutex(act))
676 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
678 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
681 case WORK_CHECK_RELEASE_SEQ:
682 resolve_release_sequences(work.location, &work_queue);
684 case WORK_CHECK_MO_EDGES: {
685 /** @todo Complete verification of work_queue */
686 ModelAction *act = work.action;
687 bool updated = false;
689 if (act->is_read()) {
690 const ModelAction *rf = act->get_reads_from();
691 if (rf != NULL && r_modification_order(act, rf))
694 if (act->is_write()) {
695 if (w_modification_order(act))
698 mo_graph->commitChanges();
701 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
710 check_curr_backtracking(curr);
712 set_backtracking(curr);
714 return get_next_thread(curr);
718 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
719 * operation from the Thread it is joining with. Must be called after the
720 * completion of the Thread in question.
721 * @param join The THREAD_JOIN action
723 void ModelChecker::do_complete_join(ModelAction *join)
725 Thread *blocking = (Thread *)join->get_location();
726 ModelAction *act = get_last_action(blocking->get_id());
727 join->synchronize_with(act);
730 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
731 Node *currnode = curr->get_node();
732 Node *parnode = currnode->get_parent();
734 if ((!parnode->backtrack_empty() ||
735 !currnode->read_from_empty() ||
736 !currnode->future_value_empty() ||
737 !currnode->promise_empty())
738 && (!priv->next_backtrack ||
739 *curr > *priv->next_backtrack)) {
740 priv->next_backtrack = curr;
744 bool ModelChecker::promises_expired() {
745 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
746 Promise *promise = (*promises)[promise_index];
747 if (promise->get_expiration()<priv->used_sequence_numbers) {
754 /** @return whether the current partial trace must be a prefix of a
756 bool ModelChecker::isfeasibleprefix() {
757 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
760 /** @return whether the current partial trace is feasible. */
761 bool ModelChecker::isfeasible() {
762 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
763 DEBUG("Infeasible: RMW violation\n");
765 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
768 /** @return whether the current partial trace is feasible other than
769 * multiple RMW reading from the same store. */
770 bool ModelChecker::isfeasibleotherthanRMW() {
772 if (mo_graph->checkForCycles())
773 DEBUG("Infeasible: modification order cycles\n");
775 DEBUG("Infeasible: failed promise\n");
777 DEBUG("Infeasible: too many reads\n");
778 if (bad_synchronization)
779 DEBUG("Infeasible: bad synchronization ordering\n");
780 if (promises_expired())
781 DEBUG("Infeasible: promises expired\n");
783 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
786 /** Returns whether the current completed trace is feasible. */
787 bool ModelChecker::isfinalfeasible() {
788 if (DBG_ENABLED() && promises->size() != 0)
789 DEBUG("Infeasible: unrevolved promises\n");
791 return isfeasible() && promises->size() == 0;
794 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
795 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
796 int tid = id_to_int(act->get_tid());
797 ModelAction *lastread = get_last_action(tid);
798 lastread->process_rmw(act);
799 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
800 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
801 mo_graph->commitChanges();
807 * Checks whether a thread has read from the same write for too many times
808 * without seeing the effects of a later write.
811 * 1) there must a different write that we could read from that would satisfy the modification order,
812 * 2) we must have read from the same value in excess of maxreads times, and
813 * 3) that other write must have been in the reads_from set for maxreads times.
815 * If so, we decide that the execution is no longer feasible.
817 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
818 if (params.maxreads != 0) {
820 if (curr->get_node()->get_read_from_size() <= 1)
822 //Must make sure that execution is currently feasible... We could
823 //accidentally clear by rolling back
826 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
827 int tid = id_to_int(curr->get_tid());
830 if ((int)thrd_lists->size() <= tid)
832 action_list_t *list = &(*thrd_lists)[tid];
834 action_list_t::reverse_iterator rit = list->rbegin();
836 for (; (*rit) != curr; rit++)
838 /* go past curr now */
841 action_list_t::reverse_iterator ritcopy = rit;
842 //See if we have enough reads from the same value
844 for (; count < params.maxreads; rit++,count++) {
845 if (rit==list->rend())
847 ModelAction *act = *rit;
851 if (act->get_reads_from() != rf)
853 if (act->get_node()->get_read_from_size() <= 1)
856 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
858 const ModelAction * write = curr->get_node()->get_read_from_at(i);
860 //Need a different write
864 /* Test to see whether this is a feasible write to read from*/
865 mo_graph->startChanges();
866 r_modification_order(curr, write);
867 bool feasiblereadfrom = isfeasible();
868 mo_graph->rollbackChanges();
870 if (!feasiblereadfrom)
874 bool feasiblewrite = true;
875 //new we need to see if this write works for everyone
877 for (int loop = count; loop>0; loop--,rit++) {
878 ModelAction *act=*rit;
879 bool foundvalue = false;
880 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
881 if (act->get_node()->get_read_from_at(i)==write) {
887 feasiblewrite = false;
892 too_many_reads = true;
900 * Updates the mo_graph with the constraints imposed from the current
903 * Basic idea is the following: Go through each other thread and find
904 * the lastest action that happened before our read. Two cases:
906 * (1) The action is a write => that write must either occur before
907 * the write we read from or be the write we read from.
909 * (2) The action is a read => the write that that action read from
910 * must occur before the write we read from or be the same write.
912 * @param curr The current action. Must be a read.
913 * @param rf The action that curr reads from. Must be a write.
914 * @return True if modification order edges were added; false otherwise
916 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
918 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
921 ASSERT(curr->is_read());
923 /* Iterate over all threads */
924 for (i = 0; i < thrd_lists->size(); i++) {
925 /* Iterate over actions in thread, starting from most recent */
926 action_list_t *list = &(*thrd_lists)[i];
927 action_list_t::reverse_iterator rit;
928 for (rit = list->rbegin(); rit != list->rend(); rit++) {
929 ModelAction *act = *rit;
932 * Include at most one act per-thread that "happens
933 * before" curr. Don't consider reflexively.
935 if (act->happens_before(curr) && act != curr) {
936 if (act->is_write()) {
938 mo_graph->addEdge(act, rf);
942 const ModelAction *prevreadfrom = act->get_reads_from();
943 if (prevreadfrom != NULL && rf != prevreadfrom) {
944 mo_graph->addEdge(prevreadfrom, rf);
956 /** This method fixes up the modification order when we resolve a
957 * promises. The basic problem is that actions that occur after the
958 * read curr could not property add items to the modification order
961 * So for each thread, we find the earliest item that happens after
962 * the read curr. This is the item we have to fix up with additional
963 * constraints. If that action is write, we add a MO edge between
964 * the Action rf and that action. If the action is a read, we add a
965 * MO edge between the Action rf, and whatever the read accessed.
967 * @param curr is the read ModelAction that we are fixing up MO edges for.
968 * @param rf is the write ModelAction that curr reads from.
971 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
973 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
975 ASSERT(curr->is_read());
977 /* Iterate over all threads */
978 for (i = 0; i < thrd_lists->size(); i++) {
979 /* Iterate over actions in thread, starting from most recent */
980 action_list_t *list = &(*thrd_lists)[i];
981 action_list_t::reverse_iterator rit;
982 ModelAction *lastact = NULL;
984 /* Find last action that happens after curr that is either not curr or a rmw */
985 for (rit = list->rbegin(); rit != list->rend(); rit++) {
986 ModelAction *act = *rit;
987 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
993 /* Include at most one act per-thread that "happens before" curr */
994 if (lastact != NULL) {
996 //Case 1: The resolved read is a RMW, and we need to make sure
997 //that the write portion of the RMW mod order after rf
999 mo_graph->addEdge(rf, lastact);
1000 } else if (lastact->is_read()) {
1001 //Case 2: The resolved read is a normal read and the next
1002 //operation is a read, and we need to make sure the value read
1003 //is mod ordered after rf
1005 const ModelAction *postreadfrom = lastact->get_reads_from();
1006 if (postreadfrom != NULL&&rf != postreadfrom)
1007 mo_graph->addEdge(rf, postreadfrom);
1009 //Case 3: The resolved read is a normal read and the next
1010 //operation is a write, and we need to make sure that the
1011 //write is mod ordered after rf
1013 mo_graph->addEdge(rf, lastact);
1021 * Updates the mo_graph with the constraints imposed from the current write.
1023 * Basic idea is the following: Go through each other thread and find
1024 * the lastest action that happened before our write. Two cases:
1026 * (1) The action is a write => that write must occur before
1029 * (2) The action is a read => the write that that action read from
1030 * must occur before the current write.
1032 * This method also handles two other issues:
1034 * (I) Sequential Consistency: Making sure that if the current write is
1035 * seq_cst, that it occurs after the previous seq_cst write.
1037 * (II) Sending the write back to non-synchronizing reads.
1039 * @param curr The current action. Must be a write.
1040 * @return True if modification order edges were added; false otherwise
1042 bool ModelChecker::w_modification_order(ModelAction *curr)
1044 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1047 ASSERT(curr->is_write());
1049 if (curr->is_seqcst()) {
1050 /* We have to at least see the last sequentially consistent write,
1051 so we are initialized. */
1052 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1053 if (last_seq_cst != NULL) {
1054 mo_graph->addEdge(last_seq_cst, curr);
1059 /* Iterate over all threads */
1060 for (i = 0; i < thrd_lists->size(); i++) {
1061 /* Iterate over actions in thread, starting from most recent */
1062 action_list_t *list = &(*thrd_lists)[i];
1063 action_list_t::reverse_iterator rit;
1064 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1065 ModelAction *act = *rit;
1068 * If RMW, we already have all relevant edges,
1069 * so just skip to next thread.
1070 * If normal write, we need to look at earlier
1071 * actions, so continue processing list.
1080 * Include at most one act per-thread that "happens
1083 if (act->happens_before(curr)) {
1085 * Note: if act is RMW, just add edge:
1087 * The following edge should be handled elsewhere:
1088 * readfrom(act) --mo--> act
1090 if (act->is_write())
1091 mo_graph->addEdge(act, curr);
1092 else if (act->is_read() && act->get_reads_from() != NULL)
1093 mo_graph->addEdge(act->get_reads_from(), curr);
1096 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1097 !act->same_thread(curr)) {
1098 /* We have an action that:
1099 (1) did not happen before us
1100 (2) is a read and we are a write
1101 (3) cannot synchronize with us
1102 (4) is in a different thread
1104 that read could potentially read from our write.
1106 if (thin_air_constraint_may_allow(curr, act)) {
1108 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1109 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1110 futurevalues->push_back(pfv);
1120 /** Arbitrary reads from the future are not allowed. Section 29.3
1121 * part 9 places some constraints. This method checks one result of constraint
1122 * constraint. Others require compiler support. */
1123 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1124 if (!writer->is_rmw())
1127 if (!reader->is_rmw())
1130 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1131 if (search == reader)
1133 if (search->get_tid() == reader->get_tid() &&
1134 search->happens_before(reader))
1142 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1143 * The ModelAction under consideration is expected to be taking part in
1144 * release/acquire synchronization as an object of the "reads from" relation.
1145 * Note that this can only provide release sequence support for RMW chains
1146 * which do not read from the future, as those actions cannot be traced until
1147 * their "promise" is fulfilled. Similarly, we may not even establish the
1148 * presence of a release sequence with certainty, as some modification order
1149 * constraints may be decided further in the future. Thus, this function
1150 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1151 * and a boolean representing certainty.
1153 * @todo Finish lazy updating, when promises are fulfilled in the future
1154 * @param rf The action that might be part of a release sequence. Must be a
1156 * @param release_heads A pass-by-reference style return parameter. After
1157 * execution of this function, release_heads will contain the heads of all the
1158 * relevant release sequences, if any exists
1159 * @return true, if the ModelChecker is certain that release_heads is complete;
1162 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1164 /* Only check for release sequences if there are no cycles */
1165 if (mo_graph->checkForCycles())
1169 ASSERT(rf->is_write());
1171 if (rf->is_release())
1172 release_heads->push_back(rf);
1174 break; /* End of RMW chain */
1176 /** @todo Need to be smarter here... In the linux lock
1177 * example, this will run to the beginning of the program for
1179 /** @todo The way to be smarter here is to keep going until 1
1180 * thread has a release preceded by an acquire and you've seen
1183 /* acq_rel RMW is a sufficient stopping condition */
1184 if (rf->is_acquire() && rf->is_release())
1185 return true; /* complete */
1187 rf = rf->get_reads_from();
1190 /* read from future: need to settle this later */
1191 return false; /* incomplete */
1194 if (rf->is_release())
1195 return true; /* complete */
1197 /* else relaxed write; check modification order for contiguous subsequence
1198 * -> rf must be same thread as release */
1199 int tid = id_to_int(rf->get_tid());
1200 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1201 action_list_t *list = &(*thrd_lists)[tid];
1202 action_list_t::const_reverse_iterator rit;
1204 /* Find rf in the thread list */
1205 rit = std::find(list->rbegin(), list->rend(), rf);
1206 ASSERT(rit != list->rend());
1208 /* Find the last write/release */
1209 for (; rit != list->rend(); rit++)
1210 if ((*rit)->is_release())
1212 if (rit == list->rend()) {
1213 /* No write-release in this thread */
1214 return true; /* complete */
1216 ModelAction *release = *rit;
1218 ASSERT(rf->same_thread(release));
1220 bool certain = true;
1221 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1222 if (id_to_int(rf->get_tid()) == (int)i)
1224 list = &(*thrd_lists)[i];
1226 /* Can we ensure no future writes from this thread may break
1227 * the release seq? */
1228 bool future_ordered = false;
1230 ModelAction *last = get_last_action(int_to_id(i));
1231 if (last && (rf->happens_before(last) ||
1232 last->get_type() == THREAD_FINISH))
1233 future_ordered = true;
1235 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1236 const ModelAction *act = *rit;
1237 /* Reach synchronization -> this thread is complete */
1238 if (act->happens_before(release))
1240 if (rf->happens_before(act)) {
1241 future_ordered = true;
1245 /* Only writes can break release sequences */
1246 if (!act->is_write())
1249 /* Check modification order */
1250 if (mo_graph->checkReachable(rf, act)) {
1251 /* rf --mo--> act */
1252 future_ordered = true;
1255 if (mo_graph->checkReachable(act, release))
1256 /* act --mo--> release */
1258 if (mo_graph->checkReachable(release, act) &&
1259 mo_graph->checkReachable(act, rf)) {
1260 /* release --mo-> act --mo--> rf */
1261 return true; /* complete */
1265 if (!future_ordered)
1266 return false; /* This thread is uncertain */
1270 release_heads->push_back(release);
1275 * A public interface for getting the release sequence head(s) with which a
1276 * given ModelAction must synchronize. This function only returns a non-empty
1277 * result when it can locate a release sequence head with certainty. Otherwise,
1278 * it may mark the internal state of the ModelChecker so that it will handle
1279 * the release sequence at a later time, causing @a act to update its
1280 * synchronization at some later point in execution.
1281 * @param act The 'acquire' action that may read from a release sequence
1282 * @param release_heads A pass-by-reference return parameter. Will be filled
1283 * with the head(s) of the release sequence(s), if they exists with certainty.
1284 * @see ModelChecker::release_seq_head
1286 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1288 const ModelAction *rf = act->get_reads_from();
1290 complete = release_seq_head(rf, release_heads);
1292 /* add act to 'lazy checking' list */
1293 pending_acq_rel_seq->push_back(act);
1298 * Attempt to resolve all stashed operations that might synchronize with a
1299 * release sequence for a given location. This implements the "lazy" portion of
1300 * determining whether or not a release sequence was contiguous, since not all
1301 * modification order information is present at the time an action occurs.
1303 * @param location The location/object that should be checked for release
1304 * sequence resolutions. A NULL value means to check all locations.
1305 * @param work_queue The work queue to which to add work items as they are
1307 * @return True if any updates occurred (new synchronization, new mo_graph
1310 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1312 bool updated = false;
1313 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1314 while (it != pending_acq_rel_seq->end()) {
1315 ModelAction *act = *it;
1317 /* Only resolve sequences on the given location, if provided */
1318 if (location && act->get_location() != location) {
1323 const ModelAction *rf = act->get_reads_from();
1324 rel_heads_list_t release_heads;
1326 complete = release_seq_head(rf, &release_heads);
1327 for (unsigned int i = 0; i < release_heads.size(); i++) {
1328 if (!act->has_synchronized_with(release_heads[i])) {
1329 if (act->synchronize_with(release_heads[i]))
1332 set_bad_synchronization();
1337 /* Re-check all pending release sequences */
1338 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1339 /* Re-check act for mo_graph edges */
1340 work_queue->push_back(MOEdgeWorkEntry(act));
1342 /* propagate synchronization to later actions */
1343 action_list_t::reverse_iterator rit = action_trace->rbegin();
1344 for (; (*rit) != act; rit++) {
1345 ModelAction *propagate = *rit;
1346 if (act->happens_before(propagate)) {
1347 propagate->synchronize_with(act);
1348 /* Re-check 'propagate' for mo_graph edges */
1349 work_queue->push_back(MOEdgeWorkEntry(propagate));
1354 it = pending_acq_rel_seq->erase(it);
1359 // If we resolved promises or data races, see if we have realized a data race.
1360 if (checkDataRaces()) {
1368 * Performs various bookkeeping operations for the current ModelAction. For
1369 * instance, adds action to the per-object, per-thread action vector and to the
1370 * action trace list of all thread actions.
1372 * @param act is the ModelAction to add.
1374 void ModelChecker::add_action_to_lists(ModelAction *act)
1376 int tid = id_to_int(act->get_tid());
1377 action_trace->push_back(act);
1379 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1381 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1382 if (tid >= (int)vec->size())
1383 vec->resize(priv->next_thread_id);
1384 (*vec)[tid].push_back(act);
1386 if ((int)thrd_last_action->size() <= tid)
1387 thrd_last_action->resize(get_num_threads());
1388 (*thrd_last_action)[tid] = act;
1392 * @brief Get the last action performed by a particular Thread
1393 * @param tid The thread ID of the Thread in question
1394 * @return The last action in the thread
1396 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1398 int threadid = id_to_int(tid);
1399 if (threadid < (int)thrd_last_action->size())
1400 return (*thrd_last_action)[id_to_int(tid)];
1406 * Gets the last memory_order_seq_cst write (in the total global sequence)
1407 * performed on a particular object (i.e., memory location), not including the
1409 * @param curr The current ModelAction; also denotes the object location to
1411 * @return The last seq_cst write
1413 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1415 void *location = curr->get_location();
1416 action_list_t *list = obj_map->get_safe_ptr(location);
1417 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1418 action_list_t::reverse_iterator rit;
1419 for (rit = list->rbegin(); rit != list->rend(); rit++)
1420 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1426 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1427 * location). This function identifies the mutex according to the current
1428 * action, which is presumed to perform on the same mutex.
1429 * @param curr The current ModelAction; also denotes the object location to
1431 * @return The last unlock operation
1433 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1435 void *location = curr->get_location();
1436 action_list_t *list = obj_map->get_safe_ptr(location);
1437 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1438 action_list_t::reverse_iterator rit;
1439 for (rit = list->rbegin(); rit != list->rend(); rit++)
1440 if ((*rit)->is_unlock())
1445 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1447 ModelAction *parent = get_last_action(tid);
1449 parent = get_thread(tid)->get_creation();
1454 * Returns the clock vector for a given thread.
1455 * @param tid The thread whose clock vector we want
1456 * @return Desired clock vector
1458 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1460 return get_parent_action(tid)->get_cv();
1464 * Resolve a set of Promises with a current write. The set is provided in the
1465 * Node corresponding to @a write.
1466 * @param write The ModelAction that is fulfilling Promises
1467 * @return True if promises were resolved; false otherwise
1469 bool ModelChecker::resolve_promises(ModelAction *write)
1471 bool resolved = false;
1473 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1474 Promise *promise = (*promises)[promise_index];
1475 if (write->get_node()->get_promise(i)) {
1476 ModelAction *read = promise->get_action();
1477 if (read->is_rmw()) {
1478 mo_graph->addRMWEdge(write, read);
1480 read->read_from(write);
1481 //First fix up the modification order for actions that happened
1483 r_modification_order(read, write);
1484 //Next fix up the modification order for actions that happened
1486 post_r_modification_order(read, write);
1487 //Make sure the promise's value matches the write's value
1488 ASSERT(promise->get_value() == write->get_value());
1491 promises->erase(promises->begin() + promise_index);
1500 * Compute the set of promises that could potentially be satisfied by this
1501 * action. Note that the set computation actually appears in the Node, not in
1503 * @param curr The ModelAction that may satisfy promises
1505 void ModelChecker::compute_promises(ModelAction *curr)
1507 for (unsigned int i = 0; i < promises->size(); i++) {
1508 Promise *promise = (*promises)[i];
1509 const ModelAction *act = promise->get_action();
1510 if (!act->happens_before(curr) &&
1512 !act->is_synchronizing(curr) &&
1513 !act->same_thread(curr) &&
1514 promise->get_value() == curr->get_value()) {
1515 curr->get_node()->set_promise(i);
1520 /** Checks promises in response to change in ClockVector Threads. */
1521 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1523 for (unsigned int i = 0; i < promises->size(); i++) {
1524 Promise *promise = (*promises)[i];
1525 const ModelAction *act = promise->get_action();
1526 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1527 merge_cv->synchronized_since(act)) {
1528 //This thread is no longer able to send values back to satisfy the promise
1529 int num_synchronized_threads = promise->increment_threads();
1530 if (num_synchronized_threads == get_num_threads()) {
1531 //Promise has failed
1532 failed_promise = true;
1540 * Build up an initial set of all past writes that this 'read' action may read
1541 * from. This set is determined by the clock vector's "happens before"
1543 * @param curr is the current ModelAction that we are exploring; it must be a
1546 void ModelChecker::build_reads_from_past(ModelAction *curr)
1548 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1550 ASSERT(curr->is_read());
1552 ModelAction *last_seq_cst = NULL;
1554 /* Track whether this object has been initialized */
1555 bool initialized = false;
1557 if (curr->is_seqcst()) {
1558 last_seq_cst = get_last_seq_cst(curr);
1559 /* We have to at least see the last sequentially consistent write,
1560 so we are initialized. */
1561 if (last_seq_cst != NULL)
1565 /* Iterate over all threads */
1566 for (i = 0; i < thrd_lists->size(); i++) {
1567 /* Iterate over actions in thread, starting from most recent */
1568 action_list_t *list = &(*thrd_lists)[i];
1569 action_list_t::reverse_iterator rit;
1570 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1571 ModelAction *act = *rit;
1573 /* Only consider 'write' actions */
1574 if (!act->is_write() || act == curr)
1577 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1578 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1579 DEBUG("Adding action to may_read_from:\n");
1580 if (DBG_ENABLED()) {
1584 curr->get_node()->add_read_from(act);
1587 /* Include at most one act per-thread that "happens before" curr */
1588 if (act->happens_before(curr)) {
1596 /** @todo Need a more informative way of reporting errors. */
1597 printf("ERROR: may read from uninitialized atomic\n");
1600 if (DBG_ENABLED() || !initialized) {
1601 printf("Reached read action:\n");
1603 printf("Printing may_read_from\n");
1604 curr->get_node()->print_may_read_from();
1605 printf("End printing may_read_from\n");
1608 ASSERT(initialized);
1611 static void print_list(action_list_t *list)
1613 action_list_t::iterator it;
1615 printf("---------------------------------------------------------------------\n");
1618 for (it = list->begin(); it != list->end(); it++) {
1621 printf("---------------------------------------------------------------------\n");
1624 #if SUPPORT_MOD_ORDER_DUMP
1625 void ModelChecker::dumpGraph(char *filename) {
1627 sprintf(buffer, "%s.dot",filename);
1628 FILE *file=fopen(buffer, "w");
1629 fprintf(file, "digraph %s {\n",filename);
1630 mo_graph->dumpNodes(file);
1631 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1633 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1634 ModelAction *action=*it;
1635 if (action->is_read()) {
1636 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1637 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1639 if (thread_array[action->get_tid()] != NULL) {
1640 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1643 thread_array[action->get_tid()]=action;
1645 fprintf(file,"}\n");
1646 model_free(thread_array);
1651 void ModelChecker::print_summary()
1654 printf("Number of executions: %d\n", num_executions);
1655 printf("Number of feasible executions: %d\n", num_feasible_executions);
1656 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1658 #if SUPPORT_MOD_ORDER_DUMP
1660 char buffername[100];
1661 sprintf(buffername, "exec%04u", num_executions);
1662 mo_graph->dumpGraphToFile(buffername);
1663 sprintf(buffername, "graph%04u", num_executions);
1664 dumpGraph(buffername);
1667 if (!isfinalfeasible())
1668 printf("INFEASIBLE EXECUTION!\n");
1669 print_list(action_trace);
1674 * Add a Thread to the system for the first time. Should only be called once
1676 * @param t The Thread to add
1678 void ModelChecker::add_thread(Thread *t)
1680 thread_map->put(id_to_int(t->get_id()), t);
1681 scheduler->add_thread(t);
1685 * Removes a thread from the scheduler.
1686 * @param the thread to remove.
1688 void ModelChecker::remove_thread(Thread *t)
1690 scheduler->remove_thread(t);
1694 * @brief Get a Thread reference by its ID
1695 * @param tid The Thread's ID
1696 * @return A Thread reference
1698 Thread * ModelChecker::get_thread(thread_id_t tid)
1700 return thread_map->get(id_to_int(tid));
1704 * @brief Get a reference to the Thread in which a ModelAction was executed
1705 * @param act The ModelAction
1706 * @return A Thread reference
1708 Thread * ModelChecker::get_thread(ModelAction *act)
1710 return get_thread(act->get_tid());
1714 * Switch from a user-context to the "master thread" context (a.k.a. system
1715 * context). This switch is made with the intention of exploring a particular
1716 * model-checking action (described by a ModelAction object). Must be called
1717 * from a user-thread context.
1719 * @param act The current action that will be explored. May be NULL only if
1720 * trace is exiting via an assertion (see ModelChecker::set_assert and
1721 * ModelChecker::has_asserted).
1722 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1724 int ModelChecker::switch_to_master(ModelAction *act)
1727 Thread *old = thread_current();
1728 set_current_action(act);
1729 old->set_state(THREAD_READY);
1730 return Thread::swap(old, &system_context);
1734 * Takes the next step in the execution, if possible.
1735 * @return Returns true (success) if a step was taken and false otherwise.
1737 bool ModelChecker::take_step() {
1741 Thread * curr = thread_current();
1743 if (curr->get_state() == THREAD_READY) {
1744 ASSERT(priv->current_action);
1746 priv->nextThread = check_current_action(priv->current_action);
1747 priv->current_action = NULL;
1749 if (curr->is_blocked() || curr->is_complete())
1750 scheduler->remove_thread(curr);
1755 Thread * next = scheduler->next_thread(priv->nextThread);
1757 /* Infeasible -> don't take any more steps */
1762 next->set_state(THREAD_RUNNING);
1763 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1765 /* next == NULL -> don't take any more steps */
1769 if ( next->get_pending() != NULL ) {
1770 //restart a pending action
1771 set_current_action(next->get_pending());
1772 next->set_pending(NULL);
1773 next->set_state(THREAD_READY);
1777 /* Return false only if swap fails with an error */
1778 return (Thread::swap(&system_context, next) == 0);
1781 /** Runs the current execution until threre are no more steps to take. */
1782 void ModelChecker::finish_execution() {
1785 while (take_step());