8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
15 #define INITIAL_THREAD_ID 0
19 /** @brief Constructor */
20 ModelChecker::ModelChecker(struct model_params params) :
21 /* Initialize default scheduler */
22 scheduler(new Scheduler()),
26 action_trace(new action_list_t()),
27 thread_map(new HashTable<int, Thread *, int>()),
28 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
29 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
30 promises(new std::vector<Promise *>()),
31 lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
32 thrd_last_action(new std::vector<ModelAction *>(1)),
33 node_stack(new NodeStack()),
34 mo_graph(new CycleGraph()),
35 failed_promise(false),
38 /* Allocate this "size" on the snapshotting heap */
39 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
40 /* First thread created will have id INITIAL_THREAD_ID */
41 priv->next_thread_id = INITIAL_THREAD_ID;
43 lazy_sync_size = &priv->lazy_sync_size;
46 /** @brief Destructor */
47 ModelChecker::~ModelChecker()
49 for (int i = 0; i < get_num_threads(); i++)
50 delete thread_map->get(i);
57 for (unsigned int i = 0; i < promises->size(); i++)
58 delete (*promises)[i];
61 delete lazy_sync_with_release;
63 delete thrd_last_action;
70 * Restores user program to initial state and resets all model-checker data
73 void ModelChecker::reset_to_initial_state()
75 DEBUG("+++ Resetting to initial state +++\n");
76 node_stack->reset_execution();
77 failed_promise = false;
79 snapshotObject->backTrackBeforeStep(0);
82 /** @returns a thread ID for a new Thread */
83 thread_id_t ModelChecker::get_next_id()
85 return priv->next_thread_id++;
88 /** @returns the number of user threads created during this execution */
89 int ModelChecker::get_num_threads()
91 return priv->next_thread_id;
94 /** @returns a sequence number for a new ModelAction */
95 modelclock_t ModelChecker::get_next_seq_num()
97 return ++priv->used_sequence_numbers;
101 * @brief Choose the next thread to execute.
103 * This function chooses the next thread that should execute. It can force the
104 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
105 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
106 * The model-checker may have no preference regarding the next thread (i.e.,
107 * when exploring a new execution ordering), in which case this will return
109 * @param curr The current ModelAction. This action might guide the choice of
111 * @return The next thread to run. If the model-checker has no preference, NULL.
113 Thread * ModelChecker::get_next_thread(ModelAction *curr)
117 /* Do not split atomic actions. */
119 return thread_current();
120 /* The THREAD_CREATE action points to the created Thread */
121 else if (curr->get_type() == THREAD_CREATE)
122 return (Thread *)curr->get_location();
124 /* Have we completed exploring the preselected path? */
128 /* Else, we are trying to replay an execution */
129 ModelAction *next = node_stack->get_next()->get_action();
131 if (next == diverge) {
132 Node *nextnode = next->get_node();
133 /* Reached divergence point */
134 if (nextnode->increment_promise()) {
135 /* The next node will try to satisfy a different set of promises. */
136 tid = next->get_tid();
137 node_stack->pop_restofstack(2);
138 } else if (nextnode->increment_read_from()) {
139 /* The next node will read from a different value. */
140 tid = next->get_tid();
141 node_stack->pop_restofstack(2);
142 } else if (nextnode->increment_future_value()) {
143 /* The next node will try to read from a different future value. */
144 tid = next->get_tid();
145 node_stack->pop_restofstack(2);
147 /* Make a different thread execute for next step */
148 Node *node = nextnode->get_parent();
149 tid = node->get_next_backtrack();
150 node_stack->pop_restofstack(1);
152 DEBUG("*** Divergence point ***\n");
155 tid = next->get_tid();
157 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
158 ASSERT(tid != THREAD_ID_T_NONE);
159 return thread_map->get(id_to_int(tid));
163 * Queries the model-checker for more executions to explore and, if one
164 * exists, resets the model-checker state to execute a new execution.
166 * @return If there are more executions to explore, return true. Otherwise,
169 bool ModelChecker::next_execution()
175 if (isfinalfeasible() || DBG_ENABLED())
178 if ((diverge = get_next_backtrack()) == NULL)
182 printf("Next execution will diverge at:\n");
186 reset_to_initial_state();
190 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
192 action_type type = act->get_type();
202 /* linear search: from most recent to oldest */
203 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
204 action_list_t::reverse_iterator rit;
205 for (rit = list->rbegin(); rit != list->rend(); rit++) {
206 ModelAction *prev = *rit;
207 if (act->is_synchronizing(prev))
213 void ModelChecker::set_backtracking(ModelAction *act)
217 Thread *t = get_thread(act->get_tid());
219 prev = get_last_conflict(act);
223 node = prev->get_node()->get_parent();
225 while (!node->is_enabled(t))
228 /* Check if this has been explored already */
229 if (node->has_been_explored(t->get_id()))
232 /* Cache the latest backtracking point */
233 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
234 priv->next_backtrack = prev;
236 /* If this is a new backtracking point, mark the tree */
237 if (!node->set_backtrack(t->get_id()))
239 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
240 prev->get_tid(), t->get_id());
248 * Returns last backtracking point. The model checker will explore a different
249 * path for this point in the next execution.
250 * @return The ModelAction at which the next execution should diverge.
252 ModelAction * ModelChecker::get_next_backtrack()
254 ModelAction *next = priv->next_backtrack;
255 priv->next_backtrack = NULL;
260 * This is the heart of the model checker routine. It performs model-checking
261 * actions corresponding to a given "current action." Among other processes, it
262 * calculates reads-from relationships, updates synchronization clock vectors,
263 * forms a memory_order constraints graph, and handles replay/backtrack
264 * execution when running permutations of previously-observed executions.
266 * @param curr The current action to process
267 * @return The next Thread that must be executed. May be NULL if ModelChecker
268 * makes no choice (e.g., according to replay execution, combining RMW actions,
271 Thread * ModelChecker::check_current_action(ModelAction *curr)
273 bool already_added = false;
277 if (curr->is_rmwc() || curr->is_rmw()) {
278 ModelAction *tmp = process_rmw(curr);
279 already_added = true;
283 ModelAction *tmp = node_stack->explore_action(curr);
285 /* Discard duplicate ModelAction; use action from NodeStack */
286 /* First restore type and order in case of RMW operation */
288 tmp->copy_typeandorder(curr);
290 /* If we have diverged, we need to reset the clock vector. */
292 tmp->create_cv(get_parent_action(tmp->get_tid()));
298 * Perform one-time actions when pushing new ModelAction onto
301 curr->create_cv(get_parent_action(curr->get_tid()));
302 /* Build may_read_from set */
304 build_reads_from_past(curr);
305 if (curr->is_write())
306 compute_promises(curr);
310 /* Thread specific actions */
311 switch(curr->get_type()) {
312 case THREAD_CREATE: {
313 Thread *th = (Thread *)curr->get_location();
314 th->set_creation(curr);
319 wait = get_thread(curr->get_tid());
320 join = (Thread *)curr->get_location();
321 if (!join->is_complete())
322 scheduler->wait(wait, join);
325 case THREAD_FINISH: {
326 Thread *th = get_thread(curr->get_tid());
327 while (!th->wait_list_empty()) {
328 Thread *wake = th->pop_wait_list();
329 scheduler->wake(wake);
335 check_promises(NULL, curr->get_cv());
342 /* Assign reads_from values */
343 Thread *th = get_thread(curr->get_tid());
344 uint64_t value = VALUE_NONE;
345 bool updated = false;
346 if (curr->is_read()) {
347 const ModelAction *reads_from = curr->get_node()->get_read_from();
348 if (reads_from != NULL) {
349 value = reads_from->get_value();
350 /* Assign reads_from, perform release/acquire synchronization */
351 curr->read_from(reads_from);
352 if (r_modification_order(curr,reads_from))
355 /* Read from future value */
356 value = curr->get_node()->get_future_value();
357 curr->read_from(NULL);
358 Promise *valuepromise = new Promise(curr, value);
359 promises->push_back(valuepromise);
361 } else if (curr->is_write()) {
362 if (w_modification_order(curr))
364 if (resolve_promises(curr))
369 resolve_release_sequences(curr->get_location());
371 th->set_return_value(value);
373 /* Add action to list. */
375 add_action_to_lists(curr);
377 Node *currnode = curr->get_node();
378 Node *parnode = currnode->get_parent();
380 if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
381 !currnode->future_value_empty() || !currnode->promise_empty())
382 if (!priv->next_backtrack || *curr > *priv->next_backtrack)
383 priv->next_backtrack = curr;
385 set_backtracking(curr);
387 return get_next_thread(curr);
390 /** @returns whether the current partial trace must be a prefix of a
392 bool ModelChecker::isfeasibleprefix() {
393 return promises->size() == 0 && *lazy_sync_size == 0;
396 /** @returns whether the current partial trace is feasible. */
397 bool ModelChecker::isfeasible() {
398 return !mo_graph->checkForCycles() && !failed_promise;
401 /** Returns whether the current completed trace is feasible. */
402 bool ModelChecker::isfinalfeasible() {
403 return isfeasible() && promises->size() == 0;
406 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
407 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
408 int tid = id_to_int(act->get_tid());
409 ModelAction *lastread = get_last_action(tid);
410 lastread->process_rmw(act);
412 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
417 * Updates the mo_graph with the constraints imposed from the current read.
418 * @param curr The current action. Must be a read.
419 * @param rf The action that curr reads from. Must be a write.
420 * @return True if modification order edges were added; false otherwise
422 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
424 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
427 ASSERT(curr->is_read());
429 /* Iterate over all threads */
430 for (i = 0; i < thrd_lists->size(); i++) {
431 /* Iterate over actions in thread, starting from most recent */
432 action_list_t *list = &(*thrd_lists)[i];
433 action_list_t::reverse_iterator rit;
434 for (rit = list->rbegin(); rit != list->rend(); rit++) {
435 ModelAction *act = *rit;
437 /* Include at most one act per-thread that "happens before" curr */
438 if (act->happens_before(curr)) {
439 if (act->is_read()) {
440 const ModelAction *prevreadfrom = act->get_reads_from();
441 if (prevreadfrom != NULL && rf != prevreadfrom) {
442 mo_graph->addEdge(prevreadfrom, rf);
445 } else if (rf != act) {
446 mo_graph->addEdge(act, rf);
457 /** Updates the mo_graph with the constraints imposed from the current read. */
458 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
460 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
462 ASSERT(curr->is_read());
464 /* Iterate over all threads */
465 for (i = 0; i < thrd_lists->size(); i++) {
466 /* Iterate over actions in thread, starting from most recent */
467 action_list_t *list = &(*thrd_lists)[i];
468 action_list_t::reverse_iterator rit;
469 ModelAction *lastact = NULL;
471 /* Find last action that happens after curr */
472 for (rit = list->rbegin(); rit != list->rend(); rit++) {
473 ModelAction *act = *rit;
474 if (curr->happens_before(act)) {
480 /* Include at most one act per-thread that "happens before" curr */
481 if (lastact != NULL) {
482 if (lastact->is_read()) {
483 const ModelAction *postreadfrom = lastact->get_reads_from();
484 if (postreadfrom != NULL&&rf != postreadfrom)
485 mo_graph->addEdge(rf, postreadfrom);
486 } else if (rf != lastact) {
487 mo_graph->addEdge(rf, lastact);
495 * Updates the mo_graph with the constraints imposed from the current write.
496 * @param curr The current action. Must be a write.
497 * @return True if modification order edges were added; false otherwise
499 bool ModelChecker::w_modification_order(ModelAction *curr)
501 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
504 ASSERT(curr->is_write());
506 if (curr->is_seqcst()) {
507 /* We have to at least see the last sequentially consistent write,
508 so we are initialized. */
509 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
510 if (last_seq_cst != NULL) {
511 mo_graph->addEdge(last_seq_cst, curr);
516 /* Iterate over all threads */
517 for (i = 0; i < thrd_lists->size(); i++) {
518 /* Iterate over actions in thread, starting from most recent */
519 action_list_t *list = &(*thrd_lists)[i];
520 action_list_t::reverse_iterator rit;
521 for (rit = list->rbegin(); rit != list->rend(); rit++) {
522 ModelAction *act = *rit;
524 /* Include at most one act per-thread that "happens before" curr */
525 if (act->happens_before(curr)) {
527 mo_graph->addEdge(act->get_reads_from(), curr);
529 mo_graph->addEdge(act, curr);
532 } else if (act->is_read() && !act->is_synchronizing(curr) &&
533 !act->same_thread(curr)) {
534 /* We have an action that:
535 (1) did not happen before us
536 (2) is a read and we are a write
537 (3) cannot synchronize with us
538 (4) is in a different thread
540 that read could potentially read from our write.
542 if (act->get_node()->add_future_value(curr->get_value()) &&
543 (!priv->next_backtrack || *act > *priv->next_backtrack))
544 priv->next_backtrack = act;
553 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
554 * The ModelAction under consideration is expected to be taking part in
555 * release/acquire synchronization as an object of the "reads from" relation.
556 * Note that this can only provide release sequence support for RMW chains
557 * which do not read from the future, as those actions cannot be traced until
558 * their "promise" is fulfilled. Similarly, we may not even establish the
559 * presence of a release sequence with certainty, as some modification order
560 * constraints may be decided further in the future. Thus, this function
561 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
562 * and a boolean representing certainty.
564 * @todo Finish lazy updating, when promises are fulfilled in the future
565 * @param rf The action that might be part of a release sequence. Must be a
567 * @param release_heads A pass-by-reference style return parameter. After
568 * execution of this function, release_heads will contain the heads of all the
569 * relevant release sequences, if any exists
570 * @return true, if the ModelChecker is certain that release_heads is complete;
573 bool ModelChecker::release_seq_head(const ModelAction *rf,
574 std::vector<const ModelAction *> *release_heads) const
576 ASSERT(rf->is_write());
578 /* read from future: need to settle this later */
579 return false; /* incomplete */
581 if (rf->is_release())
582 release_heads->push_back(rf);
584 /* We need a RMW action that is both an acquire and release to stop */
585 /** @todo Need to be smarter here... In the linux lock
586 * example, this will run to the beginning of the program for
588 if (rf->is_acquire() && rf->is_release())
589 return true; /* complete */
590 return release_seq_head(rf->get_reads_from(), release_heads);
592 if (rf->is_release())
593 return true; /* complete */
595 /* else relaxed write; check modification order for contiguous subsequence
596 * -> rf must be same thread as release */
597 int tid = id_to_int(rf->get_tid());
598 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
599 action_list_t *list = &(*thrd_lists)[tid];
600 action_list_t::const_reverse_iterator rit;
602 /* Find rf in the thread list */
603 rit = std::find(list->rbegin(), list->rend(), rf);
604 ASSERT(rit != list->rend());
606 /* Find the last write/release */
607 for (; rit != list->rend(); rit++)
608 if ((*rit)->is_release())
610 if (rit == list->rend()) {
611 /* No write-release in this thread */
612 return true; /* complete */
614 ModelAction *release = *rit;
616 ASSERT(rf->same_thread(release));
619 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
620 if (id_to_int(rf->get_tid()) == (int)i)
622 list = &(*thrd_lists)[i];
624 /* Can we ensure no future writes from this thread may break
625 * the release seq? */
626 bool future_ordered = false;
628 for (rit = list->rbegin(); rit != list->rend(); rit++) {
629 const ModelAction *act = *rit;
630 if (!act->is_write())
632 /* Reach synchronization -> this thread is complete */
633 if (act->happens_before(release))
635 if (rf->happens_before(act)) {
636 future_ordered = true;
640 /* Check modification order */
641 if (mo_graph->checkReachable(rf, act)) {
643 future_ordered = true;
646 if (mo_graph->checkReachable(act, release))
647 /* act --mo--> release */
649 if (mo_graph->checkReachable(release, act) &&
650 mo_graph->checkReachable(act, rf)) {
651 /* release --mo-> act --mo--> rf */
652 return true; /* complete */
657 return false; /* This thread is uncertain */
661 release_heads->push_back(release);
666 * A public interface for getting the release sequence head(s) with which a
667 * given ModelAction must synchronize. This function only returns a non-empty
668 * result when it can locate a release sequence head with certainty. Otherwise,
669 * it may mark the internal state of the ModelChecker so that it will handle
670 * the release sequence at a later time, causing @a act to update its
671 * synchronization at some later point in execution.
672 * @param act The 'acquire' action that may read from a release sequence
673 * @param release_heads A pass-by-reference return parameter. Will be filled
674 * with the head(s) of the release sequence(s), if they exists with certainty.
675 * @see ModelChecker::release_seq_head
677 void ModelChecker::get_release_seq_heads(ModelAction *act,
678 std::vector<const ModelAction *> *release_heads)
680 const ModelAction *rf = act->get_reads_from();
682 complete = release_seq_head(rf, release_heads);
684 /* add act to 'lazy checking' list */
685 std::list<ModelAction *> *list;
686 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
687 list->push_back(act);
693 * Attempt to resolve all stashed operations that might synchronize with a
694 * release sequence for a given location. This implements the "lazy" portion of
695 * determining whether or not a release sequence was contiguous, since not all
696 * modification order information is present at the time an action occurs.
698 * @param location The location/object that should be checked for release
699 * sequence resolutions
700 * @return True if any updates occurred (new synchronization, new mo_graph edges)
702 bool ModelChecker::resolve_release_sequences(void *location)
704 std::list<ModelAction *> *list;
705 list = lazy_sync_with_release->getptr(location);
709 bool updated = false;
710 std::list<ModelAction *>::iterator it = list->begin();
711 while (it != list->end()) {
712 ModelAction *act = *it;
713 const ModelAction *rf = act->get_reads_from();
714 std::vector<const ModelAction *> release_heads;
716 complete = release_seq_head(rf, &release_heads);
717 for (unsigned int i = 0; i < release_heads.size(); i++) {
718 if (!act->has_synchronized_with(release_heads[i])) {
720 act->synchronize_with(release_heads[i]);
725 /* propagate synchronization to later actions */
726 action_list_t::reverse_iterator it = action_trace->rbegin();
727 while ((*it) != act) {
728 ModelAction *propagate = *it;
729 if (act->happens_before(propagate))
730 /** @todo new mo_graph edges along with
731 * this synchronization? */
732 propagate->synchronize_with(act);
736 it = list->erase(it);
742 // If we resolved promises or data races, see if we have realized a data race.
743 if (checkDataRaces()) {
751 * Performs various bookkeeping operations for the current ModelAction. For
752 * instance, adds action to the per-object, per-thread action vector and to the
753 * action trace list of all thread actions.
755 * @param act is the ModelAction to add.
757 void ModelChecker::add_action_to_lists(ModelAction *act)
759 int tid = id_to_int(act->get_tid());
760 action_trace->push_back(act);
762 obj_map->get_safe_ptr(act->get_location())->push_back(act);
764 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
765 if (tid >= (int)vec->size())
766 vec->resize(priv->next_thread_id);
767 (*vec)[tid].push_back(act);
769 if ((int)thrd_last_action->size() <= tid)
770 thrd_last_action->resize(get_num_threads());
771 (*thrd_last_action)[tid] = act;
774 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
776 int nthreads = get_num_threads();
777 if ((int)thrd_last_action->size() < nthreads)
778 thrd_last_action->resize(nthreads);
779 return (*thrd_last_action)[id_to_int(tid)];
783 * Gets the last memory_order_seq_cst action (in the total global sequence)
784 * performed on a particular object (i.e., memory location).
785 * @param location The object location to check
786 * @return The last seq_cst action performed
788 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
790 action_list_t *list = obj_map->get_safe_ptr(location);
791 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
792 action_list_t::reverse_iterator rit;
793 for (rit = list->rbegin(); rit != list->rend(); rit++)
794 if ((*rit)->is_write() && (*rit)->is_seqcst())
799 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
801 ModelAction *parent = get_last_action(tid);
803 parent = get_thread(tid)->get_creation();
808 * Returns the clock vector for a given thread.
809 * @param tid The thread whose clock vector we want
810 * @return Desired clock vector
812 ClockVector * ModelChecker::get_cv(thread_id_t tid)
814 return get_parent_action(tid)->get_cv();
818 * Resolve a set of Promises with a current write. The set is provided in the
819 * Node corresponding to @a write.
820 * @param write The ModelAction that is fulfilling Promises
821 * @return True if promises were resolved; false otherwise
823 bool ModelChecker::resolve_promises(ModelAction *write)
825 bool resolved = false;
826 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
827 Promise *promise = (*promises)[promise_index];
828 if (write->get_node()->get_promise(i)) {
829 ModelAction *read = promise->get_action();
830 read->read_from(write);
831 r_modification_order(read, write);
832 post_r_modification_order(read, write);
833 promises->erase(promises->begin() + promise_index);
843 * Compute the set of promises that could potentially be satisfied by this
844 * action. Note that the set computation actually appears in the Node, not in
846 * @param curr The ModelAction that may satisfy promises
848 void ModelChecker::compute_promises(ModelAction *curr)
850 for (unsigned int i = 0; i < promises->size(); i++) {
851 Promise *promise = (*promises)[i];
852 const ModelAction *act = promise->get_action();
853 if (!act->happens_before(curr) &&
855 !act->is_synchronizing(curr) &&
856 !act->same_thread(curr) &&
857 promise->get_value() == curr->get_value()) {
858 curr->get_node()->set_promise(i);
863 /** Checks promises in response to change in ClockVector Threads. */
864 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
866 for (unsigned int i = 0; i < promises->size(); i++) {
867 Promise *promise = (*promises)[i];
868 const ModelAction *act = promise->get_action();
869 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
870 merge_cv->synchronized_since(act)) {
871 //This thread is no longer able to send values back to satisfy the promise
872 int num_synchronized_threads = promise->increment_threads();
873 if (num_synchronized_threads == get_num_threads()) {
875 failed_promise = true;
883 * Build up an initial set of all past writes that this 'read' action may read
884 * from. This set is determined by the clock vector's "happens before"
886 * @param curr is the current ModelAction that we are exploring; it must be a
889 void ModelChecker::build_reads_from_past(ModelAction *curr)
891 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
893 ASSERT(curr->is_read());
895 ModelAction *last_seq_cst = NULL;
897 /* Track whether this object has been initialized */
898 bool initialized = false;
900 if (curr->is_seqcst()) {
901 last_seq_cst = get_last_seq_cst(curr->get_location());
902 /* We have to at least see the last sequentially consistent write,
903 so we are initialized. */
904 if (last_seq_cst != NULL)
908 /* Iterate over all threads */
909 for (i = 0; i < thrd_lists->size(); i++) {
910 /* Iterate over actions in thread, starting from most recent */
911 action_list_t *list = &(*thrd_lists)[i];
912 action_list_t::reverse_iterator rit;
913 for (rit = list->rbegin(); rit != list->rend(); rit++) {
914 ModelAction *act = *rit;
916 /* Only consider 'write' actions */
917 if (!act->is_write())
920 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
921 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
922 DEBUG("Adding action to may_read_from:\n");
927 curr->get_node()->add_read_from(act);
930 /* Include at most one act per-thread that "happens before" curr */
931 if (act->happens_before(curr)) {
939 /** @todo Need a more informative way of reporting errors. */
940 printf("ERROR: may read from uninitialized atomic\n");
943 if (DBG_ENABLED() || !initialized) {
944 printf("Reached read action:\n");
946 printf("Printing may_read_from\n");
947 curr->get_node()->print_may_read_from();
948 printf("End printing may_read_from\n");
954 static void print_list(action_list_t *list)
956 action_list_t::iterator it;
958 printf("---------------------------------------------------------------------\n");
961 for (it = list->begin(); it != list->end(); it++) {
964 printf("---------------------------------------------------------------------\n");
967 void ModelChecker::print_summary()
970 printf("Number of executions: %d\n", num_executions);
971 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
975 if (!isfinalfeasible())
976 printf("INFEASIBLE EXECUTION!\n");
977 print_list(action_trace);
982 * Add a Thread to the system for the first time. Should only be called once
984 * @param t The Thread to add
986 void ModelChecker::add_thread(Thread *t)
988 thread_map->put(id_to_int(t->get_id()), t);
989 scheduler->add_thread(t);
992 void ModelChecker::remove_thread(Thread *t)
994 scheduler->remove_thread(t);
998 * Switch from a user-context to the "master thread" context (a.k.a. system
999 * context). This switch is made with the intention of exploring a particular
1000 * model-checking action (described by a ModelAction object). Must be called
1001 * from a user-thread context.
1002 * @param act The current action that will be explored. Must not be NULL.
1003 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1005 int ModelChecker::switch_to_master(ModelAction *act)
1008 Thread *old = thread_current();
1009 set_current_action(act);
1010 old->set_state(THREAD_READY);
1011 return Thread::swap(old, &system_context);
1015 * Takes the next step in the execution, if possible.
1016 * @return Returns true (success) if a step was taken and false otherwise.
1018 bool ModelChecker::take_step() {
1019 Thread *curr, *next;
1024 curr = thread_current();
1026 if (curr->get_state() == THREAD_READY) {
1027 ASSERT(priv->current_action);
1028 priv->nextThread = check_current_action(priv->current_action);
1029 priv->current_action = NULL;
1030 if (!curr->is_blocked() && !curr->is_complete())
1031 scheduler->add_thread(curr);
1036 next = scheduler->next_thread(priv->nextThread);
1038 /* Infeasible -> don't take any more steps */
1043 next->set_state(THREAD_RUNNING);
1044 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1046 /* next == NULL -> don't take any more steps */
1049 /* Return false only if swap fails with an error */
1050 return (Thread::swap(&system_context, next) == 0);
1053 /** Runs the current execution until threre are no more steps to take. */
1054 void ModelChecker::finish_execution() {
1057 while (take_step());