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", id_to_int(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 id_to_int(prev->get_tid()),
328 id_to_int(t->get_id()));
337 * Returns last backtracking point. The model checker will explore a different
338 * path for this point in the next execution.
339 * @return The ModelAction at which the next execution should diverge.
341 ModelAction * ModelChecker::get_next_backtrack()
343 ModelAction *next = priv->next_backtrack;
344 priv->next_backtrack = NULL;
349 * Processes a read or rmw model action.
350 * @param curr is the read model action to process.
351 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
352 * @return True if processing this read updates the mo_graph.
354 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
357 bool updated = false;
359 const ModelAction *reads_from = curr->get_node()->get_read_from();
360 if (reads_from != NULL) {
361 mo_graph->startChanges();
363 value = reads_from->get_value();
364 bool r_status = false;
366 if (!second_part_of_rmw) {
367 check_recency(curr, reads_from);
368 r_status = r_modification_order(curr, reads_from);
372 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
373 mo_graph->rollbackChanges();
374 too_many_reads = false;
378 curr->read_from(reads_from);
379 mo_graph->commitChanges();
381 } else if (!second_part_of_rmw) {
382 /* Read from future value */
383 value = curr->get_node()->get_future_value();
384 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
385 curr->read_from(NULL);
386 Promise *valuepromise = new Promise(curr, value, expiration);
387 promises->push_back(valuepromise);
389 get_thread(curr)->set_return_value(value);
395 * Processes a lock, trylock, or unlock model action. @param curr is
396 * the read model action to process.
398 * The try lock operation checks whether the lock is taken. If not,
399 * it falls to the normal lock operation case. If so, it returns
402 * The lock operation has already been checked that it is enabled, so
403 * it just grabs the lock and synchronizes with the previous unlock.
405 * The unlock operation has to re-enable all of the threads that are
406 * waiting on the lock.
408 * @return True if synchronization was updated; false otherwise
410 bool ModelChecker::process_mutex(ModelAction *curr) {
411 std::mutex *mutex = (std::mutex *)curr->get_location();
412 struct std::mutex_state *state = mutex->get_state();
413 switch (curr->get_type()) {
414 case ATOMIC_TRYLOCK: {
415 bool success = !state->islocked;
416 curr->set_try_lock(success);
418 get_thread(curr)->set_return_value(0);
421 get_thread(curr)->set_return_value(1);
423 //otherwise fall into the lock case
425 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
426 printf("Lock access before initialization\n");
429 state->islocked = true;
430 ModelAction *unlock = get_last_unlock(curr);
431 //synchronize with the previous unlock statement
432 if (unlock != NULL) {
433 curr->synchronize_with(unlock);
438 case ATOMIC_UNLOCK: {
440 state->islocked = false;
441 //wake up the other threads
442 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
443 //activate all the waiting threads
444 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
445 scheduler->wake(get_thread(*rit));
457 * Process a write ModelAction
458 * @param curr The ModelAction to process
459 * @return True if the mo_graph was updated or promises were resolved
461 bool ModelChecker::process_write(ModelAction *curr)
463 bool updated_mod_order = w_modification_order(curr);
464 bool updated_promises = resolve_promises(curr);
466 if (promises->size() == 0) {
467 for (unsigned int i = 0; i < futurevalues->size(); i++) {
468 struct PendingFutureValue pfv = (*futurevalues)[i];
469 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
470 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
471 priv->next_backtrack = pfv.act;
473 futurevalues->resize(0);
476 mo_graph->commitChanges();
477 get_thread(curr)->set_return_value(VALUE_NONE);
478 return updated_mod_order || updated_promises;
482 * @brief Process the current action for thread-related activity
484 * Performs current-action processing for a THREAD_* ModelAction. Proccesses
485 * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
486 * synchronization, etc. This function is a no-op for non-THREAD actions
487 * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
489 * @param curr The current action
490 * @return True if synchronization was updated or a thread completed
492 bool ModelChecker::process_thread_action(ModelAction *curr)
494 bool updated = false;
496 switch (curr->get_type()) {
497 case THREAD_CREATE: {
498 Thread *th = (Thread *)curr->get_location();
499 th->set_creation(curr);
503 Thread *waiting, *blocking;
504 waiting = get_thread(curr);
505 blocking = (Thread *)curr->get_location();
506 if (!blocking->is_complete()) {
507 blocking->push_wait_list(curr);
508 scheduler->sleep(waiting);
510 do_complete_join(curr);
511 updated = true; /* trigger rel-seq checks */
515 case THREAD_FINISH: {
516 Thread *th = get_thread(curr);
517 while (!th->wait_list_empty()) {
518 ModelAction *act = th->pop_wait_list();
519 Thread *wake = get_thread(act);
520 scheduler->wake(wake);
521 do_complete_join(act);
522 updated = true; /* trigger rel-seq checks */
525 updated = true; /* trigger rel-seq checks */
529 check_promises(NULL, curr->get_cv());
540 * Initialize the current action by performing one or more of the following
541 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
542 * in the NodeStack, manipulating backtracking sets, allocating and
543 * initializing clock vectors, and computing the promises to fulfill.
545 * @param curr The current action, as passed from the user context; may be
546 * freed/invalidated after the execution of this function
547 * @return The current action, as processed by the ModelChecker. Is only the
548 * same as the parameter @a curr if this is a newly-explored action.
550 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
552 ModelAction *newcurr;
554 if (curr->is_rmwc() || curr->is_rmw()) {
555 newcurr = process_rmw(curr);
558 if (newcurr->is_rmw())
559 compute_promises(newcurr);
563 curr->set_seq_number(get_next_seq_num());
565 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
567 /* First restore type and order in case of RMW operation */
569 newcurr->copy_typeandorder(curr);
571 ASSERT(curr->get_location() == newcurr->get_location());
572 newcurr->copy_from_new(curr);
574 /* Discard duplicate ModelAction; use action from NodeStack */
577 /* Always compute new clock vector */
578 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
582 /* Always compute new clock vector */
583 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
585 * Perform one-time actions when pushing new ModelAction onto
588 if (newcurr->is_write())
589 compute_promises(newcurr);
595 * This method checks whether a model action is enabled at the given point.
596 * At this point, it checks whether a lock operation would be successful at this point.
597 * If not, it puts the thread in a waiter list.
598 * @param curr is the ModelAction to check whether it is enabled.
599 * @return a bool that indicates whether the action is enabled.
601 bool ModelChecker::check_action_enabled(ModelAction *curr) {
602 if (curr->is_lock()) {
603 std::mutex * lock = (std::mutex *)curr->get_location();
604 struct std::mutex_state * state = lock->get_state();
605 if (state->islocked) {
606 //Stick the action in the appropriate waiting queue
607 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
616 * This is the heart of the model checker routine. It performs model-checking
617 * actions corresponding to a given "current action." Among other processes, it
618 * calculates reads-from relationships, updates synchronization clock vectors,
619 * forms a memory_order constraints graph, and handles replay/backtrack
620 * execution when running permutations of previously-observed executions.
622 * @param curr The current action to process
623 * @return The next Thread that must be executed. May be NULL if ModelChecker
624 * makes no choice (e.g., according to replay execution, combining RMW actions,
627 Thread * ModelChecker::check_current_action(ModelAction *curr)
631 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
633 if (!check_action_enabled(curr)) {
634 /* Make the execution look like we chose to run this action
635 * much later, when a lock is actually available to release */
636 get_current_thread()->set_pending(curr);
637 scheduler->sleep(get_current_thread());
638 return get_next_thread(NULL);
641 ModelAction *newcurr = initialize_curr_action(curr);
643 /* Add the action to lists before any other model-checking tasks */
644 if (!second_part_of_rmw)
645 add_action_to_lists(newcurr);
647 /* Build may_read_from set for newly-created actions */
648 if (curr == newcurr && curr->is_read())
649 build_reads_from_past(curr);
652 /* Initialize work_queue with the "current action" work */
653 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
655 while (!work_queue.empty()) {
656 WorkQueueEntry work = work_queue.front();
657 work_queue.pop_front();
660 case WORK_CHECK_CURR_ACTION: {
661 ModelAction *act = work.action;
662 bool update = false; /* update this location's release seq's */
663 bool update_all = false; /* update all release seq's */
665 if (process_thread_action(curr))
668 if (act->is_read() && process_read(act, second_part_of_rmw))
671 if (act->is_write() && process_write(act))
674 if (act->is_mutex_op() && process_mutex(act))
678 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
680 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
683 case WORK_CHECK_RELEASE_SEQ:
684 resolve_release_sequences(work.location, &work_queue);
686 case WORK_CHECK_MO_EDGES: {
687 /** @todo Complete verification of work_queue */
688 ModelAction *act = work.action;
689 bool updated = false;
691 if (act->is_read()) {
692 const ModelAction *rf = act->get_reads_from();
693 if (rf != NULL && r_modification_order(act, rf))
696 if (act->is_write()) {
697 if (w_modification_order(act))
700 mo_graph->commitChanges();
703 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
712 check_curr_backtracking(curr);
714 set_backtracking(curr);
716 return get_next_thread(curr);
720 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
721 * operation from the Thread it is joining with. Must be called after the
722 * completion of the Thread in question.
723 * @param join The THREAD_JOIN action
725 void ModelChecker::do_complete_join(ModelAction *join)
727 Thread *blocking = (Thread *)join->get_location();
728 ModelAction *act = get_last_action(blocking->get_id());
729 join->synchronize_with(act);
732 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
733 Node *currnode = curr->get_node();
734 Node *parnode = currnode->get_parent();
736 if ((!parnode->backtrack_empty() ||
737 !currnode->read_from_empty() ||
738 !currnode->future_value_empty() ||
739 !currnode->promise_empty())
740 && (!priv->next_backtrack ||
741 *curr > *priv->next_backtrack)) {
742 priv->next_backtrack = curr;
746 bool ModelChecker::promises_expired() {
747 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
748 Promise *promise = (*promises)[promise_index];
749 if (promise->get_expiration()<priv->used_sequence_numbers) {
756 /** @return whether the current partial trace must be a prefix of a
758 bool ModelChecker::isfeasibleprefix() {
759 return promises->size() == 0 && pending_acq_rel_seq->size() == 0;
762 /** @return whether the current partial trace is feasible. */
763 bool ModelChecker::isfeasible() {
764 if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
765 DEBUG("Infeasible: RMW violation\n");
767 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
770 /** @return whether the current partial trace is feasible other than
771 * multiple RMW reading from the same store. */
772 bool ModelChecker::isfeasibleotherthanRMW() {
774 if (mo_graph->checkForCycles())
775 DEBUG("Infeasible: modification order cycles\n");
777 DEBUG("Infeasible: failed promise\n");
779 DEBUG("Infeasible: too many reads\n");
780 if (bad_synchronization)
781 DEBUG("Infeasible: bad synchronization ordering\n");
782 if (promises_expired())
783 DEBUG("Infeasible: promises expired\n");
785 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
788 /** Returns whether the current completed trace is feasible. */
789 bool ModelChecker::isfinalfeasible() {
790 if (DBG_ENABLED() && promises->size() != 0)
791 DEBUG("Infeasible: unrevolved promises\n");
793 return isfeasible() && promises->size() == 0;
796 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
797 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
798 ModelAction *lastread = get_last_action(act->get_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 the previous read is unresolved, keep going...
945 if (prevreadfrom == NULL)
948 if (rf != prevreadfrom) {
949 mo_graph->addEdge(prevreadfrom, rf);
961 /** This method fixes up the modification order when we resolve a
962 * promises. The basic problem is that actions that occur after the
963 * read curr could not property add items to the modification order
966 * So for each thread, we find the earliest item that happens after
967 * the read curr. This is the item we have to fix up with additional
968 * constraints. If that action is write, we add a MO edge between
969 * the Action rf and that action. If the action is a read, we add a
970 * MO edge between the Action rf, and whatever the read accessed.
972 * @param curr is the read ModelAction that we are fixing up MO edges for.
973 * @param rf is the write ModelAction that curr reads from.
976 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
978 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
980 ASSERT(curr->is_read());
982 /* Iterate over all threads */
983 for (i = 0; i < thrd_lists->size(); i++) {
984 /* Iterate over actions in thread, starting from most recent */
985 action_list_t *list = &(*thrd_lists)[i];
986 action_list_t::reverse_iterator rit;
987 ModelAction *lastact = NULL;
989 /* Find last action that happens after curr that is either not curr or a rmw */
990 for (rit = list->rbegin(); rit != list->rend(); rit++) {
991 ModelAction *act = *rit;
992 if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
998 /* Include at most one act per-thread that "happens before" curr */
999 if (lastact != NULL) {
1000 if (lastact==curr) {
1001 //Case 1: The resolved read is a RMW, and we need to make sure
1002 //that the write portion of the RMW mod order after rf
1004 mo_graph->addEdge(rf, lastact);
1005 } else if (lastact->is_read()) {
1006 //Case 2: The resolved read is a normal read and the next
1007 //operation is a read, and we need to make sure the value read
1008 //is mod ordered after rf
1010 const ModelAction *postreadfrom = lastact->get_reads_from();
1011 if (postreadfrom != NULL&&rf != postreadfrom)
1012 mo_graph->addEdge(rf, postreadfrom);
1014 //Case 3: The resolved read is a normal read and the next
1015 //operation is a write, and we need to make sure that the
1016 //write is mod ordered after rf
1018 mo_graph->addEdge(rf, lastact);
1026 * Updates the mo_graph with the constraints imposed from the current write.
1028 * Basic idea is the following: Go through each other thread and find
1029 * the lastest action that happened before our write. Two cases:
1031 * (1) The action is a write => that write must occur before
1034 * (2) The action is a read => the write that that action read from
1035 * must occur before the current write.
1037 * This method also handles two other issues:
1039 * (I) Sequential Consistency: Making sure that if the current write is
1040 * seq_cst, that it occurs after the previous seq_cst write.
1042 * (II) Sending the write back to non-synchronizing reads.
1044 * @param curr The current action. Must be a write.
1045 * @return True if modification order edges were added; false otherwise
1047 bool ModelChecker::w_modification_order(ModelAction *curr)
1049 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1052 ASSERT(curr->is_write());
1054 if (curr->is_seqcst()) {
1055 /* We have to at least see the last sequentially consistent write,
1056 so we are initialized. */
1057 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1058 if (last_seq_cst != NULL) {
1059 mo_graph->addEdge(last_seq_cst, curr);
1064 /* Iterate over all threads */
1065 for (i = 0; i < thrd_lists->size(); i++) {
1066 /* Iterate over actions in thread, starting from most recent */
1067 action_list_t *list = &(*thrd_lists)[i];
1068 action_list_t::reverse_iterator rit;
1069 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1070 ModelAction *act = *rit;
1073 * 1) If RMW and it actually read from something, then we
1074 * already have all relevant edges, so just skip to next
1077 * 2) If RMW and it didn't read from anything, we should
1078 * whatever edge we can get to speed up convergence.
1080 * 3) If normal write, we need to look at earlier actions, so
1081 * continue processing list.
1083 if (curr->is_rmw()) {
1084 if (curr->get_reads_from()!=NULL)
1093 * Include at most one act per-thread that "happens
1096 if (act->happens_before(curr)) {
1098 * Note: if act is RMW, just add edge:
1100 * The following edge should be handled elsewhere:
1101 * readfrom(act) --mo--> act
1103 if (act->is_write())
1104 mo_graph->addEdge(act, curr);
1105 else if (act->is_read()) {
1106 //if previous read accessed a null, just keep going
1107 if (act->get_reads_from() == NULL)
1109 mo_graph->addEdge(act->get_reads_from(), curr);
1113 } else if (act->is_read() && !act->is_synchronizing(curr) &&
1114 !act->same_thread(curr)) {
1115 /* We have an action that:
1116 (1) did not happen before us
1117 (2) is a read and we are a write
1118 (3) cannot synchronize with us
1119 (4) is in a different thread
1121 that read could potentially read from our write.
1123 if (thin_air_constraint_may_allow(curr, act)) {
1125 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1126 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1127 futurevalues->push_back(pfv);
1137 /** Arbitrary reads from the future are not allowed. Section 29.3
1138 * part 9 places some constraints. This method checks one result of constraint
1139 * constraint. Others require compiler support. */
1140 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1141 if (!writer->is_rmw())
1144 if (!reader->is_rmw())
1147 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1148 if (search == reader)
1150 if (search->get_tid() == reader->get_tid() &&
1151 search->happens_before(reader))
1159 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1160 * The ModelAction under consideration is expected to be taking part in
1161 * release/acquire synchronization as an object of the "reads from" relation.
1162 * Note that this can only provide release sequence support for RMW chains
1163 * which do not read from the future, as those actions cannot be traced until
1164 * their "promise" is fulfilled. Similarly, we may not even establish the
1165 * presence of a release sequence with certainty, as some modification order
1166 * constraints may be decided further in the future. Thus, this function
1167 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1168 * and a boolean representing certainty.
1170 * @todo Finish lazy updating, when promises are fulfilled in the future
1171 * @param rf The action that might be part of a release sequence. Must be a
1173 * @param release_heads A pass-by-reference style return parameter. After
1174 * execution of this function, release_heads will contain the heads of all the
1175 * relevant release sequences, if any exists
1176 * @return true, if the ModelChecker is certain that release_heads is complete;
1179 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1181 /* Only check for release sequences if there are no cycles */
1182 if (mo_graph->checkForCycles())
1186 ASSERT(rf->is_write());
1188 if (rf->is_release())
1189 release_heads->push_back(rf);
1191 break; /* End of RMW chain */
1193 /** @todo Need to be smarter here... In the linux lock
1194 * example, this will run to the beginning of the program for
1196 /** @todo The way to be smarter here is to keep going until 1
1197 * thread has a release preceded by an acquire and you've seen
1200 /* acq_rel RMW is a sufficient stopping condition */
1201 if (rf->is_acquire() && rf->is_release())
1202 return true; /* complete */
1204 rf = rf->get_reads_from();
1207 /* read from future: need to settle this later */
1208 return false; /* incomplete */
1211 if (rf->is_release())
1212 return true; /* complete */
1214 /* else relaxed write; check modification order for contiguous subsequence
1215 * -> rf must be same thread as release */
1216 int tid = id_to_int(rf->get_tid());
1217 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1218 action_list_t *list = &(*thrd_lists)[tid];
1219 action_list_t::const_reverse_iterator rit;
1221 /* Find rf in the thread list */
1222 rit = std::find(list->rbegin(), list->rend(), rf);
1223 ASSERT(rit != list->rend());
1225 /* Find the last write/release */
1226 for (; rit != list->rend(); rit++)
1227 if ((*rit)->is_release())
1229 if (rit == list->rend()) {
1230 /* No write-release in this thread */
1231 return true; /* complete */
1233 ModelAction *release = *rit;
1235 ASSERT(rf->same_thread(release));
1237 bool certain = true;
1238 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1239 if (id_to_int(rf->get_tid()) == (int)i)
1241 list = &(*thrd_lists)[i];
1243 /* Can we ensure no future writes from this thread may break
1244 * the release seq? */
1245 bool future_ordered = false;
1247 ModelAction *last = get_last_action(int_to_id(i));
1248 if (last && (rf->happens_before(last) ||
1249 last->get_type() == THREAD_FINISH))
1250 future_ordered = true;
1252 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1253 const ModelAction *act = *rit;
1254 /* Reach synchronization -> this thread is complete */
1255 if (act->happens_before(release))
1257 if (rf->happens_before(act)) {
1258 future_ordered = true;
1262 /* Only writes can break release sequences */
1263 if (!act->is_write())
1266 /* Check modification order */
1267 if (mo_graph->checkReachable(rf, act)) {
1268 /* rf --mo--> act */
1269 future_ordered = true;
1272 if (mo_graph->checkReachable(act, release))
1273 /* act --mo--> release */
1275 if (mo_graph->checkReachable(release, act) &&
1276 mo_graph->checkReachable(act, rf)) {
1277 /* release --mo-> act --mo--> rf */
1278 return true; /* complete */
1282 if (!future_ordered)
1283 return false; /* This thread is uncertain */
1287 release_heads->push_back(release);
1292 * A public interface for getting the release sequence head(s) with which a
1293 * given ModelAction must synchronize. This function only returns a non-empty
1294 * result when it can locate a release sequence head with certainty. Otherwise,
1295 * it may mark the internal state of the ModelChecker so that it will handle
1296 * the release sequence at a later time, causing @a act to update its
1297 * synchronization at some later point in execution.
1298 * @param act The 'acquire' action that may read from a release sequence
1299 * @param release_heads A pass-by-reference return parameter. Will be filled
1300 * with the head(s) of the release sequence(s), if they exists with certainty.
1301 * @see ModelChecker::release_seq_head
1303 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1305 const ModelAction *rf = act->get_reads_from();
1307 complete = release_seq_head(rf, release_heads);
1309 /* add act to 'lazy checking' list */
1310 pending_acq_rel_seq->push_back(act);
1315 * Attempt to resolve all stashed operations that might synchronize with a
1316 * release sequence for a given location. This implements the "lazy" portion of
1317 * determining whether or not a release sequence was contiguous, since not all
1318 * modification order information is present at the time an action occurs.
1320 * @param location The location/object that should be checked for release
1321 * sequence resolutions. A NULL value means to check all locations.
1322 * @param work_queue The work queue to which to add work items as they are
1324 * @return True if any updates occurred (new synchronization, new mo_graph
1327 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1329 bool updated = false;
1330 std::vector<ModelAction *>::iterator it = pending_acq_rel_seq->begin();
1331 while (it != pending_acq_rel_seq->end()) {
1332 ModelAction *act = *it;
1334 /* Only resolve sequences on the given location, if provided */
1335 if (location && act->get_location() != location) {
1340 const ModelAction *rf = act->get_reads_from();
1341 rel_heads_list_t release_heads;
1343 complete = release_seq_head(rf, &release_heads);
1344 for (unsigned int i = 0; i < release_heads.size(); i++) {
1345 if (!act->has_synchronized_with(release_heads[i])) {
1346 if (act->synchronize_with(release_heads[i]))
1349 set_bad_synchronization();
1354 /* Re-check all pending release sequences */
1355 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1356 /* Re-check act for mo_graph edges */
1357 work_queue->push_back(MOEdgeWorkEntry(act));
1359 /* propagate synchronization to later actions */
1360 action_list_t::reverse_iterator rit = action_trace->rbegin();
1361 for (; (*rit) != act; rit++) {
1362 ModelAction *propagate = *rit;
1363 if (act->happens_before(propagate)) {
1364 propagate->synchronize_with(act);
1365 /* Re-check 'propagate' for mo_graph edges */
1366 work_queue->push_back(MOEdgeWorkEntry(propagate));
1371 it = pending_acq_rel_seq->erase(it);
1376 // If we resolved promises or data races, see if we have realized a data race.
1377 if (checkDataRaces()) {
1385 * Performs various bookkeeping operations for the current ModelAction. For
1386 * instance, adds action to the per-object, per-thread action vector and to the
1387 * action trace list of all thread actions.
1389 * @param act is the ModelAction to add.
1391 void ModelChecker::add_action_to_lists(ModelAction *act)
1393 int tid = id_to_int(act->get_tid());
1394 action_trace->push_back(act);
1396 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1398 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1399 if (tid >= (int)vec->size())
1400 vec->resize(priv->next_thread_id);
1401 (*vec)[tid].push_back(act);
1403 if ((int)thrd_last_action->size() <= tid)
1404 thrd_last_action->resize(get_num_threads());
1405 (*thrd_last_action)[tid] = act;
1409 * @brief Get the last action performed by a particular Thread
1410 * @param tid The thread ID of the Thread in question
1411 * @return The last action in the thread
1413 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1415 int threadid = id_to_int(tid);
1416 if (threadid < (int)thrd_last_action->size())
1417 return (*thrd_last_action)[id_to_int(tid)];
1423 * Gets the last memory_order_seq_cst write (in the total global sequence)
1424 * performed on a particular object (i.e., memory location), not including the
1426 * @param curr The current ModelAction; also denotes the object location to
1428 * @return The last seq_cst write
1430 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1432 void *location = curr->get_location();
1433 action_list_t *list = obj_map->get_safe_ptr(location);
1434 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1435 action_list_t::reverse_iterator rit;
1436 for (rit = list->rbegin(); rit != list->rend(); rit++)
1437 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1443 * Gets the last unlock operation performed on a particular mutex (i.e., memory
1444 * location). This function identifies the mutex according to the current
1445 * action, which is presumed to perform on the same mutex.
1446 * @param curr The current ModelAction; also denotes the object location to
1448 * @return The last unlock operation
1450 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1452 void *location = curr->get_location();
1453 action_list_t *list = obj_map->get_safe_ptr(location);
1454 /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1455 action_list_t::reverse_iterator rit;
1456 for (rit = list->rbegin(); rit != list->rend(); rit++)
1457 if ((*rit)->is_unlock())
1462 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1464 ModelAction *parent = get_last_action(tid);
1466 parent = get_thread(tid)->get_creation();
1471 * Returns the clock vector for a given thread.
1472 * @param tid The thread whose clock vector we want
1473 * @return Desired clock vector
1475 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1477 return get_parent_action(tid)->get_cv();
1481 * Resolve a set of Promises with a current write. The set is provided in the
1482 * Node corresponding to @a write.
1483 * @param write The ModelAction that is fulfilling Promises
1484 * @return True if promises were resolved; false otherwise
1486 bool ModelChecker::resolve_promises(ModelAction *write)
1488 bool resolved = false;
1490 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1491 Promise *promise = (*promises)[promise_index];
1492 if (write->get_node()->get_promise(i)) {
1493 ModelAction *read = promise->get_action();
1494 if (read->is_rmw()) {
1495 mo_graph->addRMWEdge(write, read);
1497 read->read_from(write);
1498 //First fix up the modification order for actions that happened
1500 r_modification_order(read, write);
1501 //Next fix up the modification order for actions that happened
1503 post_r_modification_order(read, write);
1504 //Make sure the promise's value matches the write's value
1505 ASSERT(promise->get_value() == write->get_value());
1508 promises->erase(promises->begin() + promise_index);
1517 * Compute the set of promises that could potentially be satisfied by this
1518 * action. Note that the set computation actually appears in the Node, not in
1520 * @param curr The ModelAction that may satisfy promises
1522 void ModelChecker::compute_promises(ModelAction *curr)
1524 for (unsigned int i = 0; i < promises->size(); i++) {
1525 Promise *promise = (*promises)[i];
1526 const ModelAction *act = promise->get_action();
1527 if (!act->happens_before(curr) &&
1529 !act->is_synchronizing(curr) &&
1530 !act->same_thread(curr) &&
1531 promise->get_value() == curr->get_value()) {
1532 curr->get_node()->set_promise(i);
1537 /** Checks promises in response to change in ClockVector Threads. */
1538 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1540 for (unsigned int i = 0; i < promises->size(); i++) {
1541 Promise *promise = (*promises)[i];
1542 const ModelAction *act = promise->get_action();
1543 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1544 merge_cv->synchronized_since(act)) {
1545 //This thread is no longer able to send values back to satisfy the promise
1546 int num_synchronized_threads = promise->increment_threads();
1547 if (num_synchronized_threads == get_num_threads()) {
1548 //Promise has failed
1549 failed_promise = true;
1557 * Build up an initial set of all past writes that this 'read' action may read
1558 * from. This set is determined by the clock vector's "happens before"
1560 * @param curr is the current ModelAction that we are exploring; it must be a
1563 void ModelChecker::build_reads_from_past(ModelAction *curr)
1565 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1567 ASSERT(curr->is_read());
1569 ModelAction *last_seq_cst = NULL;
1571 /* Track whether this object has been initialized */
1572 bool initialized = false;
1574 if (curr->is_seqcst()) {
1575 last_seq_cst = get_last_seq_cst(curr);
1576 /* We have to at least see the last sequentially consistent write,
1577 so we are initialized. */
1578 if (last_seq_cst != NULL)
1582 /* Iterate over all threads */
1583 for (i = 0; i < thrd_lists->size(); i++) {
1584 /* Iterate over actions in thread, starting from most recent */
1585 action_list_t *list = &(*thrd_lists)[i];
1586 action_list_t::reverse_iterator rit;
1587 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1588 ModelAction *act = *rit;
1590 /* Only consider 'write' actions */
1591 if (!act->is_write() || act == curr)
1594 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1595 if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1596 DEBUG("Adding action to may_read_from:\n");
1597 if (DBG_ENABLED()) {
1601 curr->get_node()->add_read_from(act);
1604 /* Include at most one act per-thread that "happens before" curr */
1605 if (act->happens_before(curr)) {
1613 /** @todo Need a more informative way of reporting errors. */
1614 printf("ERROR: may read from uninitialized atomic\n");
1617 if (DBG_ENABLED() || !initialized) {
1618 printf("Reached read action:\n");
1620 printf("Printing may_read_from\n");
1621 curr->get_node()->print_may_read_from();
1622 printf("End printing may_read_from\n");
1625 ASSERT(initialized);
1628 static void print_list(action_list_t *list)
1630 action_list_t::iterator it;
1632 printf("---------------------------------------------------------------------\n");
1635 for (it = list->begin(); it != list->end(); it++) {
1638 printf("---------------------------------------------------------------------\n");
1641 #if SUPPORT_MOD_ORDER_DUMP
1642 void ModelChecker::dumpGraph(char *filename) {
1644 sprintf(buffer, "%s.dot",filename);
1645 FILE *file=fopen(buffer, "w");
1646 fprintf(file, "digraph %s {\n",filename);
1647 mo_graph->dumpNodes(file);
1648 ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1650 for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1651 ModelAction *action=*it;
1652 if (action->is_read()) {
1653 fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1654 if (action->get_reads_from()!=NULL)
1655 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1657 if (thread_array[action->get_tid()] != NULL) {
1658 fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1661 thread_array[action->get_tid()]=action;
1663 fprintf(file,"}\n");
1664 model_free(thread_array);
1669 void ModelChecker::print_summary()
1672 printf("Number of executions: %d\n", num_executions);
1673 printf("Number of feasible executions: %d\n", num_feasible_executions);
1674 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1676 #if SUPPORT_MOD_ORDER_DUMP
1678 char buffername[100];
1679 sprintf(buffername, "exec%04u", num_executions);
1680 mo_graph->dumpGraphToFile(buffername);
1681 sprintf(buffername, "graph%04u", num_executions);
1682 dumpGraph(buffername);
1685 if (!isfinalfeasible())
1686 printf("INFEASIBLE EXECUTION!\n");
1687 print_list(action_trace);
1692 * Add a Thread to the system for the first time. Should only be called once
1694 * @param t The Thread to add
1696 void ModelChecker::add_thread(Thread *t)
1698 thread_map->put(id_to_int(t->get_id()), t);
1699 scheduler->add_thread(t);
1703 * Removes a thread from the scheduler.
1704 * @param the thread to remove.
1706 void ModelChecker::remove_thread(Thread *t)
1708 scheduler->remove_thread(t);
1712 * @brief Get a Thread reference by its ID
1713 * @param tid The Thread's ID
1714 * @return A Thread reference
1716 Thread * ModelChecker::get_thread(thread_id_t tid) const
1718 return thread_map->get(id_to_int(tid));
1722 * @brief Get a reference to the Thread in which a ModelAction was executed
1723 * @param act The ModelAction
1724 * @return A Thread reference
1726 Thread * ModelChecker::get_thread(ModelAction *act) const
1728 return get_thread(act->get_tid());
1732 * Switch from a user-context to the "master thread" context (a.k.a. system
1733 * context). This switch is made with the intention of exploring a particular
1734 * model-checking action (described by a ModelAction object). Must be called
1735 * from a user-thread context.
1737 * @param act The current action that will be explored. May be NULL only if
1738 * trace is exiting via an assertion (see ModelChecker::set_assert and
1739 * ModelChecker::has_asserted).
1740 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1742 int ModelChecker::switch_to_master(ModelAction *act)
1745 Thread *old = thread_current();
1746 set_current_action(act);
1747 old->set_state(THREAD_READY);
1748 return Thread::swap(old, &system_context);
1752 * Takes the next step in the execution, if possible.
1753 * @return Returns true (success) if a step was taken and false otherwise.
1755 bool ModelChecker::take_step() {
1759 Thread *curr = thread_current();
1761 if (curr->get_state() == THREAD_READY) {
1762 ASSERT(priv->current_action);
1764 priv->nextThread = check_current_action(priv->current_action);
1765 priv->current_action = NULL;
1767 if (curr->is_blocked() || curr->is_complete())
1768 scheduler->remove_thread(curr);
1773 Thread *next = scheduler->next_thread(priv->nextThread);
1775 /* Infeasible -> don't take any more steps */
1779 DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1780 next ? id_to_int(next->get_id()) : -1);
1782 /* next == NULL -> don't take any more steps */
1786 next->set_state(THREAD_RUNNING);
1788 if (next->get_pending() != NULL) {
1789 /* restart a pending action */
1790 set_current_action(next->get_pending());
1791 next->set_pending(NULL);
1792 next->set_state(THREAD_READY);
1796 /* Return false only if swap fails with an error */
1797 return (Thread::swap(&system_context, next) == 0);
1800 /** Runs the current execution until threre are no more steps to take. */
1801 void ModelChecker::finish_execution() {
1804 while (take_step());