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),
40 /* Allocate this "size" on the snapshotting heap */
41 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
42 /* First thread created will have id INITIAL_THREAD_ID */
43 priv->next_thread_id = INITIAL_THREAD_ID;
45 lazy_sync_size = &priv->lazy_sync_size;
48 /** @brief Destructor */
49 ModelChecker::~ModelChecker()
51 for (int i = 0; i < get_num_threads(); i++)
52 delete thread_map->get(i);
59 for (unsigned int i = 0; i < promises->size(); i++)
60 delete (*promises)[i];
63 delete lazy_sync_with_release;
65 delete thrd_last_action;
72 * Restores user program to initial state and resets all model-checker data
75 void ModelChecker::reset_to_initial_state()
77 DEBUG("+++ Resetting to initial state +++\n");
78 node_stack->reset_execution();
79 failed_promise = false;
80 too_many_reads = false;
83 snapshotObject->backTrackBeforeStep(0);
86 /** @returns a thread ID for a new Thread */
87 thread_id_t ModelChecker::get_next_id()
89 return priv->next_thread_id++;
92 /** @returns the number of user threads created during this execution */
93 int ModelChecker::get_num_threads()
95 return priv->next_thread_id;
98 /** @returns a sequence number for a new ModelAction */
99 modelclock_t ModelChecker::get_next_seq_num()
101 return ++priv->used_sequence_numbers;
105 * @brief Choose the next thread to execute.
107 * This function chooses the next thread that should execute. It can force the
108 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
109 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
110 * The model-checker may have no preference regarding the next thread (i.e.,
111 * when exploring a new execution ordering), in which case this will return
113 * @param curr The current ModelAction. This action might guide the choice of
115 * @return The next thread to run. If the model-checker has no preference, NULL.
117 Thread * ModelChecker::get_next_thread(ModelAction *curr)
121 /* Do not split atomic actions. */
123 return thread_current();
124 /* The THREAD_CREATE action points to the created Thread */
125 else if (curr->get_type() == THREAD_CREATE)
126 return (Thread *)curr->get_location();
128 /* Have we completed exploring the preselected path? */
132 /* Else, we are trying to replay an execution */
133 ModelAction *next = node_stack->get_next()->get_action();
135 if (next == diverge) {
136 Node *nextnode = next->get_node();
137 /* Reached divergence point */
138 if (nextnode->increment_promise()) {
139 /* The next node will try to satisfy a different set of promises. */
140 tid = next->get_tid();
141 node_stack->pop_restofstack(2);
142 } else if (nextnode->increment_read_from()) {
143 /* The next node will read from a different value. */
144 tid = next->get_tid();
145 node_stack->pop_restofstack(2);
146 } else if (nextnode->increment_future_value()) {
147 /* The next node will try to read from a different future value. */
148 tid = next->get_tid();
149 node_stack->pop_restofstack(2);
151 /* Make a different thread execute for next step */
152 Node *node = nextnode->get_parent();
153 tid = node->get_next_backtrack();
154 node_stack->pop_restofstack(1);
156 DEBUG("*** Divergence point ***\n");
159 tid = next->get_tid();
161 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
162 ASSERT(tid != THREAD_ID_T_NONE);
163 return thread_map->get(id_to_int(tid));
167 * Queries the model-checker for more executions to explore and, if one
168 * exists, resets the model-checker state to execute a new execution.
170 * @return If there are more executions to explore, return true. Otherwise,
173 bool ModelChecker::next_execution()
179 if (isfinalfeasible() || DBG_ENABLED())
182 if ((diverge = get_next_backtrack()) == NULL)
186 printf("Next execution will diverge at:\n");
190 reset_to_initial_state();
194 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
196 action_type type = act->get_type();
206 /* linear search: from most recent to oldest */
207 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
208 action_list_t::reverse_iterator rit;
209 for (rit = list->rbegin(); rit != list->rend(); rit++) {
210 ModelAction *prev = *rit;
211 if (act->is_synchronizing(prev))
217 void ModelChecker::set_backtracking(ModelAction *act)
221 Thread *t = get_thread(act);
223 prev = get_last_conflict(act);
227 node = prev->get_node()->get_parent();
229 while (!node->is_enabled(t))
232 /* Check if this has been explored already */
233 if (node->has_been_explored(t->get_id()))
236 /* Cache the latest backtracking point */
237 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
238 priv->next_backtrack = prev;
240 /* If this is a new backtracking point, mark the tree */
241 if (!node->set_backtrack(t->get_id()))
243 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
244 prev->get_tid(), t->get_id());
252 * Returns last backtracking point. The model checker will explore a different
253 * path for this point in the next execution.
254 * @return The ModelAction at which the next execution should diverge.
256 ModelAction * ModelChecker::get_next_backtrack()
258 ModelAction *next = priv->next_backtrack;
259 priv->next_backtrack = NULL;
264 /** Checks whether making the ModelAction read read_from the
265 ModelAction write will introduce a cycle in the reads_from
268 @return true if making it read from will be fine, false otherwise.
272 bool ModelChecker::ensure_rmw_acyclic(const ModelAction * read, const ModelAction *write) {
275 if (!write->is_rmw())
282 write=write->get_reads_from();
288 * Processes a read or rmw model action.
289 * @param curr is the read model action to process.
290 * @param th is the thread
291 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
292 * @return True if processing this read updates the mo_graph.
295 bool ModelChecker::process_read(ModelAction *curr, Thread * th, bool second_part_of_rmw) {
299 const ModelAction *reads_from = curr->get_node()->get_read_from();
300 if (reads_from != NULL) {
301 mo_graph->startChanges();
303 value = reads_from->get_value();
304 /* Assign reads_from, perform release/acquire synchronization */
305 if (ensure_rmw_acyclic(curr, reads_from))
306 curr->read_from(reads_from);
307 if (!second_part_of_rmw) {
308 check_recency(curr,false);
311 bool r_status=r_modification_order(curr,reads_from);
313 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||!curr->get_node()->future_value_empty())) {
314 mo_graph->rollbackChanges();
315 too_many_reads=false;
319 mo_graph->commitChanges();
321 } else if (!second_part_of_rmw) {
322 /* Read from future value */
323 value = curr->get_node()->get_future_value();
324 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
325 curr->read_from(NULL);
326 Promise *valuepromise = new Promise(curr, value, expiration);
327 promises->push_back(valuepromise);
329 th->set_return_value(value);
335 * This is the heart of the model checker routine. It performs model-checking
336 * actions corresponding to a given "current action." Among other processes, it
337 * calculates reads-from relationships, updates synchronization clock vectors,
338 * forms a memory_order constraints graph, and handles replay/backtrack
339 * execution when running permutations of previously-observed executions.
341 * @param curr The current action to process
342 * @return The next Thread that must be executed. May be NULL if ModelChecker
343 * makes no choice (e.g., according to replay execution, combining RMW actions,
346 Thread * ModelChecker::check_current_action(ModelAction *curr)
348 bool second_part_of_rmw = false;
352 if (curr->is_rmwc() || curr->is_rmw()) {
353 ModelAction *tmp = process_rmw(curr);
354 second_part_of_rmw = true;
357 compute_promises(curr);
359 ModelAction *tmp = node_stack->explore_action(curr);
361 /* Discard duplicate ModelAction; use action from NodeStack */
362 /* First restore type and order in case of RMW operation */
364 tmp->copy_typeandorder(curr);
366 /* If we have diverged, we need to reset the clock vector. */
368 tmp->create_cv(get_parent_action(tmp->get_tid()));
374 * Perform one-time actions when pushing new ModelAction onto
377 curr->create_cv(get_parent_action(curr->get_tid()));
378 /* Build may_read_from set */
380 build_reads_from_past(curr);
381 if (curr->is_write())
382 compute_promises(curr);
386 /* Thread specific actions */
387 switch(curr->get_type()) {
388 case THREAD_CREATE: {
389 Thread *th = (Thread *)curr->get_location();
390 th->set_creation(curr);
394 Thread *waiting, *blocking;
395 waiting = get_thread(curr);
396 blocking = (Thread *)curr->get_location();
397 if (!blocking->is_complete()) {
398 blocking->push_wait_list(curr);
399 scheduler->sleep(waiting);
403 case THREAD_FINISH: {
404 Thread *th = get_thread(curr);
405 while (!th->wait_list_empty()) {
406 ModelAction *act = th->pop_wait_list();
407 Thread *wake = get_thread(act);
408 scheduler->wake(wake);
414 check_promises(NULL, curr->get_cv());
421 Thread *th = get_thread(curr);
423 bool updated = false;
424 if (curr->is_read()) {
425 updated=process_read(curr, th, second_part_of_rmw);
428 if (curr->is_write()) {
429 bool updated_mod_order=w_modification_order(curr);
430 bool updated_promises=resolve_promises(curr);
431 updated=updated_mod_order|updated_promises;
433 mo_graph->commitChanges();
434 th->set_return_value(VALUE_NONE);
438 resolve_release_sequences(curr->get_location());
440 /* Add action to list. */
441 if (!second_part_of_rmw)
442 add_action_to_lists(curr);
444 check_curr_backtracking(curr);
446 set_backtracking(curr);
448 return get_next_thread(curr);
451 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
452 Node *currnode = curr->get_node();
453 Node *parnode = currnode->get_parent();
455 if ((!parnode->backtrack_empty() ||
456 !currnode->read_from_empty() ||
457 !currnode->future_value_empty() ||
458 !currnode->promise_empty())
459 && (!priv->next_backtrack ||
460 *curr > *priv->next_backtrack)) {
461 priv->next_backtrack = curr;
466 bool ModelChecker::promises_expired() {
467 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
468 Promise *promise = (*promises)[promise_index];
469 if (promise->get_expiration()<priv->used_sequence_numbers) {
476 /** @returns whether the current partial trace must be a prefix of a
478 bool ModelChecker::isfeasibleprefix() {
479 return promises->size() == 0 && *lazy_sync_size == 0;
482 /** @returns whether the current partial trace is feasible. */
483 bool ModelChecker::isfeasible() {
484 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
487 /** @returns whether the current partial trace is feasible other than
488 * multiple RMW reading from the same store. */
489 bool ModelChecker::isfeasibleotherthanRMW() {
490 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !rmw_cycle && !promises_expired();
493 /** Returns whether the current completed trace is feasible. */
494 bool ModelChecker::isfinalfeasible() {
495 return isfeasible() && promises->size() == 0;
498 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
499 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
500 int tid = id_to_int(act->get_tid());
501 ModelAction *lastread = get_last_action(tid);
502 lastread->process_rmw(act);
503 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
504 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
505 mo_graph->commitChanges();
511 * Checks whether a thread has read from the same write for too many times
512 * without seeing the effects of a later write.
515 * 1) there must a different write that we could read from that would satisfy the modification order,
516 * 2) we must have read from the same value in excess of maxreads times, and
517 * 3) that other write must have been in the reads_from set for maxreads times.
519 * If so, we decide that the execution is no longer feasible.
521 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
522 if (params.maxreads != 0) {
523 if (curr->get_node()->get_read_from_size() <= 1)
526 //Must make sure that execution is currently feasible... We could
527 //accidentally clear by rolling back
531 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
532 int tid = id_to_int(curr->get_tid());
535 if ((int)thrd_lists->size() <= tid)
538 action_list_t *list = &(*thrd_lists)[tid];
540 action_list_t::reverse_iterator rit = list->rbegin();
543 for (; (*rit) != curr; rit++)
545 /* go past curr now */
549 action_list_t::reverse_iterator ritcopy=rit;
550 //See if we have enough reads from the same value
552 for (; count < params.maxreads; rit++,count++) {
553 if (rit==list->rend())
555 ModelAction *act = *rit;
558 if (act->get_reads_from() != curr->get_reads_from())
560 if (act->get_node()->get_read_from_size() <= 1)
564 for (int i=0;i<curr->get_node()->get_read_from_size();i++) {
566 const ModelAction * write=curr->get_node()->get_read_from_at(i);
567 //Need a different write
568 if (write==curr->get_reads_from())
571 /* Test to see whether this is a feasible write to read from*/
572 mo_graph->startChanges();
573 r_modification_order(curr, write);
574 bool feasiblereadfrom=isfeasible();
575 mo_graph->rollbackChanges();
577 if (!feasiblereadfrom)
581 bool feasiblewrite=true;
582 //new we need to see if this write works for everyone
584 for (int loop=count;loop>0;loop--,rit++) {
585 ModelAction *act=*rit;
586 bool foundvalue=false;
587 for(int j=0;j<act->get_node()->get_read_from_size();j++) {
588 if (act->get_node()->get_read_from_at(i)==write) {
599 too_many_reads = true;
607 * Updates the mo_graph with the constraints imposed from the current read.
608 * @param curr The current action. Must be a read.
609 * @param rf The action that curr reads from. Must be a write.
610 * @return True if modification order edges were added; false otherwise
612 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
614 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
617 ASSERT(curr->is_read());
619 /* Iterate over all threads */
620 for (i = 0; i < thrd_lists->size(); i++) {
621 /* Iterate over actions in thread, starting from most recent */
622 action_list_t *list = &(*thrd_lists)[i];
623 action_list_t::reverse_iterator rit;
624 for (rit = list->rbegin(); rit != list->rend(); rit++) {
625 ModelAction *act = *rit;
627 /* Include at most one act per-thread that "happens before" curr */
628 if (act->happens_before(curr)) {
629 if (act->is_read()) {
630 const ModelAction *prevreadfrom = act->get_reads_from();
631 if (prevreadfrom != NULL && rf != prevreadfrom) {
632 mo_graph->addEdge(prevreadfrom, rf);
635 } else if (rf != act) {
636 mo_graph->addEdge(act, rf);
647 /** Updates the mo_graph with the constraints imposed from the current read. */
648 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
650 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
652 ASSERT(curr->is_read());
654 /* Iterate over all threads */
655 for (i = 0; i < thrd_lists->size(); i++) {
656 /* Iterate over actions in thread, starting from most recent */
657 action_list_t *list = &(*thrd_lists)[i];
658 action_list_t::reverse_iterator rit;
659 ModelAction *lastact = NULL;
661 /* Find last action that happens after curr */
662 for (rit = list->rbegin(); rit != list->rend(); rit++) {
663 ModelAction *act = *rit;
664 if (curr->happens_before(act)) {
670 /* Include at most one act per-thread that "happens before" curr */
671 if (lastact != NULL) {
672 if (lastact->is_read()) {
673 const ModelAction *postreadfrom = lastact->get_reads_from();
674 if (postreadfrom != NULL&&rf != postreadfrom)
675 mo_graph->addEdge(rf, postreadfrom);
676 } else if (rf != lastact) {
677 mo_graph->addEdge(rf, lastact);
685 * Updates the mo_graph with the constraints imposed from the current write.
686 * @param curr The current action. Must be a write.
687 * @return True if modification order edges were added; false otherwise
689 bool ModelChecker::w_modification_order(ModelAction *curr)
691 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
694 ASSERT(curr->is_write());
696 if (curr->is_seqcst()) {
697 /* We have to at least see the last sequentially consistent write,
698 so we are initialized. */
699 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
700 if (last_seq_cst != NULL) {
701 mo_graph->addEdge(last_seq_cst, curr);
706 /* Iterate over all threads */
707 for (i = 0; i < thrd_lists->size(); i++) {
708 /* Iterate over actions in thread, starting from most recent */
709 action_list_t *list = &(*thrd_lists)[i];
710 action_list_t::reverse_iterator rit;
711 for (rit = list->rbegin(); rit != list->rend(); rit++) {
712 ModelAction *act = *rit;
714 /* Include at most one act per-thread that "happens before" curr */
715 if (act->happens_before(curr)) {
717 * Note: if act is RMW, just add edge:
719 * The following edge should be handled elsewhere:
720 * readfrom(act) --mo--> act
722 if (act->is_write()) {
723 //RMW shouldn't have an edge to themselves
725 mo_graph->addEdge(act, curr);
726 } else if (act->is_read() && act->get_reads_from() != NULL)
727 mo_graph->addEdge(act->get_reads_from(), curr);
730 } else if (act->is_read() && !act->is_synchronizing(curr) &&
731 !act->same_thread(curr)) {
732 /* We have an action that:
733 (1) did not happen before us
734 (2) is a read and we are a write
735 (3) cannot synchronize with us
736 (4) is in a different thread
738 that read could potentially read from our write.
740 if (thin_air_constraint_may_allow(curr, act)) {
742 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
743 if (act->get_node()->add_future_value(curr->get_value(), curr->get_seq_number()+params.maxfuturedelay) &&
744 (!priv->next_backtrack || *act > *priv->next_backtrack))
745 priv->next_backtrack = act;
755 /** Arbitrary reads from the future are not allowed. Section 29.3
756 * part 9 places some constraints. This method checks one result of constraint
757 * constraint. Others require compiler support. */
759 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
760 if (!writer->is_rmw())
763 if (!reader->is_rmw())
766 for(const ModelAction *search=writer->get_reads_from();search!=NULL;search=search->get_reads_from()) {
769 if (search->get_tid()==reader->get_tid()&&
770 search->happens_before(reader))
779 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
780 * The ModelAction under consideration is expected to be taking part in
781 * release/acquire synchronization as an object of the "reads from" relation.
782 * Note that this can only provide release sequence support for RMW chains
783 * which do not read from the future, as those actions cannot be traced until
784 * their "promise" is fulfilled. Similarly, we may not even establish the
785 * presence of a release sequence with certainty, as some modification order
786 * constraints may be decided further in the future. Thus, this function
787 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
788 * and a boolean representing certainty.
790 * @todo Finish lazy updating, when promises are fulfilled in the future
791 * @param rf The action that might be part of a release sequence. Must be a
793 * @param release_heads A pass-by-reference style return parameter. After
794 * execution of this function, release_heads will contain the heads of all the
795 * relevant release sequences, if any exists
796 * @return true, if the ModelChecker is certain that release_heads is complete;
799 bool ModelChecker::release_seq_head(const ModelAction *rf,
800 std::vector<const ModelAction *> *release_heads) const
802 ASSERT(rf->is_write());
804 /* read from future: need to settle this later */
805 return false; /* incomplete */
807 if (rf->is_release())
808 release_heads->push_back(rf);
810 /* We need a RMW action that is both an acquire and release to stop */
811 /** @todo Need to be smarter here... In the linux lock
812 * example, this will run to the beginning of the program for
814 if (rf->is_acquire() && rf->is_release())
815 return true; /* complete */
816 return release_seq_head(rf->get_reads_from(), release_heads);
818 if (rf->is_release())
819 return true; /* complete */
821 /* else relaxed write; check modification order for contiguous subsequence
822 * -> rf must be same thread as release */
823 int tid = id_to_int(rf->get_tid());
824 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
825 action_list_t *list = &(*thrd_lists)[tid];
826 action_list_t::const_reverse_iterator rit;
828 /* Find rf in the thread list */
829 rit = std::find(list->rbegin(), list->rend(), rf);
830 ASSERT(rit != list->rend());
832 /* Find the last write/release */
833 for (; rit != list->rend(); rit++)
834 if ((*rit)->is_release())
836 if (rit == list->rend()) {
837 /* No write-release in this thread */
838 return true; /* complete */
840 ModelAction *release = *rit;
842 ASSERT(rf->same_thread(release));
845 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
846 if (id_to_int(rf->get_tid()) == (int)i)
848 list = &(*thrd_lists)[i];
850 /* Can we ensure no future writes from this thread may break
851 * the release seq? */
852 bool future_ordered = false;
854 for (rit = list->rbegin(); rit != list->rend(); rit++) {
855 const ModelAction *act = *rit;
856 if (!act->is_write())
858 /* Reach synchronization -> this thread is complete */
859 if (act->happens_before(release))
861 if (rf->happens_before(act)) {
862 future_ordered = true;
866 /* Check modification order */
867 if (mo_graph->checkReachable(rf, act)) {
869 future_ordered = true;
872 if (mo_graph->checkReachable(act, release))
873 /* act --mo--> release */
875 if (mo_graph->checkReachable(release, act) &&
876 mo_graph->checkReachable(act, rf)) {
877 /* release --mo-> act --mo--> rf */
878 return true; /* complete */
883 return false; /* This thread is uncertain */
887 release_heads->push_back(release);
892 * A public interface for getting the release sequence head(s) with which a
893 * given ModelAction must synchronize. This function only returns a non-empty
894 * result when it can locate a release sequence head with certainty. Otherwise,
895 * it may mark the internal state of the ModelChecker so that it will handle
896 * the release sequence at a later time, causing @a act to update its
897 * synchronization at some later point in execution.
898 * @param act The 'acquire' action that may read from a release sequence
899 * @param release_heads A pass-by-reference return parameter. Will be filled
900 * with the head(s) of the release sequence(s), if they exists with certainty.
901 * @see ModelChecker::release_seq_head
903 void ModelChecker::get_release_seq_heads(ModelAction *act,
904 std::vector<const ModelAction *> *release_heads)
906 const ModelAction *rf = act->get_reads_from();
908 complete = release_seq_head(rf, release_heads);
910 /* add act to 'lazy checking' list */
911 std::list<ModelAction *> *list;
912 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
913 list->push_back(act);
919 * Attempt to resolve all stashed operations that might synchronize with a
920 * release sequence for a given location. This implements the "lazy" portion of
921 * determining whether or not a release sequence was contiguous, since not all
922 * modification order information is present at the time an action occurs.
924 * @param location The location/object that should be checked for release
925 * sequence resolutions
926 * @return True if any updates occurred (new synchronization, new mo_graph edges)
928 bool ModelChecker::resolve_release_sequences(void *location)
930 std::list<ModelAction *> *list;
931 list = lazy_sync_with_release->getptr(location);
935 bool updated = false;
936 std::list<ModelAction *>::iterator it = list->begin();
937 while (it != list->end()) {
938 ModelAction *act = *it;
939 const ModelAction *rf = act->get_reads_from();
940 std::vector<const ModelAction *> release_heads;
942 complete = release_seq_head(rf, &release_heads);
943 for (unsigned int i = 0; i < release_heads.size(); i++) {
944 if (!act->has_synchronized_with(release_heads[i])) {
946 act->synchronize_with(release_heads[i]);
951 /* propagate synchronization to later actions */
952 action_list_t::reverse_iterator it = action_trace->rbegin();
953 while ((*it) != act) {
954 ModelAction *propagate = *it;
955 if (act->happens_before(propagate))
956 /** @todo new mo_graph edges along with
957 * this synchronization? */
958 propagate->synchronize_with(act);
962 it = list->erase(it);
968 // If we resolved promises or data races, see if we have realized a data race.
969 if (checkDataRaces()) {
977 * Performs various bookkeeping operations for the current ModelAction. For
978 * instance, adds action to the per-object, per-thread action vector and to the
979 * action trace list of all thread actions.
981 * @param act is the ModelAction to add.
983 void ModelChecker::add_action_to_lists(ModelAction *act)
985 int tid = id_to_int(act->get_tid());
986 action_trace->push_back(act);
988 obj_map->get_safe_ptr(act->get_location())->push_back(act);
990 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
991 if (tid >= (int)vec->size())
992 vec->resize(priv->next_thread_id);
993 (*vec)[tid].push_back(act);
995 if ((int)thrd_last_action->size() <= tid)
996 thrd_last_action->resize(get_num_threads());
997 (*thrd_last_action)[tid] = act;
1000 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1002 int nthreads = get_num_threads();
1003 if ((int)thrd_last_action->size() < nthreads)
1004 thrd_last_action->resize(nthreads);
1005 return (*thrd_last_action)[id_to_int(tid)];
1009 * Gets the last memory_order_seq_cst action (in the total global sequence)
1010 * performed on a particular object (i.e., memory location).
1011 * @param location The object location to check
1012 * @return The last seq_cst action performed
1014 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1016 action_list_t *list = obj_map->get_safe_ptr(location);
1017 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1018 action_list_t::reverse_iterator rit;
1019 for (rit = list->rbegin(); rit != list->rend(); rit++)
1020 if ((*rit)->is_write() && (*rit)->is_seqcst())
1025 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1027 ModelAction *parent = get_last_action(tid);
1029 parent = get_thread(tid)->get_creation();
1034 * Returns the clock vector for a given thread.
1035 * @param tid The thread whose clock vector we want
1036 * @return Desired clock vector
1038 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1040 return get_parent_action(tid)->get_cv();
1044 * Resolve a set of Promises with a current write. The set is provided in the
1045 * Node corresponding to @a write.
1046 * @param write The ModelAction that is fulfilling Promises
1047 * @return True if promises were resolved; false otherwise
1049 bool ModelChecker::resolve_promises(ModelAction *write)
1051 bool resolved = false;
1053 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1054 Promise *promise = (*promises)[promise_index];
1055 if (write->get_node()->get_promise(i)) {
1056 ModelAction *read = promise->get_action();
1057 if (ensure_rmw_acyclic(read, write))
1058 read->read_from(write);
1059 if (read->is_rmw()) {
1060 mo_graph->addRMWEdge(write, read);
1062 r_modification_order(read, write);
1063 post_r_modification_order(read, write);
1064 promises->erase(promises->begin() + promise_index);
1075 * Compute the set of promises that could potentially be satisfied by this
1076 * action. Note that the set computation actually appears in the Node, not in
1078 * @param curr The ModelAction that may satisfy promises
1080 void ModelChecker::compute_promises(ModelAction *curr)
1082 for (unsigned int i = 0; i < promises->size(); i++) {
1083 Promise *promise = (*promises)[i];
1084 const ModelAction *act = promise->get_action();
1085 if (!act->happens_before(curr) &&
1087 !act->is_synchronizing(curr) &&
1088 !act->same_thread(curr) &&
1089 promise->get_value() == curr->get_value()) {
1090 curr->get_node()->set_promise(i);
1095 /** Checks promises in response to change in ClockVector Threads. */
1096 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1098 for (unsigned int i = 0; i < promises->size(); i++) {
1099 Promise *promise = (*promises)[i];
1100 const ModelAction *act = promise->get_action();
1101 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1102 merge_cv->synchronized_since(act)) {
1103 //This thread is no longer able to send values back to satisfy the promise
1104 int num_synchronized_threads = promise->increment_threads();
1105 if (num_synchronized_threads == get_num_threads()) {
1106 //Promise has failed
1107 failed_promise = true;
1115 * Build up an initial set of all past writes that this 'read' action may read
1116 * from. This set is determined by the clock vector's "happens before"
1118 * @param curr is the current ModelAction that we are exploring; it must be a
1121 void ModelChecker::build_reads_from_past(ModelAction *curr)
1123 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1125 ASSERT(curr->is_read());
1127 ModelAction *last_seq_cst = NULL;
1129 /* Track whether this object has been initialized */
1130 bool initialized = false;
1132 if (curr->is_seqcst()) {
1133 last_seq_cst = get_last_seq_cst(curr->get_location());
1134 /* We have to at least see the last sequentially consistent write,
1135 so we are initialized. */
1136 if (last_seq_cst != NULL)
1140 /* Iterate over all threads */
1141 for (i = 0; i < thrd_lists->size(); i++) {
1142 /* Iterate over actions in thread, starting from most recent */
1143 action_list_t *list = &(*thrd_lists)[i];
1144 action_list_t::reverse_iterator rit;
1145 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1146 ModelAction *act = *rit;
1148 /* Only consider 'write' actions */
1149 if (!act->is_write())
1152 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1153 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1154 DEBUG("Adding action to may_read_from:\n");
1155 if (DBG_ENABLED()) {
1159 curr->get_node()->add_read_from(act);
1162 /* Include at most one act per-thread that "happens before" curr */
1163 if (act->happens_before(curr)) {
1171 /** @todo Need a more informative way of reporting errors. */
1172 printf("ERROR: may read from uninitialized atomic\n");
1175 if (DBG_ENABLED() || !initialized) {
1176 printf("Reached read action:\n");
1178 printf("Printing may_read_from\n");
1179 curr->get_node()->print_may_read_from();
1180 printf("End printing may_read_from\n");
1183 ASSERT(initialized);
1186 static void print_list(action_list_t *list)
1188 action_list_t::iterator it;
1190 printf("---------------------------------------------------------------------\n");
1193 for (it = list->begin(); it != list->end(); it++) {
1196 printf("---------------------------------------------------------------------\n");
1199 void ModelChecker::print_summary()
1202 printf("Number of executions: %d\n", num_executions);
1203 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1207 if (!isfinalfeasible())
1208 printf("INFEASIBLE EXECUTION!\n");
1209 print_list(action_trace);
1214 * Add a Thread to the system for the first time. Should only be called once
1216 * @param t The Thread to add
1218 void ModelChecker::add_thread(Thread *t)
1220 thread_map->put(id_to_int(t->get_id()), t);
1221 scheduler->add_thread(t);
1224 void ModelChecker::remove_thread(Thread *t)
1226 scheduler->remove_thread(t);
1230 * Switch from a user-context to the "master thread" context (a.k.a. system
1231 * context). This switch is made with the intention of exploring a particular
1232 * model-checking action (described by a ModelAction object). Must be called
1233 * from a user-thread context.
1234 * @param act The current action that will be explored. Must not be NULL.
1235 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1237 int ModelChecker::switch_to_master(ModelAction *act)
1240 Thread *old = thread_current();
1241 set_current_action(act);
1242 old->set_state(THREAD_READY);
1243 return Thread::swap(old, &system_context);
1247 * Takes the next step in the execution, if possible.
1248 * @return Returns true (success) if a step was taken and false otherwise.
1250 bool ModelChecker::take_step() {
1251 Thread *curr, *next;
1256 curr = thread_current();
1258 if (curr->get_state() == THREAD_READY) {
1259 ASSERT(priv->current_action);
1261 priv->nextThread = check_current_action(priv->current_action);
1262 priv->current_action = NULL;
1263 if (!curr->is_blocked() && !curr->is_complete())
1264 scheduler->add_thread(curr);
1269 next = scheduler->next_thread(priv->nextThread);
1271 /* Infeasible -> don't take any more steps */
1276 next->set_state(THREAD_RUNNING);
1277 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1279 /* next == NULL -> don't take any more steps */
1282 /* Return false only if swap fails with an error */
1283 return (Thread::swap(&system_context, next) == 0);
1286 /** Runs the current execution until threre are no more steps to take. */
1287 void ModelChecker::finish_execution() {
1290 while (take_step());