8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
17 #define INITIAL_THREAD_ID 0
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23 /* Initialize default scheduler */
25 scheduler(new Scheduler()),
27 num_feasible_executions(0),
29 earliest_diverge(NULL),
30 action_trace(new action_list_t()),
31 thread_map(new HashTable<int, Thread *, int>()),
32 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
34 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
35 promises(new std::vector<Promise *>()),
36 futurevalues(new std::vector<struct PendingFutureValue>()),
37 pending_acq_rel_seq(new std::vector<ModelAction *>()),
38 thrd_last_action(new std::vector<ModelAction *>(1)),
39 node_stack(new NodeStack()),
40 mo_graph(new CycleGraph()),
41 failed_promise(false),
42 too_many_reads(false),
44 bad_synchronization(false)
46 /* Allocate this "size" on the snapshotting heap */
47 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
48 /* First thread created will have id INITIAL_THREAD_ID */
49 priv->next_thread_id = INITIAL_THREAD_ID;
52 /** @brief Destructor */
53 ModelChecker::~ModelChecker()
55 for (int i = 0; i < get_num_threads(); i++)
56 delete thread_map->get(i);
61 delete lock_waiters_map;
64 for (unsigned int i = 0; i < promises->size(); i++)
65 delete (*promises)[i];
68 delete pending_acq_rel_seq;
70 delete thrd_last_action;
77 * Restores user program to initial state and resets all model-checker data
80 void ModelChecker::reset_to_initial_state()
82 DEBUG("+++ Resetting to initial state +++\n");
83 node_stack->reset_execution();
84 failed_promise = false;
85 too_many_reads = false;
86 bad_synchronization = false;
88 snapshotObject->backTrackBeforeStep(0);
91 /** @return a thread ID for a new Thread */
92 thread_id_t ModelChecker::get_next_id()
94 return priv->next_thread_id++;
97 /** @return the number of user threads created during this execution */
98 int ModelChecker::get_num_threads()
100 return priv->next_thread_id;
103 /** @return The currently executing Thread. */
104 Thread * ModelChecker::get_current_thread()
106 return scheduler->get_current_thread();
109 /** @return a sequence number for a new ModelAction */
110 modelclock_t ModelChecker::get_next_seq_num()
112 return ++priv->used_sequence_numbers;
116 * @brief Choose the next thread to execute.
118 * This function chooses the next thread that should execute. It can force the
119 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
120 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
121 * The model-checker may have no preference regarding the next thread (i.e.,
122 * when exploring a new execution ordering), in which case this will return
124 * @param curr The current ModelAction. This action might guide the choice of
126 * @return The next thread to run. If the model-checker has no preference, NULL.
128 Thread * ModelChecker::get_next_thread(ModelAction *curr)
133 /* Do not split atomic actions. */
135 return thread_current();
136 /* The THREAD_CREATE action points to the created Thread */
137 else if (curr->get_type() == THREAD_CREATE)
138 return (Thread *)curr->get_location();
141 /* Have we completed exploring the preselected path? */
145 /* Else, we are trying to replay an execution */
146 ModelAction *next = node_stack->get_next()->get_action();
148 if (next == diverge) {
149 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
150 earliest_diverge=diverge;
152 Node *nextnode = next->get_node();
153 /* Reached divergence point */
154 if (nextnode->increment_promise()) {
155 /* The next node will try to satisfy a different set of promises. */
156 tid = next->get_tid();
157 node_stack->pop_restofstack(2);
158 } else if (nextnode->increment_read_from()) {
159 /* The next node will read from a different value. */
160 tid = next->get_tid();
161 node_stack->pop_restofstack(2);
162 } else if (nextnode->increment_future_value()) {
163 /* The next node will try to read from a different future value. */
164 tid = next->get_tid();
165 node_stack->pop_restofstack(2);
167 /* Make a different thread execute for next step */
168 Node *node = nextnode->get_parent();
169 tid = node->get_next_backtrack();
170 node_stack->pop_restofstack(1);
171 if (diverge==earliest_diverge) {
172 earliest_diverge=node->get_action();
175 DEBUG("*** Divergence point ***\n");
179 tid = next->get_tid();
181 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
182 ASSERT(tid != THREAD_ID_T_NONE);
183 return thread_map->get(id_to_int(tid));
187 * Queries the model-checker for more executions to explore and, if one
188 * exists, resets the model-checker state to execute a new execution.
190 * @return If there are more executions to explore, return true. Otherwise,
193 bool ModelChecker::next_execution()
199 if (isfinalfeasible()) {
200 printf("Earliest divergence point since last feasible execution:\n");
201 if (earliest_diverge)
202 earliest_diverge->print(false);
204 printf("(Not set)\n");
206 earliest_diverge = NULL;
207 num_feasible_executions++;
210 DEBUG("Number of acquires waiting on pending release sequences: %lu\n",
211 pending_acq_rel_seq->size());
213 if (isfinalfeasible() || DBG_ENABLED())
216 if ((diverge = get_next_backtrack()) == NULL)
220 printf("Next execution will diverge at:\n");
224 reset_to_initial_state();
228 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
230 switch (act->get_type()) {
234 /* linear search: from most recent to oldest */
235 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
236 action_list_t::reverse_iterator rit;
237 for (rit = list->rbegin(); rit != list->rend(); rit++) {
238 ModelAction *prev = *rit;
239 if (act->is_synchronizing(prev))
245 case ATOMIC_TRYLOCK: {
246 /* linear search: from most recent to oldest */
247 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
248 action_list_t::reverse_iterator rit;
249 for (rit = list->rbegin(); rit != list->rend(); rit++) {
250 ModelAction *prev = *rit;
251 if (act->is_conflicting_lock(prev))
256 case ATOMIC_UNLOCK: {
257 /* linear search: from most recent to oldest */
258 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
259 action_list_t::reverse_iterator rit;
260 for (rit = list->rbegin(); rit != list->rend(); rit++) {
261 ModelAction *prev = *rit;
262 if (!act->same_thread(prev)&&prev->is_failed_trylock())
273 /** This method find backtracking points where we should try to
274 * reorder the parameter ModelAction against.
276 * @param the ModelAction to find backtracking points for.
278 void ModelChecker::set_backtracking(ModelAction *act)
280 Thread *t = get_thread(act);
281 ModelAction * prev = get_last_conflict(act);
285 Node * node = prev->get_node()->get_parent();
287 int low_tid, high_tid;
288 if (node->is_enabled(t)) {
289 low_tid = id_to_int(act->get_tid());
290 high_tid = low_tid+1;
293 high_tid = get_num_threads();
296 for(int i = low_tid; i < high_tid; i++) {
297 thread_id_t tid = int_to_id(i);
298 if (!node->is_enabled(tid))
301 /* Check if this has been explored already */
302 if (node->has_been_explored(tid))
305 /* See if fairness allows */
306 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
308 for(int t=0;t<node->get_num_threads();t++) {
309 thread_id_t tother=int_to_id(t);
310 if (node->is_enabled(tother) && node->has_priority(tother)) {
319 /* Cache the latest backtracking point */
320 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
321 priv->next_backtrack = prev;
323 /* If this is a new backtracking point, mark the tree */
324 if (!node->set_backtrack(tid))
326 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
327 prev->get_tid(), t->get_id());
336 * Returns last backtracking point. The model checker will explore a different
337 * path for this point in the next execution.
338 * @return The ModelAction at which the next execution should diverge.
340 ModelAction * ModelChecker::get_next_backtrack()
342 ModelAction *next = priv->next_backtrack;
343 priv->next_backtrack = NULL;
348 * Processes a read or rmw model action.
349 * @param curr is the read model action to process.
350 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
351 * @return True if processing this read updates the mo_graph.
353 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
356 bool updated = false;
358 const ModelAction *reads_from = curr->get_node()->get_read_from();
359 if (reads_from != NULL) {
360 mo_graph->startChanges();
362 value = reads_from->get_value();
363 bool r_status = false;
365 if (!second_part_of_rmw) {
366 check_recency(curr, reads_from);
367 r_status = r_modification_order(curr, reads_from);
371 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
372 mo_graph->rollbackChanges();
373 too_many_reads = false;
377 curr->read_from(reads_from);
378 mo_graph->commitChanges();
380 } else if (!second_part_of_rmw) {
381 /* Read from future value */
382 value = curr->get_node()->get_future_value();
383 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
384 curr->read_from(NULL);
385 Promise *valuepromise = new Promise(curr, value, expiration);
386 promises->push_back(valuepromise);
388 get_thread(curr)->set_return_value(value);
394 * Processes a lock, trylock, or unlock model action. @param curr is
395 * the read model action to process.
397 * The try lock operation checks whether the lock is taken. If not,
398 * it falls to the normal lock operation case. If so, it returns
401 * The lock operation has already been checked that it is enabled, so
402 * it just grabs the lock and synchronizes with the previous unlock.
404 * The unlock operation has to re-enable all of the threads that are
405 * waiting on the lock.
407 * @return True if synchronization was updated; false otherwise
409 bool ModelChecker::process_mutex(ModelAction *curr) {
410 std::mutex *mutex = (std::mutex *)curr->get_location();
411 struct std::mutex_state *state = mutex->get_state();
412 switch (curr->get_type()) {
413 case ATOMIC_TRYLOCK: {
414 bool success = !state->islocked;
415 curr->set_try_lock(success);
417 get_thread(curr)->set_return_value(0);
420 get_thread(curr)->set_return_value(1);
422 //otherwise fall into the lock case
424 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
425 printf("Lock access before initialization\n");
428 state->islocked = true;
429 ModelAction *unlock = get_last_unlock(curr);
430 //synchronize with the previous unlock statement
431 if (unlock != NULL) {
432 curr->synchronize_with(unlock);
437 case ATOMIC_UNLOCK: {
439 state->islocked = false;
440 //wake up the other threads
441 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
442 //activate all the waiting threads
443 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
444 scheduler->wake(get_thread(*rit));
456 * Process a write ModelAction
457 * @param curr The ModelAction to process
458 * @return True if the mo_graph was updated or promises were resolved
460 bool ModelChecker::process_write(ModelAction *curr)
462 bool updated_mod_order = w_modification_order(curr);
463 bool updated_promises = resolve_promises(curr);
465 if (promises->size() == 0) {
466 for (unsigned int i = 0; i < futurevalues->size(); i++) {
467 struct PendingFutureValue pfv = (*futurevalues)[i];
468 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
469 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
470 priv->next_backtrack = pfv.act;
472 futurevalues->resize(0);
475 mo_graph->commitChanges();
476 get_thread(curr)->set_return_value(VALUE_NONE);
477 return updated_mod_order || updated_promises;
481 * @brief Process the current action for thread-related activity
483 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
484 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
485 * synchronization, etc. This function is a no-op for non-THREAD actions
486 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
488 * @param curr The current action
489 * @return True if synchronization was updated or a thread completed
491 bool ModelChecker::process_thread_action(ModelAction *curr)
493 bool updated = false;
495 switch (curr->get_type()) {
496 case THREAD_CREATE: {
497 Thread *th = (Thread *)curr->get_location();
498 th->set_creation(curr);
502 Thread *waiting, *blocking;
503 waiting = get_thread(curr);
504 blocking = (Thread *)curr->get_location();
505 if (!blocking->is_complete()) {
506 blocking->push_wait_list(curr);
507 scheduler->sleep(waiting);
509 do_complete_join(curr);
510 updated = true; /* trigger rel-seq checks */
514 case THREAD_FINISH: {
515 Thread *th = get_thread(curr);
516 while (!th->wait_list_empty()) {
517 ModelAction *act = th->pop_wait_list();
518 Thread *wake = get_thread(act);
519 scheduler->wake(wake);
520 do_complete_join(act);
521 updated = true; /* trigger rel-seq checks */
524 updated = true; /* trigger rel-seq checks */
528 check_promises(NULL, curr->get_cv());
539 * Initialize the current action by performing one or more of the following
540 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
541 * in the NodeStack, manipulating backtracking sets, allocating and
542 * initializing clock vectors, and computing the promises to fulfill.
544 * @param curr The current action, as passed from the user context; may be
545 * freed/invalidated after the execution of this function
546 * @return The current action, as processed by the ModelChecker. Is only the
547 * same as the parameter @a curr if this is a newly-explored action.
549 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
551 ModelAction *newcurr;
553 if (curr->is_rmwc() || curr->is_rmw()) {
554 newcurr = process_rmw(curr);
557 if (newcurr->is_rmw())
558 compute_promises(newcurr);
562 curr->set_seq_number(get_next_seq_num());
564 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
566 /* First restore type and order in case of RMW operation */
568 newcurr->copy_typeandorder(curr);
570 ASSERT(curr->get_location() == newcurr->get_location());
571 newcurr->copy_from_new(curr);
573 /* Discard duplicate ModelAction; use action from NodeStack */
576 /* Always compute new clock vector */
577 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
581 /* Always compute new clock vector */
582 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
584 * Perform one-time actions when pushing new ModelAction onto
587 if (newcurr->is_write())
588 compute_promises(newcurr);
594 * This method checks whether a model action is enabled at the given point.
595 * At this point, it checks whether a lock operation would be successful at this point.
596 * If not, it puts the thread in a waiter list.
597 * @param curr is the ModelAction to check whether it is enabled.
598 * @return a bool that indicates whether the action is enabled.
600 bool ModelChecker::check_action_enabled(ModelAction *curr) {
601 if (curr->is_lock()) {
602 std::mutex * lock = (std::mutex *)curr->get_location();
603 struct std::mutex_state * state = lock->get_state();
604 if (state->islocked) {
605 //Stick the action in the appropriate waiting queue
606 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
615 * This is the heart of the model checker routine. It performs model-checking
616 * actions corresponding to a given "current action." Among other processes, it
617 * calculates reads-from relationships, updates synchronization clock vectors,
618 * forms a memory_order constraints graph, and handles replay/backtrack
619 * execution when running permutations of previously-observed executions.
621 * @param curr The current action to process
622 * @return The next Thread that must be executed. May be NULL if ModelChecker
623 * makes no choice (e.g., according to replay execution, combining RMW actions,
626 Thread * ModelChecker::check_current_action(ModelAction *curr)
630 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
632 if (!check_action_enabled(curr)) {
633 /* Make the execution look like we chose to run this action
634 * much later, when a lock is actually available to release */
635 get_current_thread()->set_pending(curr);
636 scheduler->sleep(get_current_thread());
637 return get_next_thread(NULL);
640 ModelAction *newcurr = initialize_curr_action(curr);
642 /* Add the action to lists before any other model-checking tasks */
643 if (!second_part_of_rmw)
644 add_action_to_lists(newcurr);
646 /* Build may_read_from set for newly-created actions */
647 if (curr == newcurr && curr->is_read())
648 build_reads_from_past(curr);
651 /* Initialize work_queue with the "current action" work */
652 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
654 while (!work_queue.empty()) {
655 WorkQueueEntry work = work_queue.front();
656 work_queue.pop_front();
659 case WORK_CHECK_CURR_ACTION: {
660 ModelAction *act = work.action;
661 bool update = false; /* update this location's release seq's */
662 bool update_all = false; /* update all release seq's */
664 if (process_thread_action(curr))
667 if (act->is_read() && process_read(act, second_part_of_rmw))
670 if (act->is_write() && process_write(act))
673 if (act->is_mutex_op() && process_mutex(act))
677 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
679 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
682 case WORK_CHECK_RELEASE_SEQ:
683 resolve_release_sequences(work.location, &work_queue);
685 case WORK_CHECK_MO_EDGES: {
686 /** @todo Complete verification of work_queue */
687 ModelAction *act = work.action;
688 bool updated = false;
690 if (act->is_read()) {
691 const ModelAction *rf = act->get_reads_from();
692 if (rf != NULL && r_modification_order(act, rf))
695 if (act->is_write()) {
696 if (w_modification_order(act))
699 mo_graph->commitChanges();
702 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
711 check_curr_backtracking(curr);
713 set_backtracking(curr);
715 return get_next_thread(curr);
719 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
720 * operation from the Thread it is joining with. Must be called after the
721 * completion of the Thread in question.
722 * @param join The THREAD_JOIN action
724 void ModelChecker::do_complete_join(ModelAction *join)
726 Thread *blocking = (Thread *)join->get_location();
727 ModelAction *act = get_last_action(blocking->get_id());
728 join->synchronize_with(act);
731 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
732 Node *currnode = curr->get_node();
733 Node *parnode = currnode->get_parent();
735 if ((!parnode->backtrack_empty() ||
736 !currnode->read_from_empty() ||
737 !currnode->future_value_empty() ||
738 !currnode->promise_empty())
739 && (!priv->next_backtrack ||
740 *curr > *priv->next_backtrack)) {
741 priv->next_backtrack = curr;
745 bool ModelChecker::promises_expired() {
746 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
747 Promise *promise = (*promises)[promise_index];
748 if (promise->get_expiration()<priv->used_sequence_numbers) {
755 /** @return whether the current partial trace must be a prefix of a
757 bool ModelChecker::isfeasibleprefix() {
758 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
761 /** @return whether the current partial trace is feasible. */
762 bool ModelChecker::isfeasible() {
763 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
764 DEBUG("Infeasible: RMW violation\n");
766 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
769 /** @return whether the current partial trace is feasible other than
770 * multiple RMW reading from the same store. */
771 bool ModelChecker::isfeasibleotherthanRMW() {
773 if (mo_graph->checkForCycles())
774 DEBUG("Infeasible: modification order cycles\n");
776 DEBUG("Infeasible: failed promise\n");
778 DEBUG("Infeasible: too many reads\n");
779 if (bad_synchronization)
780 DEBUG("Infeasible: bad synchronization ordering\n");
781 if (promises_expired())
782 DEBUG("Infeasible: promises expired\n");
784 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
787 /** Returns whether the current completed trace is feasible. */
788 bool ModelChecker::isfinalfeasible() {
789 if (DBG_ENABLED() && promises->size() != 0)
790 DEBUG("Infeasible: unrevolved promises\n");
792 return isfeasible() && promises->size() == 0;
795 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
796 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
797 int tid = id_to_int(act->get_tid());
798 ModelAction *lastread = get_last_action(tid);
799 lastread->process_rmw(act);
800 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
801 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
802 mo_graph->commitChanges();
808 * Checks whether a thread has read from the same write for too many times
809 * without seeing the effects of a later write.
812 * 1) there must a different write that we could read from that would satisfy the modification order,
813 * 2) we must have read from the same value in excess of maxreads times, and
814 * 3) that other write must have been in the reads_from set for maxreads times.
816 * If so, we decide that the execution is no longer feasible.
818 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
819 if (params.maxreads != 0) {
821 if (curr->get_node()->get_read_from_size() <= 1)
823 //Must make sure that execution is currently feasible... We could
824 //accidentally clear by rolling back
827 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
828 int tid = id_to_int(curr->get_tid());
831 if ((int)thrd_lists->size() <= tid)
833 action_list_t *list = &(*thrd_lists)[tid];
835 action_list_t::reverse_iterator rit = list->rbegin();
837 for (; (*rit) != curr; rit++)
839 /* go past curr now */
842 action_list_t::reverse_iterator ritcopy = rit;
843 //See if we have enough reads from the same value
845 for (; count < params.maxreads; rit++,count++) {
846 if (rit==list->rend())
848 ModelAction *act = *rit;
852 if (act->get_reads_from() != rf)
854 if (act->get_node()->get_read_from_size() <= 1)
857 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
859 const ModelAction * write = curr->get_node()->get_read_from_at(i);
861 //Need a different write
865 /* Test to see whether this is a feasible write to read from*/
866 mo_graph->startChanges();
867 r_modification_order(curr, write);
868 bool feasiblereadfrom = isfeasible();
869 mo_graph->rollbackChanges();
871 if (!feasiblereadfrom)
875 bool feasiblewrite = true;
876 //new we need to see if this write works for everyone
878 for (int loop = count; loop>0; loop--,rit++) {
879 ModelAction *act=*rit;
880 bool foundvalue = false;
881 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
882 if (act->get_node()->get_read_from_at(i)==write) {
888 feasiblewrite = false;
893 too_many_reads = true;
901 * Updates the mo_graph with the constraints imposed from the current
904 * Basic idea is the following: Go through each other thread and find
905 * the lastest action that happened before our read. Two cases:
907 * (1) The action is a write => that write must either occur before
908 * the write we read from or be the write we read from.
910 * (2) The action is a read => the write that that action read from
911 * must occur before the write we read from or be the same write.
913 * @param curr The current action. Must be a read.
914 * @param rf The action that curr reads from. Must be a write.
915 * @return True if modification order edges were added; false otherwise
917 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
919 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
922 ASSERT(curr->is_read());
924 /* Iterate over all threads */
925 for (i = 0; i < thrd_lists->size(); i++) {
926 /* Iterate over actions in thread, starting from most recent */
927 action_list_t *list = &(*thrd_lists)[i];
928 action_list_t::reverse_iterator rit;
929 for (rit = list->rbegin(); rit != list->rend(); rit++) {
930 ModelAction *act = *rit;
933 * Include at most one act per-thread that "happens
934 * before" curr. Don't consider reflexively.
936 if (act->happens_before(curr) && act != curr) {
937 if (act->is_write()) {
939 mo_graph->addEdge(act, rf);
943 const ModelAction *prevreadfrom = act->get_reads_from();
944 if (prevreadfrom != NULL && rf != prevreadfrom) {
945 mo_graph->addEdge(prevreadfrom, rf);
957 /** This method fixes up the modification order when we resolve a
958 * promises. The basic problem is that actions that occur after the
959 * read curr could not property add items to the modification order
962 * So for each thread, we find the earliest item that happens after
963 * the read curr. This is the item we have to fix up with additional
964 * constraints. If that action is write, we add a MO edge between
965 * the Action rf and that action. If the action is a read, we add a
966 * MO edge between the Action rf, and whatever the read accessed.
968 * @param curr is the read ModelAction that we are fixing up MO edges for.
969 * @param rf is the write ModelAction that curr reads from.
972 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
974 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
976 ASSERT(curr->is_read());
978 /* Iterate over all threads */
979 for (i = 0; i < thrd_lists->size(); i++) {
980 /* Iterate over actions in thread, starting from most recent */
981 action_list_t *list = &(*thrd_lists)[i];
982 action_list_t::reverse_iterator rit;
983 ModelAction *lastact = NULL;
985 /* Find last action that happens after curr that is either not curr or a rmw */
986 for (rit = list->rbegin(); rit != list->rend(); rit++) {
987 ModelAction *act = *rit;
988 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
994 /* Include at most one act per-thread that "happens before" curr */
995 if (lastact != NULL) {
997 //Case 1: The resolved read is a RMW, and we need to make sure
998 //that the write portion of the RMW mod order after rf
1000 mo_graph->addEdge(rf, lastact);
1001 } else if (lastact->is_read()) {
1002 //Case 2: The resolved read is a normal read and the next
1003 //operation is a read, and we need to make sure the value read
1004 //is mod ordered after rf
1006 const ModelAction *postreadfrom = lastact->get_reads_from();
1007 if (postreadfrom != NULL&&rf != postreadfrom)
1008 mo_graph->addEdge(rf, postreadfrom);
1010 //Case 3: The resolved read is a normal read and the next
1011 //operation is a write, and we need to make sure that the
1012 //write is mod ordered after rf
1014 mo_graph->addEdge(rf, lastact);
1022 * Updates the mo_graph with the constraints imposed from the current write.
1024 * Basic idea is the following: Go through each other thread and find
1025 * the lastest action that happened before our write. Two cases:
1027 * (1) The action is a write => that write must occur before
1030 * (2) The action is a read => the write that that action read from
1031 * must occur before the current write.
1033 * This method also handles two other issues:
1035 * (I) Sequential Consistency: Making sure that if the current write is
1036 * seq_cst, that it occurs after the previous seq_cst write.
1038 * (II) Sending the write back to non-synchronizing reads.
1040 * @param curr The current action. Must be a write.
1041 * @return True if modification order edges were added; false otherwise
1043 bool ModelChecker::w_modification_order(ModelAction *curr)
1045 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1048 ASSERT(curr->is_write());
1050 if (curr->is_seqcst()) {
1051 /* We have to at least see the last sequentially consistent write,
1052 so we are initialized. */
1053 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1054 if (last_seq_cst != NULL) {
1055 mo_graph->addEdge(last_seq_cst, curr);
1060 /* Iterate over all threads */
1061 for (i = 0; i < thrd_lists->size(); i++) {
1062 /* Iterate over actions in thread, starting from most recent */
1063 action_list_t *list = &(*thrd_lists)[i];
1064 action_list_t::reverse_iterator rit;
1065 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1066 ModelAction *act = *rit;
1069 * If RMW, we already have all relevant edges,
1070 * so just skip to next thread.
1071 * If normal write, we need to look at earlier
1072 * actions, so continue processing list.
1081 * Include at most one act per-thread that "happens
1084 if (act->happens_before(curr)) {
1086 * Note: if act is RMW, just add edge:
1088 * The following edge should be handled elsewhere:
1089 * readfrom(act) --mo--> act
1091 if (act->is_write())
1092 mo_graph->addEdge(act, curr);
1093 else if (act->is_read() && act->get_reads_from() != NULL)
1094 mo_graph->addEdge(act->get_reads_from(), curr);
1097 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1098 !act->same_thread(curr)) {
1099 /* We have an action that:
1100 (1) did not happen before us
1101 (2) is a read and we are a write
1102 (3) cannot synchronize with us
1103 (4) is in a different thread
1105 that read could potentially read from our write.
1107 if (thin_air_constraint_may_allow(curr, act)) {
1109 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1110 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1111 futurevalues->push_back(pfv);
1121 /** Arbitrary reads from the future are not allowed. Section 29.3
1122 * part 9 places some constraints. This method checks one result of constraint
1123 * constraint. Others require compiler support. */
1124 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1125 if (!writer->is_rmw())
1128 if (!reader->is_rmw())
1131 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1132 if (search == reader)
1134 if (search->get_tid() == reader->get_tid() &&
1135 search->happens_before(reader))
1143 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1144 * The ModelAction under consideration is expected to be taking part in
1145 * release/acquire synchronization as an object of the "reads from" relation.
1146 * Note that this can only provide release sequence support for RMW chains
1147 * which do not read from the future, as those actions cannot be traced until
1148 * their "promise" is fulfilled. Similarly, we may not even establish the
1149 * presence of a release sequence with certainty, as some modification order
1150 * constraints may be decided further in the future. Thus, this function
1151 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1152 * and a boolean representing certainty.
1154 * @todo Finish lazy updating, when promises are fulfilled in the future
1155 * @param rf The action that might be part of a release sequence. Must be a
1157 * @param release_heads A pass-by-reference style return parameter. After
1158 * execution of this function, release_heads will contain the heads of all the
1159 * relevant release sequences, if any exists
1160 * @return true, if the ModelChecker is certain that release_heads is complete;
1163 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1165 /* Only check for release sequences if there are no cycles */
1166 if (mo_graph->checkForCycles())
1170 ASSERT(rf->is_write());
1172 if (rf->is_release())
1173 release_heads->push_back(rf);
1175 break; /* End of RMW chain */
1177 /** @todo Need to be smarter here... In the linux lock
1178 * example, this will run to the beginning of the program for
1180 /** @todo The way to be smarter here is to keep going until 1
1181 * thread has a release preceded by an acquire and you've seen
1184 /* acq_rel RMW is a sufficient stopping condition */
1185 if (rf->is_acquire() && rf->is_release())
1186 return true; /* complete */
1188 rf = rf->get_reads_from();
1191 /* read from future: need to settle this later */
1192 return false; /* incomplete */
1195 if (rf->is_release())
1196 return true; /* complete */
1198 /* else relaxed write; check modification order for contiguous subsequence
1199 * -> rf must be same thread as release */
1200 int tid = id_to_int(rf->get_tid());
1201 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1202 action_list_t *list = &(*thrd_lists)[tid];
1203 action_list_t::const_reverse_iterator rit;
1205 /* Find rf in the thread list */
1206 rit = std::find(list->rbegin(), list->rend(), rf);
1207 ASSERT(rit != list->rend());
1209 /* Find the last write/release */
1210 for (; rit != list->rend(); rit++)
1211 if ((*rit)->is_release())
1213 if (rit == list->rend()) {
1214 /* No write-release in this thread */
1215 return true; /* complete */
1217 ModelAction *release = *rit;
1219 ASSERT(rf->same_thread(release));
1221 bool certain = true;
1222 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1223 if (id_to_int(rf->get_tid()) == (int)i)
1225 list = &(*thrd_lists)[i];
1227 /* Can we ensure no future writes from this thread may break
1228 * the release seq? */
1229 bool future_ordered = false;
1231 ModelAction *last = get_last_action(int_to_id(i));
1232 if (last && (rf->happens_before(last) ||
1233 last->get_type() == THREAD_FINISH))
1234 future_ordered = true;
1236 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1237 const ModelAction *act = *rit;
1238 /* Reach synchronization -> this thread is complete */
1239 if (act->happens_before(release))
1241 if (rf->happens_before(act)) {
1242 future_ordered = true;
1246 /* Only writes can break release sequences */
1247 if (!act->is_write())
1250 /* Check modification order */
1251 if (mo_graph->checkReachable(rf, act)) {
1252 /* rf --mo--> act */
1253 future_ordered = true;
1256 if (mo_graph->checkReachable(act, release))
1257 /* act --mo--> release */
1259 if (mo_graph->checkReachable(release, act) &&
1260 mo_graph->checkReachable(act, rf)) {
1261 /* release --mo-> act --mo--> rf */
1262 return true; /* complete */
1266 if (!future_ordered)
1267 return false; /* This thread is uncertain */
1271 release_heads->push_back(release);
1276 * A public interface for getting the release sequence head(s) with which a
1277 * given ModelAction must synchronize. This function only returns a non-empty
1278 * result when it can locate a release sequence head with certainty. Otherwise,
1279 * it may mark the internal state of the ModelChecker so that it will handle
1280 * the release sequence at a later time, causing @a act to update its
1281 * synchronization at some later point in execution.
1282 * @param act The 'acquire' action that may read from a release sequence
1283 * @param release_heads A pass-by-reference return parameter. Will be filled
1284 * with the head(s) of the release sequence(s), if they exists with certainty.
1285 * @see ModelChecker::release_seq_head
1287 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1289 const ModelAction *rf = act->get_reads_from();
1291 complete = release_seq_head(rf, release_heads);
1293 /* add act to 'lazy checking' list */
1294 pending_acq_rel_seq->push_back(act);
1299 * Attempt to resolve all stashed operations that might synchronize with a
1300 * release sequence for a given location. This implements the "lazy" portion of
1301 * determining whether or not a release sequence was contiguous, since not all
1302 * modification order information is present at the time an action occurs.
1304 * @param location The location/object that should be checked for release
1305 * sequence resolutions. A NULL value means to check all locations.
1306 * @param work_queue The work queue to which to add work items as they are
1308 * @return True if any updates occurred (new synchronization, new mo_graph
1311 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1313 bool updated = false;
1314 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1315 while (it != pending_acq_rel_seq->end()) {
1316 ModelAction *act = *it;
1318 /* Only resolve sequences on the given location, if provided */
1319 if (location && act->get_location() != location) {
1324 const ModelAction *rf = act->get_reads_from();
1325 rel_heads_list_t release_heads;
1327 complete = release_seq_head(rf, &release_heads);
1328 for (unsigned int i = 0; i < release_heads.size(); i++) {
1329 if (!act->has_synchronized_with(release_heads[i])) {
1330 if (act->synchronize_with(release_heads[i]))
1333 set_bad_synchronization();
1338 /* Re-check all pending release sequences */
1339 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1340 /* Re-check act for mo_graph edges */
1341 work_queue->push_back(MOEdgeWorkEntry(act));
1343 /* propagate synchronization to later actions */
1344 action_list_t::reverse_iterator rit = action_trace->rbegin();
1345 for (; (*rit) != act; rit++) {
1346 ModelAction *propagate = *rit;
1347 if (act->happens_before(propagate)) {
1348 propagate->synchronize_with(act);
1349 /* Re-check 'propagate' for mo_graph edges */
1350 work_queue->push_back(MOEdgeWorkEntry(propagate));
1355 it = pending_acq_rel_seq->erase(it);
1360 // If we resolved promises or data races, see if we have realized a data race.
1361 if (checkDataRaces()) {
1369 * Performs various bookkeeping operations for the current ModelAction. For
1370 * instance, adds action to the per-object, per-thread action vector and to the
1371 * action trace list of all thread actions.
1373 * @param act is the ModelAction to add.
1375 void ModelChecker::add_action_to_lists(ModelAction *act)
1377 int tid = id_to_int(act->get_tid());
1378 action_trace->push_back(act);
1380 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1382 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1383 if (tid >= (int)vec->size())
1384 vec->resize(priv->next_thread_id);
1385 (*vec)[tid].push_back(act);
1387 if ((int)thrd_last_action->size() <= tid)
1388 thrd_last_action->resize(get_num_threads());
1389 (*thrd_last_action)[tid] = act;
1393 * @brief Get the last action performed by a particular Thread
1394 * @param tid The thread ID of the Thread in question
1395 * @return The last action in the thread
1397 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1399 int threadid = id_to_int(tid);
1400 if (threadid < (int)thrd_last_action->size())
1401 return (*thrd_last_action)[id_to_int(tid)];
1407 * Gets the last memory_order_seq_cst write (in the total global sequence)
1408 * performed on a particular object (i.e., memory location), not including the
1410 * @param curr The current ModelAction; also denotes the object location to
1412 * @return The last seq_cst write
1414 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1416 void *location = curr->get_location();
1417 action_list_t *list = obj_map->get_safe_ptr(location);
1418 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1419 action_list_t::reverse_iterator rit;
1420 for (rit = list->rbegin(); rit != list->rend(); rit++)
1421 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1427 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1428 * location). This function identifies the mutex according to the current
1429 * action, which is presumed to perform on the same mutex.
1430 * @param curr The current ModelAction; also denotes the object location to
1432 * @return The last unlock operation
1434 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1436 void *location = curr->get_location();
1437 action_list_t *list = obj_map->get_safe_ptr(location);
1438 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1439 action_list_t::reverse_iterator rit;
1440 for (rit = list->rbegin(); rit != list->rend(); rit++)
1441 if ((*rit)->is_unlock())
1446 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1448 ModelAction *parent = get_last_action(tid);
1450 parent = get_thread(tid)->get_creation();
1455 * Returns the clock vector for a given thread.
1456 * @param tid The thread whose clock vector we want
1457 * @return Desired clock vector
1459 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1461 return get_parent_action(tid)->get_cv();
1465 * Resolve a set of Promises with a current write. The set is provided in the
1466 * Node corresponding to @a write.
1467 * @param write The ModelAction that is fulfilling Promises
1468 * @return True if promises were resolved; false otherwise
1470 bool ModelChecker::resolve_promises(ModelAction *write)
1472 bool resolved = false;
1474 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1475 Promise *promise = (*promises)[promise_index];
1476 if (write->get_node()->get_promise(i)) {
1477 ModelAction *read = promise->get_action();
1478 if (read->is_rmw()) {
1479 mo_graph->addRMWEdge(write, read);
1481 read->read_from(write);
1482 //First fix up the modification order for actions that happened
1484 r_modification_order(read, write);
1485 //Next fix up the modification order for actions that happened
1487 post_r_modification_order(read, write);
1488 //Make sure the promise's value matches the write's value
1489 ASSERT(promise->get_value() == write->get_value());
1492 promises->erase(promises->begin() + promise_index);
1501 * Compute the set of promises that could potentially be satisfied by this
1502 * action. Note that the set computation actually appears in the Node, not in
1504 * @param curr The ModelAction that may satisfy promises
1506 void ModelChecker::compute_promises(ModelAction *curr)
1508 for (unsigned int i = 0; i < promises->size(); i++) {
1509 Promise *promise = (*promises)[i];
1510 const ModelAction *act = promise->get_action();
1511 if (!act->happens_before(curr) &&
1513 !act->is_synchronizing(curr) &&
1514 !act->same_thread(curr) &&
1515 promise->get_value() == curr->get_value()) {
1516 curr->get_node()->set_promise(i);
1521 /** Checks promises in response to change in ClockVector Threads. */
1522 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1524 for (unsigned int i = 0; i < promises->size(); i++) {
1525 Promise *promise = (*promises)[i];
1526 const ModelAction *act = promise->get_action();
1527 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1528 merge_cv->synchronized_since(act)) {
1529 //This thread is no longer able to send values back to satisfy the promise
1530 int num_synchronized_threads = promise->increment_threads();
1531 if (num_synchronized_threads == get_num_threads()) {
1532 //Promise has failed
1533 failed_promise = true;
1541 * Build up an initial set of all past writes that this 'read' action may read
1542 * from. This set is determined by the clock vector's "happens before"
1544 * @param curr is the current ModelAction that we are exploring; it must be a
1547 void ModelChecker::build_reads_from_past(ModelAction *curr)
1549 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1551 ASSERT(curr->is_read());
1553 ModelAction *last_seq_cst = NULL;
1555 /* Track whether this object has been initialized */
1556 bool initialized = false;
1558 if (curr->is_seqcst()) {
1559 last_seq_cst = get_last_seq_cst(curr);
1560 /* We have to at least see the last sequentially consistent write,
1561 so we are initialized. */
1562 if (last_seq_cst != NULL)
1566 /* Iterate over all threads */
1567 for (i = 0; i < thrd_lists->size(); i++) {
1568 /* Iterate over actions in thread, starting from most recent */
1569 action_list_t *list = &(*thrd_lists)[i];
1570 action_list_t::reverse_iterator rit;
1571 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1572 ModelAction *act = *rit;
1574 /* Only consider 'write' actions */
1575 if (!act->is_write() || act == curr)
1578 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1579 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1580 DEBUG("Adding action to may_read_from:\n");
1581 if (DBG_ENABLED()) {
1585 curr->get_node()->add_read_from(act);
1588 /* Include at most one act per-thread that "happens before" curr */
1589 if (act->happens_before(curr)) {
1597 /** @todo Need a more informative way of reporting errors. */
1598 printf("ERROR: may read from uninitialized atomic\n");
1601 if (DBG_ENABLED() || !initialized) {
1602 printf("Reached read action:\n");
1604 printf("Printing may_read_from\n");
1605 curr->get_node()->print_may_read_from();
1606 printf("End printing may_read_from\n");
1609 ASSERT(initialized);
1612 static void print_list(action_list_t *list)
1614 action_list_t::iterator it;
1616 printf("---------------------------------------------------------------------\n");
1619 for (it = list->begin(); it != list->end(); it++) {
1622 printf("---------------------------------------------------------------------\n");
1625 #if SUPPORT_MOD_ORDER_DUMP
1626 void ModelChecker::dumpGraph(char *filename) {
1628 sprintf(buffer, "%s.dot",filename);
1629 FILE *file=fopen(buffer, "w");
1630 fprintf(file, "digraph %s {\n",filename);
1631 mo_graph->dumpNodes(file);
1632 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1634 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1635 ModelAction *action=*it;
1636 if (action->is_read()) {
1637 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1638 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1640 if (thread_array[action->get_tid()] != NULL) {
1641 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1644 thread_array[action->get_tid()]=action;
1646 fprintf(file,"}\n");
1647 model_free(thread_array);
1652 void ModelChecker::print_summary()
1655 printf("Number of executions: %d\n", num_executions);
1656 printf("Number of feasible executions: %d\n", num_feasible_executions);
1657 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1659 #if SUPPORT_MOD_ORDER_DUMP
1661 char buffername[100];
1662 sprintf(buffername, "exec%04u", num_executions);
1663 mo_graph->dumpGraphToFile(buffername);
1664 sprintf(buffername, "graph%04u", num_executions);
1665 dumpGraph(buffername);
1668 if (!isfinalfeasible())
1669 printf("INFEASIBLE EXECUTION!\n");
1670 print_list(action_trace);
1675 * Add a Thread to the system for the first time. Should only be called once
1677 * @param t The Thread to add
1679 void ModelChecker::add_thread(Thread *t)
1681 thread_map->put(id_to_int(t->get_id()), t);
1682 scheduler->add_thread(t);
1686 * Removes a thread from the scheduler.
1687 * @param the thread to remove.
1689 void ModelChecker::remove_thread(Thread *t)
1691 scheduler->remove_thread(t);
1695 * @brief Get a Thread reference by its ID
1696 * @param tid The Thread's ID
1697 * @return A Thread reference
1699 Thread * ModelChecker::get_thread(thread_id_t tid)
1701 return thread_map->get(id_to_int(tid));
1705 * @brief Get a reference to the Thread in which a ModelAction was executed
1706 * @param act The ModelAction
1707 * @return A Thread reference
1709 Thread * ModelChecker::get_thread(ModelAction *act)
1711 return get_thread(act->get_tid());
1715 * Switch from a user-context to the "master thread" context (a.k.a. system
1716 * context). This switch is made with the intention of exploring a particular
1717 * model-checking action (described by a ModelAction object). Must be called
1718 * from a user-thread context.
1720 * @param act The current action that will be explored. May be NULL only if
1721 * trace is exiting via an assertion (see ModelChecker::set_assert and
1722 * ModelChecker::has_asserted).
1723 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1725 int ModelChecker::switch_to_master(ModelAction *act)
1728 Thread *old = thread_current();
1729 set_current_action(act);
1730 old->set_state(THREAD_READY);
1731 return Thread::swap(old, &system_context);
1735 * Takes the next step in the execution, if possible.
1736 * @return Returns true (success) if a step was taken and false otherwise.
1738 bool ModelChecker::take_step() {
1742 Thread * curr = thread_current();
1744 if (curr->get_state() == THREAD_READY) {
1745 ASSERT(priv->current_action);
1747 priv->nextThread = check_current_action(priv->current_action);
1748 priv->current_action = NULL;
1750 if (curr->is_blocked() || curr->is_complete())
1751 scheduler->remove_thread(curr);
1756 Thread * next = scheduler->next_thread(priv->nextThread);
1758 /* Infeasible -> don't take any more steps */
1763 next->set_state(THREAD_RUNNING);
1764 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1766 /* next == NULL -> don't take any more steps */
1770 if ( next->get_pending() != NULL ) {
1771 //restart a pending action
1772 set_current_action(next->get_pending());
1773 next->set_pending(NULL);
1774 next->set_state(THREAD_READY);
1778 /* Return false only if swap fails with an error */
1779 return (Thread::swap(&system_context, next) == 0);
1782 /** Runs the current execution until threre are no more steps to take. */
1783 void ModelChecker::finish_execution() {
1786 while (take_step());