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),
36 too_many_reads(false),
39 /* Allocate this "size" on the snapshotting heap */
40 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
41 /* First thread created will have id INITIAL_THREAD_ID */
42 priv->next_thread_id = INITIAL_THREAD_ID;
44 lazy_sync_size = &priv->lazy_sync_size;
47 /** @brief Destructor */
48 ModelChecker::~ModelChecker()
50 for (int i = 0; i < get_num_threads(); i++)
51 delete thread_map->get(i);
58 for (unsigned int i = 0; i < promises->size(); i++)
59 delete (*promises)[i];
62 delete lazy_sync_with_release;
64 delete thrd_last_action;
71 * Restores user program to initial state and resets all model-checker data
74 void ModelChecker::reset_to_initial_state()
76 DEBUG("+++ Resetting to initial state +++\n");
77 node_stack->reset_execution();
78 failed_promise = false;
79 too_many_reads = false;
81 snapshotObject->backTrackBeforeStep(0);
84 /** @returns a thread ID for a new Thread */
85 thread_id_t ModelChecker::get_next_id()
87 return priv->next_thread_id++;
90 /** @returns the number of user threads created during this execution */
91 int ModelChecker::get_num_threads()
93 return priv->next_thread_id;
96 /** @returns a sequence number for a new ModelAction */
97 modelclock_t ModelChecker::get_next_seq_num()
99 return ++priv->used_sequence_numbers;
103 * @brief Choose the next thread to execute.
105 * This function chooses the next thread that should execute. It can force the
106 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
107 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
108 * The model-checker may have no preference regarding the next thread (i.e.,
109 * when exploring a new execution ordering), in which case this will return
111 * @param curr The current ModelAction. This action might guide the choice of
113 * @return The next thread to run. If the model-checker has no preference, NULL.
115 Thread * ModelChecker::get_next_thread(ModelAction *curr)
119 /* Do not split atomic actions. */
121 return thread_current();
122 /* The THREAD_CREATE action points to the created Thread */
123 else if (curr->get_type() == THREAD_CREATE)
124 return (Thread *)curr->get_location();
126 /* Have we completed exploring the preselected path? */
130 /* Else, we are trying to replay an execution */
131 ModelAction *next = node_stack->get_next()->get_action();
133 if (next == diverge) {
134 Node *nextnode = next->get_node();
135 /* Reached divergence point */
136 if (nextnode->increment_promise()) {
137 /* The next node will try to satisfy a different set of promises. */
138 tid = next->get_tid();
139 node_stack->pop_restofstack(2);
140 } else if (nextnode->increment_read_from()) {
141 /* The next node will read from a different value. */
142 tid = next->get_tid();
143 node_stack->pop_restofstack(2);
144 } else if (nextnode->increment_future_value()) {
145 /* The next node will try to read from a different future value. */
146 tid = next->get_tid();
147 node_stack->pop_restofstack(2);
149 /* Make a different thread execute for next step */
150 Node *node = nextnode->get_parent();
151 tid = node->get_next_backtrack();
152 node_stack->pop_restofstack(1);
154 DEBUG("*** Divergence point ***\n");
157 tid = next->get_tid();
159 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
160 ASSERT(tid != THREAD_ID_T_NONE);
161 return thread_map->get(id_to_int(tid));
165 * Queries the model-checker for more executions to explore and, if one
166 * exists, resets the model-checker state to execute a new execution.
168 * @return If there are more executions to explore, return true. Otherwise,
171 bool ModelChecker::next_execution()
177 if (isfinalfeasible() || DBG_ENABLED())
180 if ((diverge = get_next_backtrack()) == NULL)
184 printf("Next execution will diverge at:\n");
188 reset_to_initial_state();
192 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
194 action_type type = act->get_type();
204 /* linear search: from most recent to oldest */
205 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
206 action_list_t::reverse_iterator rit;
207 for (rit = list->rbegin(); rit != list->rend(); rit++) {
208 ModelAction *prev = *rit;
209 if (act->is_synchronizing(prev))
215 void ModelChecker::set_backtracking(ModelAction *act)
219 Thread *t = get_thread(act);
221 prev = get_last_conflict(act);
225 node = prev->get_node()->get_parent();
227 while (!node->is_enabled(t))
230 /* Check if this has been explored already */
231 if (node->has_been_explored(t->get_id()))
234 /* Cache the latest backtracking point */
235 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
236 priv->next_backtrack = prev;
238 /* If this is a new backtracking point, mark the tree */
239 if (!node->set_backtrack(t->get_id()))
241 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
242 prev->get_tid(), t->get_id());
250 * Returns last backtracking point. The model checker will explore a different
251 * path for this point in the next execution.
252 * @return The ModelAction at which the next execution should diverge.
254 ModelAction * ModelChecker::get_next_backtrack()
256 ModelAction *next = priv->next_backtrack;
257 priv->next_backtrack = NULL;
262 * Processes a read or rmw model action.
263 * @param curr is the read model action to process.
264 * @param th is the thread
265 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
266 * @return True if processing this read updates the mo_graph.
269 bool ModelChecker::process_read(ModelAction *curr, Thread * th, bool second_part_of_rmw) {
273 const ModelAction *reads_from = curr->get_node()->get_read_from();
274 if (reads_from != NULL) {
275 value = reads_from->get_value();
276 /* Assign reads_from, perform release/acquire synchronization */
277 curr->read_from(reads_from);
278 if (!second_part_of_rmw) {
279 check_recency(curr,false);
282 bool r_status=r_modification_order(curr,reads_from);
284 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||!curr->get_node()->future_value_empty())) {
285 mo_graph->rollbackChanges();
286 too_many_reads=false;
290 mo_graph->commitChanges();
293 /* Read from future value */
294 value = curr->get_node()->get_future_value();
295 curr->read_from(NULL);
296 Promise *valuepromise = new Promise(curr, value);
297 promises->push_back(valuepromise);
299 th->set_return_value(value);
305 * This is the heart of the model checker routine. It performs model-checking
306 * actions corresponding to a given "current action." Among other processes, it
307 * calculates reads-from relationships, updates synchronization clock vectors,
308 * forms a memory_order constraints graph, and handles replay/backtrack
309 * execution when running permutations of previously-observed executions.
311 * @param curr The current action to process
312 * @return The next Thread that must be executed. May be NULL if ModelChecker
313 * makes no choice (e.g., according to replay execution, combining RMW actions,
316 Thread * ModelChecker::check_current_action(ModelAction *curr)
318 bool second_part_of_rmw = false;
322 if (curr->is_rmwc() || curr->is_rmw()) {
323 ModelAction *tmp = process_rmw(curr);
324 second_part_of_rmw = true;
328 ModelAction *tmp = node_stack->explore_action(curr);
330 /* Discard duplicate ModelAction; use action from NodeStack */
331 /* First restore type and order in case of RMW operation */
333 tmp->copy_typeandorder(curr);
335 /* If we have diverged, we need to reset the clock vector. */
337 tmp->create_cv(get_parent_action(tmp->get_tid()));
343 * Perform one-time actions when pushing new ModelAction onto
346 curr->create_cv(get_parent_action(curr->get_tid()));
347 /* Build may_read_from set */
349 build_reads_from_past(curr);
350 if (curr->is_write())
351 compute_promises(curr);
355 /* Thread specific actions */
356 switch(curr->get_type()) {
357 case THREAD_CREATE: {
358 Thread *th = (Thread *)curr->get_location();
359 th->set_creation(curr);
363 Thread *waiting, *blocking;
364 waiting = get_thread(curr);
365 blocking = (Thread *)curr->get_location();
366 if (!blocking->is_complete()) {
367 blocking->push_wait_list(curr);
368 scheduler->sleep(waiting);
372 case THREAD_FINISH: {
373 Thread *th = get_thread(curr);
374 while (!th->wait_list_empty()) {
375 ModelAction *act = th->pop_wait_list();
376 Thread *wake = get_thread(act);
377 scheduler->wake(wake);
383 check_promises(NULL, curr->get_cv());
390 Thread *th = get_thread(curr);
392 bool updated = false;
393 if (curr->is_read()) {
394 updated=process_read(curr, th, second_part_of_rmw);
397 if (curr->is_write()) {
398 bool updated_mod_order=w_modification_order(curr);
399 bool updated_promises=resolve_promises(curr);
400 updated=updated_mod_order|updated_promises;
402 mo_graph->commitChanges();
403 th->set_return_value(VALUE_NONE);
407 resolve_release_sequences(curr->get_location());
409 /* Add action to list. */
410 if (!second_part_of_rmw)
411 add_action_to_lists(curr);
413 Node *currnode = curr->get_node();
414 Node *parnode = currnode->get_parent();
416 if ((!parnode->backtrack_empty() ||
417 !currnode->read_from_empty() ||
418 !currnode->future_value_empty() ||
419 !currnode->promise_empty())
420 && (!priv->next_backtrack ||
421 *curr > *priv->next_backtrack)) {
422 priv->next_backtrack = curr;
425 set_backtracking(curr);
427 return get_next_thread(curr);
430 /** @returns whether the current partial trace must be a prefix of a
432 bool ModelChecker::isfeasibleprefix() {
433 return promises->size() == 0 && *lazy_sync_size == 0;
436 /** @returns whether the current partial trace is feasible. */
437 bool ModelChecker::isfeasible() {
438 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads;
441 /** Returns whether the current completed trace is feasible. */
442 bool ModelChecker::isfinalfeasible() {
443 return isfeasible() && promises->size() == 0;
446 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
447 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
448 int tid = id_to_int(act->get_tid());
449 ModelAction *lastread = get_last_action(tid);
450 lastread->process_rmw(act);
452 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
457 * Checks whether a thread has read from the same write for too many times
458 * without seeing the effects of a later write.
461 * 1) there must a different write that we could read from that would satisfy the modification order,
462 * 2) we must have read from the same value in excess of maxreads times, and
463 * 3) that other write must have been in the reads_from set for maxreads times.
465 * If so, we decide that the execution is no longer feasible.
467 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
468 if (params.maxreads != 0) {
469 if (curr->get_node()->get_read_from_size() <= 1)
472 //Must make sure that execution is currently feasible... We could
473 //accidentally clear by rolling back
477 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
478 int tid = id_to_int(curr->get_tid());
481 if ((int)thrd_lists->size() <= tid)
484 action_list_t *list = &(*thrd_lists)[tid];
486 action_list_t::reverse_iterator rit = list->rbegin();
488 if (!already_added) {
489 for (; (*rit) != curr; rit++)
491 /* go past curr now */
495 action_list_t::reverse_iterator ritcopy=rit;
496 //See if we have enough reads from the same value
498 for (; count < params.maxreads; rit++,count++) {
499 if (rit==list->rend())
501 ModelAction *act = *rit;
504 if (act->get_reads_from() != curr->get_reads_from())
506 if (act->get_node()->get_read_from_size() <= 1)
510 for (int i=0;i<curr->get_node()->get_read_from_size();i++) {
512 const ModelAction * write=curr->get_node()->get_read_from_at(i);
513 //Need a different write
514 if (write==curr->get_reads_from())
517 /* Test to see whether this is a feasible write to read from*/
518 r_modification_order(curr, write);
519 bool feasiblereadfrom=isfeasible();
520 mo_graph->rollbackChanges();
522 if (!feasiblereadfrom)
526 bool feasiblewrite=true;
527 //new we need to see if this write works for everyone
529 for (int loop=count;loop>0;loop--,rit++) {
530 ModelAction *act=*rit;
531 bool foundvalue=false;
532 for(int j=0;j<act->get_node()->get_read_from_size();j++) {
533 if (act->get_node()->get_read_from_at(i)==write) {
544 too_many_reads = true;
552 * Updates the mo_graph with the constraints imposed from the current read.
553 * @param curr The current action. Must be a read.
554 * @param rf The action that curr reads from. Must be a write.
555 * @return True if modification order edges were added; false otherwise
557 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
559 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
562 ASSERT(curr->is_read());
564 /* Iterate over all threads */
565 for (i = 0; i < thrd_lists->size(); i++) {
566 /* Iterate over actions in thread, starting from most recent */
567 action_list_t *list = &(*thrd_lists)[i];
568 action_list_t::reverse_iterator rit;
569 for (rit = list->rbegin(); rit != list->rend(); rit++) {
570 ModelAction *act = *rit;
572 /* Include at most one act per-thread that "happens before" curr */
573 if (act->happens_before(curr)) {
574 if (act->is_read()) {
575 const ModelAction *prevreadfrom = act->get_reads_from();
576 if (prevreadfrom != NULL && rf != prevreadfrom) {
577 mo_graph->addEdge(prevreadfrom, rf);
580 } else if (rf != act) {
581 mo_graph->addEdge(act, rf);
592 /** Updates the mo_graph with the constraints imposed from the current read. */
593 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
595 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
597 ASSERT(curr->is_read());
599 /* Iterate over all threads */
600 for (i = 0; i < thrd_lists->size(); i++) {
601 /* Iterate over actions in thread, starting from most recent */
602 action_list_t *list = &(*thrd_lists)[i];
603 action_list_t::reverse_iterator rit;
604 ModelAction *lastact = NULL;
606 /* Find last action that happens after curr */
607 for (rit = list->rbegin(); rit != list->rend(); rit++) {
608 ModelAction *act = *rit;
609 if (curr->happens_before(act)) {
615 /* Include at most one act per-thread that "happens before" curr */
616 if (lastact != NULL) {
617 if (lastact->is_read()) {
618 const ModelAction *postreadfrom = lastact->get_reads_from();
619 if (postreadfrom != NULL&&rf != postreadfrom)
620 mo_graph->addEdge(rf, postreadfrom);
621 } else if (rf != lastact) {
622 mo_graph->addEdge(rf, lastact);
630 * Updates the mo_graph with the constraints imposed from the current write.
631 * @param curr The current action. Must be a write.
632 * @return True if modification order edges were added; false otherwise
634 bool ModelChecker::w_modification_order(ModelAction *curr)
636 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
639 ASSERT(curr->is_write());
641 if (curr->is_seqcst()) {
642 /* We have to at least see the last sequentially consistent write,
643 so we are initialized. */
644 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
645 if (last_seq_cst != NULL) {
646 mo_graph->addEdge(last_seq_cst, curr);
651 /* Iterate over all threads */
652 for (i = 0; i < thrd_lists->size(); i++) {
653 /* Iterate over actions in thread, starting from most recent */
654 action_list_t *list = &(*thrd_lists)[i];
655 action_list_t::reverse_iterator rit;
656 for (rit = list->rbegin(); rit != list->rend(); rit++) {
657 ModelAction *act = *rit;
659 /* Include at most one act per-thread that "happens before" curr */
660 if (act->happens_before(curr)) {
662 * Note: if act is RMW, just add edge:
664 * The following edge should be handled elsewhere:
665 * readfrom(act) --mo--> act
668 mo_graph->addEdge(act, curr);
669 else if (act->is_read() && act->get_reads_from() != NULL)
670 mo_graph->addEdge(act->get_reads_from(), curr);
673 } else if (act->is_read() && !act->is_synchronizing(curr) &&
674 !act->same_thread(curr)) {
675 /* We have an action that:
676 (1) did not happen before us
677 (2) is a read and we are a write
678 (3) cannot synchronize with us
679 (4) is in a different thread
681 that read could potentially read from our write.
683 if (act->get_node()->add_future_value(curr->get_value()) &&
684 (!priv->next_backtrack || *act > *priv->next_backtrack))
685 priv->next_backtrack = act;
694 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
695 * The ModelAction under consideration is expected to be taking part in
696 * release/acquire synchronization as an object of the "reads from" relation.
697 * Note that this can only provide release sequence support for RMW chains
698 * which do not read from the future, as those actions cannot be traced until
699 * their "promise" is fulfilled. Similarly, we may not even establish the
700 * presence of a release sequence with certainty, as some modification order
701 * constraints may be decided further in the future. Thus, this function
702 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
703 * and a boolean representing certainty.
705 * @todo Finish lazy updating, when promises are fulfilled in the future
706 * @param rf The action that might be part of a release sequence. Must be a
708 * @param release_heads A pass-by-reference style return parameter. After
709 * execution of this function, release_heads will contain the heads of all the
710 * relevant release sequences, if any exists
711 * @return true, if the ModelChecker is certain that release_heads is complete;
714 bool ModelChecker::release_seq_head(const ModelAction *rf,
715 std::vector<const ModelAction *> *release_heads) const
717 ASSERT(rf->is_write());
719 /* read from future: need to settle this later */
720 return false; /* incomplete */
722 if (rf->is_release())
723 release_heads->push_back(rf);
725 /* We need a RMW action that is both an acquire and release to stop */
726 /** @todo Need to be smarter here... In the linux lock
727 * example, this will run to the beginning of the program for
729 if (rf->is_acquire() && rf->is_release())
730 return true; /* complete */
731 return release_seq_head(rf->get_reads_from(), release_heads);
733 if (rf->is_release())
734 return true; /* complete */
736 /* else relaxed write; check modification order for contiguous subsequence
737 * -> rf must be same thread as release */
738 int tid = id_to_int(rf->get_tid());
739 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
740 action_list_t *list = &(*thrd_lists)[tid];
741 action_list_t::const_reverse_iterator rit;
743 /* Find rf in the thread list */
744 rit = std::find(list->rbegin(), list->rend(), rf);
745 ASSERT(rit != list->rend());
747 /* Find the last write/release */
748 for (; rit != list->rend(); rit++)
749 if ((*rit)->is_release())
751 if (rit == list->rend()) {
752 /* No write-release in this thread */
753 return true; /* complete */
755 ModelAction *release = *rit;
757 ASSERT(rf->same_thread(release));
760 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
761 if (id_to_int(rf->get_tid()) == (int)i)
763 list = &(*thrd_lists)[i];
765 /* Can we ensure no future writes from this thread may break
766 * the release seq? */
767 bool future_ordered = false;
769 for (rit = list->rbegin(); rit != list->rend(); rit++) {
770 const ModelAction *act = *rit;
771 if (!act->is_write())
773 /* Reach synchronization -> this thread is complete */
774 if (act->happens_before(release))
776 if (rf->happens_before(act)) {
777 future_ordered = true;
781 /* Check modification order */
782 if (mo_graph->checkReachable(rf, act)) {
784 future_ordered = true;
787 if (mo_graph->checkReachable(act, release))
788 /* act --mo--> release */
790 if (mo_graph->checkReachable(release, act) &&
791 mo_graph->checkReachable(act, rf)) {
792 /* release --mo-> act --mo--> rf */
793 return true; /* complete */
798 return false; /* This thread is uncertain */
802 release_heads->push_back(release);
807 * A public interface for getting the release sequence head(s) with which a
808 * given ModelAction must synchronize. This function only returns a non-empty
809 * result when it can locate a release sequence head with certainty. Otherwise,
810 * it may mark the internal state of the ModelChecker so that it will handle
811 * the release sequence at a later time, causing @a act to update its
812 * synchronization at some later point in execution.
813 * @param act The 'acquire' action that may read from a release sequence
814 * @param release_heads A pass-by-reference return parameter. Will be filled
815 * with the head(s) of the release sequence(s), if they exists with certainty.
816 * @see ModelChecker::release_seq_head
818 void ModelChecker::get_release_seq_heads(ModelAction *act,
819 std::vector<const ModelAction *> *release_heads)
821 const ModelAction *rf = act->get_reads_from();
823 complete = release_seq_head(rf, release_heads);
825 /* add act to 'lazy checking' list */
826 std::list<ModelAction *> *list;
827 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
828 list->push_back(act);
834 * Attempt to resolve all stashed operations that might synchronize with a
835 * release sequence for a given location. This implements the "lazy" portion of
836 * determining whether or not a release sequence was contiguous, since not all
837 * modification order information is present at the time an action occurs.
839 * @param location The location/object that should be checked for release
840 * sequence resolutions
841 * @return True if any updates occurred (new synchronization, new mo_graph edges)
843 bool ModelChecker::resolve_release_sequences(void *location)
845 std::list<ModelAction *> *list;
846 list = lazy_sync_with_release->getptr(location);
850 bool updated = false;
851 std::list<ModelAction *>::iterator it = list->begin();
852 while (it != list->end()) {
853 ModelAction *act = *it;
854 const ModelAction *rf = act->get_reads_from();
855 std::vector<const ModelAction *> release_heads;
857 complete = release_seq_head(rf, &release_heads);
858 for (unsigned int i = 0; i < release_heads.size(); i++) {
859 if (!act->has_synchronized_with(release_heads[i])) {
861 act->synchronize_with(release_heads[i]);
866 /* propagate synchronization to later actions */
867 action_list_t::reverse_iterator it = action_trace->rbegin();
868 while ((*it) != act) {
869 ModelAction *propagate = *it;
870 if (act->happens_before(propagate))
871 /** @todo new mo_graph edges along with
872 * this synchronization? */
873 propagate->synchronize_with(act);
877 it = list->erase(it);
883 // If we resolved promises or data races, see if we have realized a data race.
884 if (checkDataRaces()) {
892 * Performs various bookkeeping operations for the current ModelAction. For
893 * instance, adds action to the per-object, per-thread action vector and to the
894 * action trace list of all thread actions.
896 * @param act is the ModelAction to add.
898 void ModelChecker::add_action_to_lists(ModelAction *act)
900 int tid = id_to_int(act->get_tid());
901 action_trace->push_back(act);
903 obj_map->get_safe_ptr(act->get_location())->push_back(act);
905 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
906 if (tid >= (int)vec->size())
907 vec->resize(priv->next_thread_id);
908 (*vec)[tid].push_back(act);
910 if ((int)thrd_last_action->size() <= tid)
911 thrd_last_action->resize(get_num_threads());
912 (*thrd_last_action)[tid] = act;
915 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
917 int nthreads = get_num_threads();
918 if ((int)thrd_last_action->size() < nthreads)
919 thrd_last_action->resize(nthreads);
920 return (*thrd_last_action)[id_to_int(tid)];
924 * Gets the last memory_order_seq_cst action (in the total global sequence)
925 * performed on a particular object (i.e., memory location).
926 * @param location The object location to check
927 * @return The last seq_cst action performed
929 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
931 action_list_t *list = obj_map->get_safe_ptr(location);
932 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
933 action_list_t::reverse_iterator rit;
934 for (rit = list->rbegin(); rit != list->rend(); rit++)
935 if ((*rit)->is_write() && (*rit)->is_seqcst())
940 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
942 ModelAction *parent = get_last_action(tid);
944 parent = get_thread(tid)->get_creation();
949 * Returns the clock vector for a given thread.
950 * @param tid The thread whose clock vector we want
951 * @return Desired clock vector
953 ClockVector * ModelChecker::get_cv(thread_id_t tid)
955 return get_parent_action(tid)->get_cv();
959 * Resolve a set of Promises with a current write. The set is provided in the
960 * Node corresponding to @a write.
961 * @param write The ModelAction that is fulfilling Promises
962 * @return True if promises were resolved; false otherwise
964 bool ModelChecker::resolve_promises(ModelAction *write)
966 bool resolved = false;
967 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
968 Promise *promise = (*promises)[promise_index];
969 if (write->get_node()->get_promise(i)) {
970 ModelAction *read = promise->get_action();
971 read->read_from(write);
972 r_modification_order(read, write);
973 post_r_modification_order(read, write);
974 promises->erase(promises->begin() + promise_index);
984 * Compute the set of promises that could potentially be satisfied by this
985 * action. Note that the set computation actually appears in the Node, not in
987 * @param curr The ModelAction that may satisfy promises
989 void ModelChecker::compute_promises(ModelAction *curr)
991 for (unsigned int i = 0; i < promises->size(); i++) {
992 Promise *promise = (*promises)[i];
993 const ModelAction *act = promise->get_action();
994 if (!act->happens_before(curr) &&
996 !act->is_synchronizing(curr) &&
997 !act->same_thread(curr) &&
998 promise->get_value() == curr->get_value()) {
999 curr->get_node()->set_promise(i);
1004 /** Checks promises in response to change in ClockVector Threads. */
1005 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1007 for (unsigned int i = 0; i < promises->size(); i++) {
1008 Promise *promise = (*promises)[i];
1009 const ModelAction *act = promise->get_action();
1010 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1011 merge_cv->synchronized_since(act)) {
1012 //This thread is no longer able to send values back to satisfy the promise
1013 int num_synchronized_threads = promise->increment_threads();
1014 if (num_synchronized_threads == get_num_threads()) {
1015 //Promise has failed
1016 failed_promise = true;
1024 * Build up an initial set of all past writes that this 'read' action may read
1025 * from. This set is determined by the clock vector's "happens before"
1027 * @param curr is the current ModelAction that we are exploring; it must be a
1030 void ModelChecker::build_reads_from_past(ModelAction *curr)
1032 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1034 ASSERT(curr->is_read());
1036 ModelAction *last_seq_cst = NULL;
1038 /* Track whether this object has been initialized */
1039 bool initialized = false;
1041 if (curr->is_seqcst()) {
1042 last_seq_cst = get_last_seq_cst(curr->get_location());
1043 /* We have to at least see the last sequentially consistent write,
1044 so we are initialized. */
1045 if (last_seq_cst != NULL)
1049 /* Iterate over all threads */
1050 for (i = 0; i < thrd_lists->size(); i++) {
1051 /* Iterate over actions in thread, starting from most recent */
1052 action_list_t *list = &(*thrd_lists)[i];
1053 action_list_t::reverse_iterator rit;
1054 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1055 ModelAction *act = *rit;
1057 /* Only consider 'write' actions */
1058 if (!act->is_write())
1061 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1062 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
1063 DEBUG("Adding action to may_read_from:\n");
1064 if (DBG_ENABLED()) {
1068 curr->get_node()->add_read_from(act);
1071 /* Include at most one act per-thread that "happens before" curr */
1072 if (act->happens_before(curr)) {
1080 /** @todo Need a more informative way of reporting errors. */
1081 printf("ERROR: may read from uninitialized atomic\n");
1084 if (DBG_ENABLED() || !initialized) {
1085 printf("Reached read action:\n");
1087 printf("Printing may_read_from\n");
1088 curr->get_node()->print_may_read_from();
1089 printf("End printing may_read_from\n");
1092 ASSERT(initialized);
1095 static void print_list(action_list_t *list)
1097 action_list_t::iterator it;
1099 printf("---------------------------------------------------------------------\n");
1102 for (it = list->begin(); it != list->end(); it++) {
1105 printf("---------------------------------------------------------------------\n");
1108 void ModelChecker::print_summary()
1111 printf("Number of executions: %d\n", num_executions);
1112 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1116 if (!isfinalfeasible())
1117 printf("INFEASIBLE EXECUTION!\n");
1118 print_list(action_trace);
1123 * Add a Thread to the system for the first time. Should only be called once
1125 * @param t The Thread to add
1127 void ModelChecker::add_thread(Thread *t)
1129 thread_map->put(id_to_int(t->get_id()), t);
1130 scheduler->add_thread(t);
1133 void ModelChecker::remove_thread(Thread *t)
1135 scheduler->remove_thread(t);
1139 * Switch from a user-context to the "master thread" context (a.k.a. system
1140 * context). This switch is made with the intention of exploring a particular
1141 * model-checking action (described by a ModelAction object). Must be called
1142 * from a user-thread context.
1143 * @param act The current action that will be explored. Must not be NULL.
1144 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1146 int ModelChecker::switch_to_master(ModelAction *act)
1149 Thread *old = thread_current();
1150 set_current_action(act);
1151 old->set_state(THREAD_READY);
1152 return Thread::swap(old, &system_context);
1156 * Takes the next step in the execution, if possible.
1157 * @return Returns true (success) if a step was taken and false otherwise.
1159 bool ModelChecker::take_step() {
1160 Thread *curr, *next;
1165 curr = thread_current();
1167 if (curr->get_state() == THREAD_READY) {
1168 ASSERT(priv->current_action);
1169 priv->nextThread = check_current_action(priv->current_action);
1170 priv->current_action = NULL;
1171 if (!curr->is_blocked() && !curr->is_complete())
1172 scheduler->add_thread(curr);
1177 next = scheduler->next_thread(priv->nextThread);
1179 /* Infeasible -> don't take any more steps */
1184 next->set_state(THREAD_RUNNING);
1185 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1187 /* next == NULL -> don't take any more steps */
1190 /* Return false only if swap fails with an error */
1191 return (Thread::swap(&system_context, next) == 0);
1194 /** Runs the current execution until threre are no more steps to take. */
1195 void ModelChecker::finish_execution() {
1198 while (take_step());