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 * Choose the next thread in the replay sequence.
105 * If the replay sequence has reached the 'diverge' point, returns a thread
106 * from the backtracking set. Otherwise, simply returns the next thread in the
107 * sequence that is being replayed.
109 Thread * ModelChecker::get_next_replay_thread()
113 /* Have we completed exploring the preselected path? */
117 /* Else, we are trying to replay an execution */
118 ModelAction *next = node_stack->get_next()->get_action();
120 if (next == diverge) {
121 Node *nextnode = next->get_node();
122 /* Reached divergence point */
123 if (nextnode->increment_promise()) {
124 /* The next node will try to satisfy a different set of promises. */
125 tid = next->get_tid();
126 node_stack->pop_restofstack(2);
127 } else if (nextnode->increment_read_from()) {
128 /* The next node will read from a different value. */
129 tid = next->get_tid();
130 node_stack->pop_restofstack(2);
131 } else if (nextnode->increment_future_value()) {
132 /* The next node will try to read from a different future value. */
133 tid = next->get_tid();
134 node_stack->pop_restofstack(2);
136 /* Make a different thread execute for next step */
137 Node *node = nextnode->get_parent();
138 tid = node->get_next_backtrack();
139 node_stack->pop_restofstack(1);
141 DEBUG("*** Divergence point ***\n");
144 tid = next->get_tid();
146 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
147 ASSERT(tid != THREAD_ID_T_NONE);
148 return thread_map->get(id_to_int(tid));
152 * Queries the model-checker for more executions to explore and, if one
153 * exists, resets the model-checker state to execute a new execution.
155 * @return If there are more executions to explore, return true. Otherwise,
158 bool ModelChecker::next_execution()
164 if (isfinalfeasible() || DBG_ENABLED())
167 if ((diverge = get_next_backtrack()) == NULL)
171 printf("Next execution will diverge at:\n");
175 reset_to_initial_state();
179 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
181 action_type type = act->get_type();
191 /* linear search: from most recent to oldest */
192 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
193 action_list_t::reverse_iterator rit;
194 for (rit = list->rbegin(); rit != list->rend(); rit++) {
195 ModelAction *prev = *rit;
196 if (act->is_synchronizing(prev))
202 void ModelChecker::set_backtracking(ModelAction *act)
206 Thread *t = get_thread(act->get_tid());
208 prev = get_last_conflict(act);
212 node = prev->get_node()->get_parent();
214 while (!node->is_enabled(t))
217 /* Check if this has been explored already */
218 if (node->has_been_explored(t->get_id()))
221 /* Cache the latest backtracking point */
222 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
223 priv->next_backtrack = prev;
225 /* If this is a new backtracking point, mark the tree */
226 if (!node->set_backtrack(t->get_id()))
228 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
229 prev->get_tid(), t->get_id());
237 * Returns last backtracking point. The model checker will explore a different
238 * path for this point in the next execution.
239 * @return The ModelAction at which the next execution should diverge.
241 ModelAction * ModelChecker::get_next_backtrack()
243 ModelAction *next = priv->next_backtrack;
244 priv->next_backtrack = NULL;
249 * Processes a read or rmw model action.
250 * @param curr is the read model action to process.
251 * @param th is the thread
252 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
253 * @return True if processing this read updates the mo_graph.
256 bool ModelChecker::process_read(ModelAction *curr, Thread * th, bool second_part_of_rmw) {
260 const ModelAction *reads_from = curr->get_node()->get_read_from();
261 if (reads_from != NULL) {
262 value = reads_from->get_value();
263 /* Assign reads_from, perform release/acquire synchronization */
264 curr->read_from(reads_from);
265 if (!second_part_of_rmw) {
266 check_recency(curr,false);
269 bool r_status=r_modification_order(curr,reads_from);
271 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||!curr->get_node()->future_value_empty())) {
272 mo_graph->rollbackChanges();
273 too_many_reads=false;
277 mo_graph->commitChanges();
280 /* Read from future value */
281 value = curr->get_node()->get_future_value();
282 curr->read_from(NULL);
283 Promise *valuepromise = new Promise(curr, value);
284 promises->push_back(valuepromise);
286 th->set_return_value(value);
292 * This is the heart of the model checker routine. It performs model-checking
293 * actions corresponding to a given "current action." Among other processes, it
294 * calculates reads-from relationships, updates synchronization clock vectors,
295 * forms a memory_order constraints graph, and handles replay/backtrack
296 * execution when running permutations of previously-observed executions.
298 * @param curr The current action to process
299 * @return The next Thread that must be executed. May be NULL if ModelChecker
300 * makes no choice (e.g., according to replay execution, combining RMW actions,
303 Thread * ModelChecker::check_current_action(ModelAction *curr)
305 bool second_part_of_rmw = false;
309 if (curr->is_rmwc() || curr->is_rmw()) {
310 ModelAction *tmp = process_rmw(curr);
311 second_part_of_rmw = true;
315 ModelAction *tmp = node_stack->explore_action(curr);
317 /* Discard duplicate ModelAction; use action from NodeStack */
318 /* First restore type and order in case of RMW operation */
320 tmp->copy_typeandorder(curr);
322 /* If we have diverged, we need to reset the clock vector. */
324 tmp->create_cv(get_parent_action(tmp->get_tid()));
330 * Perform one-time actions when pushing new ModelAction onto
333 curr->create_cv(get_parent_action(curr->get_tid()));
334 /* Build may_read_from set */
336 build_reads_from_past(curr);
337 if (curr->is_write())
338 compute_promises(curr);
342 /* Assign 'creation' parent */
343 if (curr->get_type() == THREAD_CREATE) {
344 Thread *th = (Thread *)curr->get_location();
345 th->set_creation(curr);
346 } else if (curr->get_type() == THREAD_JOIN) {
348 wait = get_thread(curr->get_tid());
349 join = (Thread *)curr->get_location();
350 if (!join->is_complete())
351 scheduler->wait(wait, join);
352 } else if (curr->get_type() == THREAD_FINISH) {
353 Thread *th = get_thread(curr->get_tid());
354 while (!th->wait_list_empty()) {
355 Thread *wake = th->pop_wait_list();
356 scheduler->wake(wake);
361 /* Deal with new thread */
362 if (curr->get_type() == THREAD_START)
363 check_promises(NULL, curr->get_cv());
365 Thread *th = get_thread(curr->get_tid());
367 bool updated = false;
368 if (curr->is_read()) {
369 updated=process_read(curr, th, second_part_of_rmw);
372 if (curr->is_write()) {
373 bool updated_mod_order=w_modification_order(curr);
374 bool updated_promises=resolve_promises(curr);
375 updated=updated_mod_order|updated_promises;
377 mo_graph->commitChanges();
378 th->set_return_value(VALUE_NONE);
382 resolve_release_sequences(curr->get_location());
384 /* Add action to list. */
385 if (!second_part_of_rmw)
386 add_action_to_lists(curr);
388 Node *currnode = curr->get_node();
389 Node *parnode = currnode->get_parent();
391 if ((!parnode->backtrack_empty() ||
392 !currnode->read_from_empty() ||
393 !currnode->future_value_empty() ||
394 !currnode->promise_empty())
395 && (!priv->next_backtrack ||
396 *curr > *priv->next_backtrack)) {
397 priv->next_backtrack = curr;
400 set_backtracking(curr);
402 /* Do not split atomic actions. */
404 return thread_current();
405 /* The THREAD_CREATE action points to the created Thread */
406 else if (curr->get_type() == THREAD_CREATE)
407 return (Thread *)curr->get_location();
409 return get_next_replay_thread();
412 /** @returns whether the current partial trace must be a prefix of a
414 bool ModelChecker::isfeasibleprefix() {
415 return promises->size() == 0 && *lazy_sync_size == 0;
418 /** @returns whether the current partial trace is feasible. */
419 bool ModelChecker::isfeasible() {
420 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads;
423 /** Returns whether the current completed trace is feasible. */
424 bool ModelChecker::isfinalfeasible() {
425 return isfeasible() && promises->size() == 0;
428 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
429 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
430 int tid = id_to_int(act->get_tid());
431 ModelAction *lastread = get_last_action(tid);
432 lastread->process_rmw(act);
434 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
439 * Checks whether a thread has read from the same write for too many times
440 * without seeing the effects of a later write.
443 * 1) there must a different write that we could read from that would satisfy the modification order,
444 * 2) we must have read from the same value in excess of maxreads times, and
445 * 3) that other write must have been in the reads_from set for maxreads times.
447 * If so, we decide that the execution is no longer feasible.
449 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
450 if (params.maxreads != 0) {
451 if (curr->get_node()->get_read_from_size() <= 1)
454 //Must make sure that execution is currently feasible... We could
455 //accidentally clear by rolling back
459 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
460 int tid = id_to_int(curr->get_tid());
463 if ((int)thrd_lists->size() <= tid)
466 action_list_t *list = &(*thrd_lists)[tid];
468 action_list_t::reverse_iterator rit = list->rbegin();
470 if (!already_added) {
471 for (; (*rit) != curr; rit++)
473 /* go past curr now */
477 action_list_t::reverse_iterator ritcopy=rit;
478 //See if we have enough reads from the same value
480 for (; count < params.maxreads; rit++,count++) {
481 if (rit==list->rend())
483 ModelAction *act = *rit;
486 if (act->get_reads_from() != curr->get_reads_from())
488 if (act->get_node()->get_read_from_size() <= 1)
492 for (int i=0;i<curr->get_node()->get_read_from_size();i++) {
494 const ModelAction * write=curr->get_node()->get_read_from_at(i);
495 //Need a different write
496 if (write==curr->get_reads_from())
499 /* Test to see whether this is a feasible write to read from*/
500 r_modification_order(curr, write);
501 bool feasiblereadfrom=isfeasible();
502 mo_graph->rollbackChanges();
504 if (!feasiblereadfrom)
508 bool feasiblewrite=true;
509 //new we need to see if this write works for everyone
511 for (int loop=count;loop>0;loop--,rit++) {
512 ModelAction *act=*rit;
513 bool foundvalue=false;
514 for(int j=0;j<act->get_node()->get_read_from_size();j++) {
515 if (act->get_node()->get_read_from_at(i)==write) {
526 too_many_reads = true;
534 * Updates the mo_graph with the constraints imposed from the current read.
535 * @param curr The current action. Must be a read.
536 * @param rf The action that curr reads from. Must be a write.
537 * @return True if modification order edges were added; false otherwise
539 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
541 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
544 ASSERT(curr->is_read());
546 /* Iterate over all threads */
547 for (i = 0; i < thrd_lists->size(); i++) {
548 /* Iterate over actions in thread, starting from most recent */
549 action_list_t *list = &(*thrd_lists)[i];
550 action_list_t::reverse_iterator rit;
551 for (rit = list->rbegin(); rit != list->rend(); rit++) {
552 ModelAction *act = *rit;
554 /* Include at most one act per-thread that "happens before" curr */
555 if (act->happens_before(curr)) {
556 if (act->is_read()) {
557 const ModelAction *prevreadfrom = act->get_reads_from();
558 if (prevreadfrom != NULL && rf != prevreadfrom) {
559 mo_graph->addEdge(prevreadfrom, rf);
562 } else if (rf != act) {
563 mo_graph->addEdge(act, rf);
574 /** Updates the mo_graph with the constraints imposed from the current read. */
575 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
577 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
579 ASSERT(curr->is_read());
581 /* Iterate over all threads */
582 for (i = 0; i < thrd_lists->size(); i++) {
583 /* Iterate over actions in thread, starting from most recent */
584 action_list_t *list = &(*thrd_lists)[i];
585 action_list_t::reverse_iterator rit;
586 ModelAction *lastact = NULL;
588 /* Find last action that happens after curr */
589 for (rit = list->rbegin(); rit != list->rend(); rit++) {
590 ModelAction *act = *rit;
591 if (curr->happens_before(act)) {
597 /* Include at most one act per-thread that "happens before" curr */
598 if (lastact != NULL) {
599 if (lastact->is_read()) {
600 const ModelAction *postreadfrom = lastact->get_reads_from();
601 if (postreadfrom != NULL&&rf != postreadfrom)
602 mo_graph->addEdge(rf, postreadfrom);
603 } else if (rf != lastact) {
604 mo_graph->addEdge(rf, lastact);
612 * Updates the mo_graph with the constraints imposed from the current write.
613 * @param curr The current action. Must be a write.
614 * @return True if modification order edges were added; false otherwise
616 bool ModelChecker::w_modification_order(ModelAction *curr)
618 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
621 ASSERT(curr->is_write());
623 if (curr->is_seqcst()) {
624 /* We have to at least see the last sequentially consistent write,
625 so we are initialized. */
626 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
627 if (last_seq_cst != NULL) {
628 mo_graph->addEdge(last_seq_cst, curr);
633 /* Iterate over all threads */
634 for (i = 0; i < thrd_lists->size(); i++) {
635 /* Iterate over actions in thread, starting from most recent */
636 action_list_t *list = &(*thrd_lists)[i];
637 action_list_t::reverse_iterator rit;
638 for (rit = list->rbegin(); rit != list->rend(); rit++) {
639 ModelAction *act = *rit;
641 /* Include at most one act per-thread that "happens before" curr */
642 if (act->happens_before(curr)) {
644 * Note: if act is RMW, just add edge:
646 * The following edge should be handled elsewhere:
647 * readfrom(act) --mo--> act
650 mo_graph->addEdge(act, curr);
651 else if (act->is_read() && act->get_reads_from() != NULL)
652 mo_graph->addEdge(act->get_reads_from(), curr);
655 } else if (act->is_read() && !act->is_synchronizing(curr) &&
656 !act->same_thread(curr)) {
657 /* We have an action that:
658 (1) did not happen before us
659 (2) is a read and we are a write
660 (3) cannot synchronize with us
661 (4) is in a different thread
663 that read could potentially read from our write.
665 if (act->get_node()->add_future_value(curr->get_value()) &&
666 (!priv->next_backtrack || *act > *priv->next_backtrack))
667 priv->next_backtrack = act;
676 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
677 * The ModelAction under consideration is expected to be taking part in
678 * release/acquire synchronization as an object of the "reads from" relation.
679 * Note that this can only provide release sequence support for RMW chains
680 * which do not read from the future, as those actions cannot be traced until
681 * their "promise" is fulfilled. Similarly, we may not even establish the
682 * presence of a release sequence with certainty, as some modification order
683 * constraints may be decided further in the future. Thus, this function
684 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
685 * and a boolean representing certainty.
687 * @todo Finish lazy updating, when promises are fulfilled in the future
688 * @param rf The action that might be part of a release sequence. Must be a
690 * @param release_heads A pass-by-reference style return parameter. After
691 * execution of this function, release_heads will contain the heads of all the
692 * relevant release sequences, if any exists
693 * @return true, if the ModelChecker is certain that release_heads is complete;
696 bool ModelChecker::release_seq_head(const ModelAction *rf,
697 std::vector<const ModelAction *> *release_heads) const
699 ASSERT(rf->is_write());
701 /* read from future: need to settle this later */
702 return false; /* incomplete */
704 if (rf->is_release())
705 release_heads->push_back(rf);
707 /* We need a RMW action that is both an acquire and release to stop */
708 /** @todo Need to be smarter here... In the linux lock
709 * example, this will run to the beginning of the program for
711 if (rf->is_acquire() && rf->is_release())
712 return true; /* complete */
713 return release_seq_head(rf->get_reads_from(), release_heads);
715 if (rf->is_release())
716 return true; /* complete */
718 /* else relaxed write; check modification order for contiguous subsequence
719 * -> rf must be same thread as release */
720 int tid = id_to_int(rf->get_tid());
721 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
722 action_list_t *list = &(*thrd_lists)[tid];
723 action_list_t::const_reverse_iterator rit;
725 /* Find rf in the thread list */
726 rit = std::find(list->rbegin(), list->rend(), rf);
727 ASSERT(rit != list->rend());
729 /* Find the last write/release */
730 for (; rit != list->rend(); rit++)
731 if ((*rit)->is_release())
733 if (rit == list->rend()) {
734 /* No write-release in this thread */
735 return true; /* complete */
737 ModelAction *release = *rit;
739 ASSERT(rf->same_thread(release));
742 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
743 if (id_to_int(rf->get_tid()) == (int)i)
745 list = &(*thrd_lists)[i];
747 /* Can we ensure no future writes from this thread may break
748 * the release seq? */
749 bool future_ordered = false;
751 for (rit = list->rbegin(); rit != list->rend(); rit++) {
752 const ModelAction *act = *rit;
753 if (!act->is_write())
755 /* Reach synchronization -> this thread is complete */
756 if (act->happens_before(release))
758 if (rf->happens_before(act)) {
759 future_ordered = true;
763 /* Check modification order */
764 if (mo_graph->checkReachable(rf, act)) {
766 future_ordered = true;
769 if (mo_graph->checkReachable(act, release))
770 /* act --mo--> release */
772 if (mo_graph->checkReachable(release, act) &&
773 mo_graph->checkReachable(act, rf)) {
774 /* release --mo-> act --mo--> rf */
775 return true; /* complete */
780 return false; /* This thread is uncertain */
784 release_heads->push_back(release);
789 * A public interface for getting the release sequence head(s) with which a
790 * given ModelAction must synchronize. This function only returns a non-empty
791 * result when it can locate a release sequence head with certainty. Otherwise,
792 * it may mark the internal state of the ModelChecker so that it will handle
793 * the release sequence at a later time, causing @a act to update its
794 * synchronization at some later point in execution.
795 * @param act The 'acquire' action that may read from a release sequence
796 * @param release_heads A pass-by-reference return parameter. Will be filled
797 * with the head(s) of the release sequence(s), if they exists with certainty.
798 * @see ModelChecker::release_seq_head
800 void ModelChecker::get_release_seq_heads(ModelAction *act,
801 std::vector<const ModelAction *> *release_heads)
803 const ModelAction *rf = act->get_reads_from();
805 complete = release_seq_head(rf, release_heads);
807 /* add act to 'lazy checking' list */
808 std::list<ModelAction *> *list;
809 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
810 list->push_back(act);
816 * Attempt to resolve all stashed operations that might synchronize with a
817 * release sequence for a given location. This implements the "lazy" portion of
818 * determining whether or not a release sequence was contiguous, since not all
819 * modification order information is present at the time an action occurs.
821 * @param location The location/object that should be checked for release
822 * sequence resolutions
823 * @return True if any updates occurred (new synchronization, new mo_graph edges)
825 bool ModelChecker::resolve_release_sequences(void *location)
827 std::list<ModelAction *> *list;
828 list = lazy_sync_with_release->getptr(location);
832 bool updated = false;
833 std::list<ModelAction *>::iterator it = list->begin();
834 while (it != list->end()) {
835 ModelAction *act = *it;
836 const ModelAction *rf = act->get_reads_from();
837 std::vector<const ModelAction *> release_heads;
839 complete = release_seq_head(rf, &release_heads);
840 for (unsigned int i = 0; i < release_heads.size(); i++) {
841 if (!act->has_synchronized_with(release_heads[i])) {
843 act->synchronize_with(release_heads[i]);
848 /* propagate synchronization to later actions */
849 action_list_t::reverse_iterator it = action_trace->rbegin();
850 while ((*it) != act) {
851 ModelAction *propagate = *it;
852 if (act->happens_before(propagate))
853 /** @todo new mo_graph edges along with
854 * this synchronization? */
855 propagate->synchronize_with(act);
859 it = list->erase(it);
865 // If we resolved promises or data races, see if we have realized a data race.
866 if (checkDataRaces()) {
874 * Performs various bookkeeping operations for the current ModelAction. For
875 * instance, adds action to the per-object, per-thread action vector and to the
876 * action trace list of all thread actions.
878 * @param act is the ModelAction to add.
880 void ModelChecker::add_action_to_lists(ModelAction *act)
882 int tid = id_to_int(act->get_tid());
883 action_trace->push_back(act);
885 obj_map->get_safe_ptr(act->get_location())->push_back(act);
887 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
888 if (tid >= (int)vec->size())
889 vec->resize(priv->next_thread_id);
890 (*vec)[tid].push_back(act);
892 if ((int)thrd_last_action->size() <= tid)
893 thrd_last_action->resize(get_num_threads());
894 (*thrd_last_action)[tid] = act;
897 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
899 int nthreads = get_num_threads();
900 if ((int)thrd_last_action->size() < nthreads)
901 thrd_last_action->resize(nthreads);
902 return (*thrd_last_action)[id_to_int(tid)];
906 * Gets the last memory_order_seq_cst action (in the total global sequence)
907 * performed on a particular object (i.e., memory location).
908 * @param location The object location to check
909 * @return The last seq_cst action performed
911 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
913 action_list_t *list = obj_map->get_safe_ptr(location);
914 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
915 action_list_t::reverse_iterator rit;
916 for (rit = list->rbegin(); rit != list->rend(); rit++)
917 if ((*rit)->is_write() && (*rit)->is_seqcst())
922 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
924 ModelAction *parent = get_last_action(tid);
926 parent = get_thread(tid)->get_creation();
931 * Returns the clock vector for a given thread.
932 * @param tid The thread whose clock vector we want
933 * @return Desired clock vector
935 ClockVector * ModelChecker::get_cv(thread_id_t tid)
937 return get_parent_action(tid)->get_cv();
941 * Resolve a set of Promises with a current write. The set is provided in the
942 * Node corresponding to @a write.
943 * @param write The ModelAction that is fulfilling Promises
944 * @return True if promises were resolved; false otherwise
946 bool ModelChecker::resolve_promises(ModelAction *write)
948 bool resolved = false;
949 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
950 Promise *promise = (*promises)[promise_index];
951 if (write->get_node()->get_promise(i)) {
952 ModelAction *read = promise->get_action();
953 read->read_from(write);
954 r_modification_order(read, write);
955 post_r_modification_order(read, write);
956 promises->erase(promises->begin() + promise_index);
966 * Compute the set of promises that could potentially be satisfied by this
967 * action. Note that the set computation actually appears in the Node, not in
969 * @param curr The ModelAction that may satisfy promises
971 void ModelChecker::compute_promises(ModelAction *curr)
973 for (unsigned int i = 0; i < promises->size(); i++) {
974 Promise *promise = (*promises)[i];
975 const ModelAction *act = promise->get_action();
976 if (!act->happens_before(curr) &&
978 !act->is_synchronizing(curr) &&
979 !act->same_thread(curr) &&
980 promise->get_value() == curr->get_value()) {
981 curr->get_node()->set_promise(i);
986 /** Checks promises in response to change in ClockVector Threads. */
987 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
989 for (unsigned int i = 0; i < promises->size(); i++) {
990 Promise *promise = (*promises)[i];
991 const ModelAction *act = promise->get_action();
992 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
993 merge_cv->synchronized_since(act)) {
994 //This thread is no longer able to send values back to satisfy the promise
995 int num_synchronized_threads = promise->increment_threads();
996 if (num_synchronized_threads == get_num_threads()) {
998 failed_promise = true;
1006 * Build up an initial set of all past writes that this 'read' action may read
1007 * from. This set is determined by the clock vector's "happens before"
1009 * @param curr is the current ModelAction that we are exploring; it must be a
1012 void ModelChecker::build_reads_from_past(ModelAction *curr)
1014 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1016 ASSERT(curr->is_read());
1018 ModelAction *last_seq_cst = NULL;
1020 /* Track whether this object has been initialized */
1021 bool initialized = false;
1023 if (curr->is_seqcst()) {
1024 last_seq_cst = get_last_seq_cst(curr->get_location());
1025 /* We have to at least see the last sequentially consistent write,
1026 so we are initialized. */
1027 if (last_seq_cst != NULL)
1031 /* Iterate over all threads */
1032 for (i = 0; i < thrd_lists->size(); i++) {
1033 /* Iterate over actions in thread, starting from most recent */
1034 action_list_t *list = &(*thrd_lists)[i];
1035 action_list_t::reverse_iterator rit;
1036 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1037 ModelAction *act = *rit;
1039 /* Only consider 'write' actions */
1040 if (!act->is_write())
1043 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1044 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
1045 DEBUG("Adding action to may_read_from:\n");
1046 if (DBG_ENABLED()) {
1050 curr->get_node()->add_read_from(act);
1053 /* Include at most one act per-thread that "happens before" curr */
1054 if (act->happens_before(curr)) {
1062 /** @todo Need a more informative way of reporting errors. */
1063 printf("ERROR: may read from uninitialized atomic\n");
1066 if (DBG_ENABLED() || !initialized) {
1067 printf("Reached read action:\n");
1069 printf("Printing may_read_from\n");
1070 curr->get_node()->print_may_read_from();
1071 printf("End printing may_read_from\n");
1074 ASSERT(initialized);
1077 static void print_list(action_list_t *list)
1079 action_list_t::iterator it;
1081 printf("---------------------------------------------------------------------\n");
1084 for (it = list->begin(); it != list->end(); it++) {
1087 printf("---------------------------------------------------------------------\n");
1090 void ModelChecker::print_summary()
1093 printf("Number of executions: %d\n", num_executions);
1094 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1098 if (!isfinalfeasible())
1099 printf("INFEASIBLE EXECUTION!\n");
1100 print_list(action_trace);
1105 * Add a Thread to the system for the first time. Should only be called once
1107 * @param t The Thread to add
1109 void ModelChecker::add_thread(Thread *t)
1111 thread_map->put(id_to_int(t->get_id()), t);
1112 scheduler->add_thread(t);
1115 void ModelChecker::remove_thread(Thread *t)
1117 scheduler->remove_thread(t);
1121 * Switch from a user-context to the "master thread" context (a.k.a. system
1122 * context). This switch is made with the intention of exploring a particular
1123 * model-checking action (described by a ModelAction object). Must be called
1124 * from a user-thread context.
1125 * @param act The current action that will be explored. Must not be NULL.
1126 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1128 int ModelChecker::switch_to_master(ModelAction *act)
1131 Thread *old = thread_current();
1132 set_current_action(act);
1133 old->set_state(THREAD_READY);
1134 return Thread::swap(old, &system_context);
1138 * Takes the next step in the execution, if possible.
1139 * @return Returns true (success) if a step was taken and false otherwise.
1141 bool ModelChecker::take_step() {
1142 Thread *curr, *next;
1147 curr = thread_current();
1149 if (curr->get_state() == THREAD_READY) {
1150 ASSERT(priv->current_action);
1151 priv->nextThread = check_current_action(priv->current_action);
1152 priv->current_action = NULL;
1153 if (!curr->is_blocked() && !curr->is_complete())
1154 scheduler->add_thread(curr);
1159 next = scheduler->next_thread(priv->nextThread);
1161 /* Infeasible -> don't take any more steps */
1166 next->set_state(THREAD_RUNNING);
1167 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1169 /* next == NULL -> don't take any more steps */
1172 /* Return false only if swap fails with an error */
1173 return (Thread::swap(&system_context, next) == 0);
1176 /** Runs the current execution until threre are no more steps to take. */
1177 void ModelChecker::finish_execution() {
1180 while (take_step());