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 futurevalues(new std::vector<struct PendingFutureValue>()),
32 lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
33 thrd_last_action(new std::vector<ModelAction *>(1)),
34 node_stack(new NodeStack()),
35 mo_graph(new CycleGraph()),
36 failed_promise(false),
37 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;
82 snapshotObject->backTrackBeforeStep(0);
85 /** @returns a thread ID for a new Thread */
86 thread_id_t ModelChecker::get_next_id()
88 return priv->next_thread_id++;
91 /** @returns the number of user threads created during this execution */
92 int ModelChecker::get_num_threads()
94 return priv->next_thread_id;
97 /** @returns a sequence number for a new ModelAction */
98 modelclock_t ModelChecker::get_next_seq_num()
100 return ++priv->used_sequence_numbers;
104 * @brief Choose the next thread to execute.
106 * This function chooses the next thread that should execute. It can force the
107 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
108 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
109 * The model-checker may have no preference regarding the next thread (i.e.,
110 * when exploring a new execution ordering), in which case this will return
112 * @param curr The current ModelAction. This action might guide the choice of
114 * @return The next thread to run. If the model-checker has no preference, NULL.
116 Thread * ModelChecker::get_next_thread(ModelAction *curr)
120 /* Do not split atomic actions. */
122 return thread_current();
123 /* The THREAD_CREATE action points to the created Thread */
124 else if (curr->get_type() == THREAD_CREATE)
125 return (Thread *)curr->get_location();
127 /* Have we completed exploring the preselected path? */
131 /* Else, we are trying to replay an execution */
132 ModelAction *next = node_stack->get_next()->get_action();
134 if (next == diverge) {
135 Node *nextnode = next->get_node();
136 /* Reached divergence point */
137 if (nextnode->increment_promise()) {
138 /* The next node will try to satisfy a different set of promises. */
139 tid = next->get_tid();
140 node_stack->pop_restofstack(2);
141 } else if (nextnode->increment_read_from()) {
142 /* The next node will read from a different value. */
143 tid = next->get_tid();
144 node_stack->pop_restofstack(2);
145 } else if (nextnode->increment_future_value()) {
146 /* The next node will try to read from a different future value. */
147 tid = next->get_tid();
148 node_stack->pop_restofstack(2);
150 /* Make a different thread execute for next step */
151 Node *node = nextnode->get_parent();
152 tid = node->get_next_backtrack();
153 node_stack->pop_restofstack(1);
155 DEBUG("*** Divergence point ***\n");
158 tid = next->get_tid();
160 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
161 ASSERT(tid != THREAD_ID_T_NONE);
162 return thread_map->get(id_to_int(tid));
166 * Queries the model-checker for more executions to explore and, if one
167 * exists, resets the model-checker state to execute a new execution.
169 * @return If there are more executions to explore, return true. Otherwise,
172 bool ModelChecker::next_execution()
178 if (isfinalfeasible() || DBG_ENABLED())
181 if ((diverge = get_next_backtrack()) == NULL)
185 printf("Next execution will diverge at:\n");
189 reset_to_initial_state();
193 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
195 action_type type = act->get_type();
205 /* linear search: from most recent to oldest */
206 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
207 action_list_t::reverse_iterator rit;
208 for (rit = list->rbegin(); rit != list->rend(); rit++) {
209 ModelAction *prev = *rit;
210 if (act->is_synchronizing(prev))
216 void ModelChecker::set_backtracking(ModelAction *act)
220 Thread *t = get_thread(act);
222 prev = get_last_conflict(act);
226 node = prev->get_node()->get_parent();
228 while (!node->is_enabled(t))
231 /* Check if this has been explored already */
232 if (node->has_been_explored(t->get_id()))
235 /* Cache the latest backtracking point */
236 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
237 priv->next_backtrack = prev;
239 /* If this is a new backtracking point, mark the tree */
240 if (!node->set_backtrack(t->get_id()))
242 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
243 prev->get_tid(), t->get_id());
251 * Returns last backtracking point. The model checker will explore a different
252 * path for this point in the next execution.
253 * @return The ModelAction at which the next execution should diverge.
255 ModelAction * ModelChecker::get_next_backtrack()
257 ModelAction *next = priv->next_backtrack;
258 priv->next_backtrack = NULL;
263 * Processes a read or rmw model action.
264 * @param curr is the read model action to process.
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.
268 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
271 bool updated = false;
273 const ModelAction *reads_from = curr->get_node()->get_read_from();
274 if (reads_from != NULL) {
275 mo_graph->startChanges();
277 value = reads_from->get_value();
278 bool r_status = false;
280 if (!second_part_of_rmw) {
281 check_recency(curr,false);
282 r_status = r_modification_order(curr, reads_from);
286 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
287 mo_graph->rollbackChanges();
288 too_many_reads = false;
292 curr->read_from(reads_from);
293 mo_graph->commitChanges();
295 } else if (!second_part_of_rmw) {
296 /* Read from future value */
297 value = curr->get_node()->get_future_value();
298 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
299 curr->read_from(NULL);
300 Promise *valuepromise = new Promise(curr, value, expiration);
301 promises->push_back(valuepromise);
303 get_thread(curr)->set_return_value(value);
309 * Process a write ModelAction
310 * @param curr The ModelAction to process
311 * @return True if the mo_graph was updated or promises were resolved
313 bool ModelChecker::process_write(ModelAction *curr)
315 bool updated_mod_order = w_modification_order(curr);
316 bool updated_promises = resolve_promises(curr);
318 if (promises->size() == 0) {
319 for (unsigned int i = 0; i<futurevalues->size(); i++) {
320 struct PendingFutureValue pfv = (*futurevalues)[i];
321 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
322 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
323 priv->next_backtrack = pfv.act;
325 futurevalues->resize(0);
328 mo_graph->commitChanges();
329 get_thread(curr)->set_return_value(VALUE_NONE);
330 return updated_mod_order || updated_promises;
334 * This is the heart of the model checker routine. It performs model-checking
335 * actions corresponding to a given "current action." Among other processes, it
336 * calculates reads-from relationships, updates synchronization clock vectors,
337 * forms a memory_order constraints graph, and handles replay/backtrack
338 * execution when running permutations of previously-observed executions.
340 * @param curr The current action to process
341 * @return The next Thread that must be executed. May be NULL if ModelChecker
342 * makes no choice (e.g., according to replay execution, combining RMW actions,
345 Thread * ModelChecker::check_current_action(ModelAction *curr)
347 bool second_part_of_rmw = false;
351 if (curr->is_rmwc() || curr->is_rmw()) {
352 ModelAction *tmp = process_rmw(curr);
353 second_part_of_rmw = true;
356 compute_promises(curr);
358 ModelAction *tmp = node_stack->explore_action(curr);
360 /* Discard duplicate ModelAction; use action from NodeStack */
361 /* First restore type and order in case of RMW operation */
363 tmp->copy_typeandorder(curr);
365 /* If we have diverged, we need to reset the clock vector. */
367 tmp->create_cv(get_parent_action(tmp->get_tid()));
373 * Perform one-time actions when pushing new ModelAction onto
376 curr->create_cv(get_parent_action(curr->get_tid()));
377 /* Build may_read_from set */
379 build_reads_from_past(curr);
380 if (curr->is_write())
381 compute_promises(curr);
385 /* Thread specific actions */
386 switch (curr->get_type()) {
387 case THREAD_CREATE: {
388 Thread *th = (Thread *)curr->get_location();
389 th->set_creation(curr);
393 Thread *waiting, *blocking;
394 waiting = get_thread(curr);
395 blocking = (Thread *)curr->get_location();
396 if (!blocking->is_complete()) {
397 blocking->push_wait_list(curr);
398 scheduler->sleep(waiting);
402 case THREAD_FINISH: {
403 Thread *th = get_thread(curr);
404 while (!th->wait_list_empty()) {
405 ModelAction *act = th->pop_wait_list();
406 Thread *wake = get_thread(act);
407 scheduler->wake(wake);
413 check_promises(NULL, curr->get_cv());
420 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
422 while (!work_queue.empty()) {
423 WorkQueueEntry work = work_queue.front();
424 work_queue.pop_front();
427 case WORK_CHECK_CURR_ACTION: {
428 ModelAction *act = work.action;
429 bool updated = false;
430 if (act->is_read() && process_read(act, second_part_of_rmw))
433 if (act->is_write() && process_write(act))
437 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
440 case WORK_CHECK_RELEASE_SEQ:
441 resolve_release_sequences(work.location, &work_queue);
443 case WORK_CHECK_MO_EDGES:
444 /** @todo Perform follow-up mo_graph checks */
451 /* Add action to list. */
452 if (!second_part_of_rmw)
453 add_action_to_lists(curr);
455 check_curr_backtracking(curr);
457 set_backtracking(curr);
459 return get_next_thread(curr);
462 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
463 Node *currnode = curr->get_node();
464 Node *parnode = currnode->get_parent();
466 if ((!parnode->backtrack_empty() ||
467 !currnode->read_from_empty() ||
468 !currnode->future_value_empty() ||
469 !currnode->promise_empty())
470 && (!priv->next_backtrack ||
471 *curr > *priv->next_backtrack)) {
472 priv->next_backtrack = curr;
476 bool ModelChecker::promises_expired() {
477 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
478 Promise *promise = (*promises)[promise_index];
479 if (promise->get_expiration()<priv->used_sequence_numbers) {
486 /** @returns whether the current partial trace must be a prefix of a
488 bool ModelChecker::isfeasibleprefix() {
489 return promises->size() == 0 && *lazy_sync_size == 0;
492 /** @returns whether the current partial trace is feasible. */
493 bool ModelChecker::isfeasible() {
494 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
497 /** @returns whether the current partial trace is feasible other than
498 * multiple RMW reading from the same store. */
499 bool ModelChecker::isfeasibleotherthanRMW() {
500 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
503 /** Returns whether the current completed trace is feasible. */
504 bool ModelChecker::isfinalfeasible() {
505 return isfeasible() && promises->size() == 0;
508 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
509 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
510 int tid = id_to_int(act->get_tid());
511 ModelAction *lastread = get_last_action(tid);
512 lastread->process_rmw(act);
513 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
514 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
515 mo_graph->commitChanges();
521 * Checks whether a thread has read from the same write for too many times
522 * without seeing the effects of a later write.
525 * 1) there must a different write that we could read from that would satisfy the modification order,
526 * 2) we must have read from the same value in excess of maxreads times, and
527 * 3) that other write must have been in the reads_from set for maxreads times.
529 * If so, we decide that the execution is no longer feasible.
531 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
532 if (params.maxreads != 0) {
533 if (curr->get_node()->get_read_from_size() <= 1)
536 //Must make sure that execution is currently feasible... We could
537 //accidentally clear by rolling back
541 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
542 int tid = id_to_int(curr->get_tid());
545 if ((int)thrd_lists->size() <= tid)
548 action_list_t *list = &(*thrd_lists)[tid];
550 action_list_t::reverse_iterator rit = list->rbegin();
553 for (; (*rit) != curr; rit++)
555 /* go past curr now */
559 action_list_t::reverse_iterator ritcopy = rit;
560 //See if we have enough reads from the same value
562 for (; count < params.maxreads; rit++,count++) {
563 if (rit==list->rend())
565 ModelAction *act = *rit;
568 if (act->get_reads_from() != curr->get_reads_from())
570 if (act->get_node()->get_read_from_size() <= 1)
574 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
576 const ModelAction * write = curr->get_node()->get_read_from_at(i);
577 //Need a different write
578 if (write==curr->get_reads_from())
581 /* Test to see whether this is a feasible write to read from*/
582 mo_graph->startChanges();
583 r_modification_order(curr, write);
584 bool feasiblereadfrom = isfeasible();
585 mo_graph->rollbackChanges();
587 if (!feasiblereadfrom)
591 bool feasiblewrite = true;
592 //new we need to see if this write works for everyone
594 for (int loop = count; loop>0; loop--,rit++) {
595 ModelAction *act=*rit;
596 bool foundvalue = false;
597 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
598 if (act->get_node()->get_read_from_at(i)==write) {
604 feasiblewrite = false;
609 too_many_reads = true;
617 * Updates the mo_graph with the constraints imposed from the current read.
618 * @param curr The current action. Must be a read.
619 * @param rf The action that curr reads from. Must be a write.
620 * @return True if modification order edges were added; false otherwise
622 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
624 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
627 ASSERT(curr->is_read());
629 /* Iterate over all threads */
630 for (i = 0; i < thrd_lists->size(); i++) {
631 /* Iterate over actions in thread, starting from most recent */
632 action_list_t *list = &(*thrd_lists)[i];
633 action_list_t::reverse_iterator rit;
634 for (rit = list->rbegin(); rit != list->rend(); rit++) {
635 ModelAction *act = *rit;
637 /* Include at most one act per-thread that "happens before" curr */
638 if (act->happens_before(curr)) {
639 if (act->is_write()) {
640 if (rf != act && act != curr) {
641 mo_graph->addEdge(act, rf);
645 const ModelAction *prevreadfrom = act->get_reads_from();
646 if (prevreadfrom != NULL && rf != prevreadfrom) {
647 mo_graph->addEdge(prevreadfrom, rf);
660 /** Updates the mo_graph with the constraints imposed from the current read. */
661 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
663 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
665 ASSERT(curr->is_read());
667 /* Iterate over all threads */
668 for (i = 0; i < thrd_lists->size(); i++) {
669 /* Iterate over actions in thread, starting from most recent */
670 action_list_t *list = &(*thrd_lists)[i];
671 action_list_t::reverse_iterator rit;
672 ModelAction *lastact = NULL;
674 /* Find last action that happens after curr */
675 for (rit = list->rbegin(); rit != list->rend(); rit++) {
676 ModelAction *act = *rit;
677 if (curr->happens_before(act)) {
683 /* Include at most one act per-thread that "happens before" curr */
684 if (lastact != NULL) {
685 if (lastact->is_read()) {
686 const ModelAction *postreadfrom = lastact->get_reads_from();
687 if (postreadfrom != NULL&&rf != postreadfrom)
688 mo_graph->addEdge(rf, postreadfrom);
689 } else if (rf != lastact) {
690 mo_graph->addEdge(rf, lastact);
698 * Updates the mo_graph with the constraints imposed from the current write.
699 * @param curr The current action. Must be a write.
700 * @return True if modification order edges were added; false otherwise
702 bool ModelChecker::w_modification_order(ModelAction *curr)
704 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
707 ASSERT(curr->is_write());
709 if (curr->is_seqcst()) {
710 /* We have to at least see the last sequentially consistent write,
711 so we are initialized. */
712 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
713 if (last_seq_cst != NULL) {
714 mo_graph->addEdge(last_seq_cst, curr);
719 /* Iterate over all threads */
720 for (i = 0; i < thrd_lists->size(); i++) {
721 /* Iterate over actions in thread, starting from most recent */
722 action_list_t *list = &(*thrd_lists)[i];
723 action_list_t::reverse_iterator rit;
724 for (rit = list->rbegin(); rit != list->rend(); rit++) {
725 ModelAction *act = *rit;
727 /* Include at most one act per-thread that "happens before" curr */
728 if (act->happens_before(curr)) {
730 * Note: if act is RMW, just add edge:
732 * The following edge should be handled elsewhere:
733 * readfrom(act) --mo--> act
735 if (act->is_write()) {
736 //RMW shouldn't have an edge to themselves
738 mo_graph->addEdge(act, curr);
739 } else if (act->is_read() && act->get_reads_from() != NULL)
740 mo_graph->addEdge(act->get_reads_from(), curr);
743 } else if (act->is_read() && !act->is_synchronizing(curr) &&
744 !act->same_thread(curr)) {
745 /* We have an action that:
746 (1) did not happen before us
747 (2) is a read and we are a write
748 (3) cannot synchronize with us
749 (4) is in a different thread
751 that read could potentially read from our write.
753 if (thin_air_constraint_may_allow(curr, act)) {
755 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
756 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
757 futurevalues->push_back(pfv);
767 /** Arbitrary reads from the future are not allowed. Section 29.3
768 * part 9 places some constraints. This method checks one result of constraint
769 * constraint. Others require compiler support. */
771 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
772 if (!writer->is_rmw())
775 if (!reader->is_rmw())
778 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
781 if (search->get_tid() == reader->get_tid() &&
782 search->happens_before(reader))
790 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
791 * The ModelAction under consideration is expected to be taking part in
792 * release/acquire synchronization as an object of the "reads from" relation.
793 * Note that this can only provide release sequence support for RMW chains
794 * which do not read from the future, as those actions cannot be traced until
795 * their "promise" is fulfilled. Similarly, we may not even establish the
796 * presence of a release sequence with certainty, as some modification order
797 * constraints may be decided further in the future. Thus, this function
798 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
799 * and a boolean representing certainty.
801 * @todo Finish lazy updating, when promises are fulfilled in the future
802 * @param rf The action that might be part of a release sequence. Must be a
804 * @param release_heads A pass-by-reference style return parameter. After
805 * execution of this function, release_heads will contain the heads of all the
806 * relevant release sequences, if any exists
807 * @return true, if the ModelChecker is certain that release_heads is complete;
810 bool ModelChecker::release_seq_head(const ModelAction *rf,
811 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
814 /* read from future: need to settle this later */
815 return false; /* incomplete */
818 ASSERT(rf->is_write());
820 if (rf->is_release())
821 release_heads->push_back(rf);
823 /* We need a RMW action that is both an acquire and release to stop */
824 /** @todo Need to be smarter here... In the linux lock
825 * example, this will run to the beginning of the program for
827 if (rf->is_acquire() && rf->is_release())
828 return true; /* complete */
829 return release_seq_head(rf->get_reads_from(), release_heads);
831 if (rf->is_release())
832 return true; /* complete */
834 /* else relaxed write; check modification order for contiguous subsequence
835 * -> rf must be same thread as release */
836 int tid = id_to_int(rf->get_tid());
837 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
838 action_list_t *list = &(*thrd_lists)[tid];
839 action_list_t::const_reverse_iterator rit;
841 /* Find rf in the thread list */
842 rit = std::find(list->rbegin(), list->rend(), rf);
843 ASSERT(rit != list->rend());
845 /* Find the last write/release */
846 for (; rit != list->rend(); rit++)
847 if ((*rit)->is_release())
849 if (rit == list->rend()) {
850 /* No write-release in this thread */
851 return true; /* complete */
853 ModelAction *release = *rit;
855 ASSERT(rf->same_thread(release));
858 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
859 if (id_to_int(rf->get_tid()) == (int)i)
861 list = &(*thrd_lists)[i];
863 /* Can we ensure no future writes from this thread may break
864 * the release seq? */
865 bool future_ordered = false;
867 for (rit = list->rbegin(); rit != list->rend(); rit++) {
868 const ModelAction *act = *rit;
869 if (!act->is_write())
871 /* Reach synchronization -> this thread is complete */
872 if (act->happens_before(release))
874 if (rf->happens_before(act)) {
875 future_ordered = true;
879 /* Check modification order */
880 if (mo_graph->checkReachable(rf, act)) {
882 future_ordered = true;
885 if (mo_graph->checkReachable(act, release))
886 /* act --mo--> release */
888 if (mo_graph->checkReachable(release, act) &&
889 mo_graph->checkReachable(act, rf)) {
890 /* release --mo-> act --mo--> rf */
891 return true; /* complete */
896 return false; /* This thread is uncertain */
900 release_heads->push_back(release);
905 * A public interface for getting the release sequence head(s) with which a
906 * given ModelAction must synchronize. This function only returns a non-empty
907 * result when it can locate a release sequence head with certainty. Otherwise,
908 * it may mark the internal state of the ModelChecker so that it will handle
909 * the release sequence at a later time, causing @a act to update its
910 * synchronization at some later point in execution.
911 * @param act The 'acquire' action that may read from a release sequence
912 * @param release_heads A pass-by-reference return parameter. Will be filled
913 * with the head(s) of the release sequence(s), if they exists with certainty.
914 * @see ModelChecker::release_seq_head
916 void ModelChecker::get_release_seq_heads(ModelAction *act,
917 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
919 const ModelAction *rf = act->get_reads_from();
921 complete = release_seq_head(rf, release_heads);
923 /* add act to 'lazy checking' list */
924 std::list<ModelAction *> *list;
925 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
926 list->push_back(act);
932 * Attempt to resolve all stashed operations that might synchronize with a
933 * release sequence for a given location. This implements the "lazy" portion of
934 * determining whether or not a release sequence was contiguous, since not all
935 * modification order information is present at the time an action occurs.
937 * @param location The location/object that should be checked for release
938 * sequence resolutions
939 * @param work_queue The work queue to which to add work items as they are
941 * @return True if any updates occurred (new synchronization, new mo_graph
944 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
946 std::list<ModelAction *> *list;
947 list = lazy_sync_with_release->getptr(location);
951 bool updated = false;
952 std::list<ModelAction *>::iterator it = list->begin();
953 while (it != list->end()) {
954 ModelAction *act = *it;
955 const ModelAction *rf = act->get_reads_from();
956 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
958 complete = release_seq_head(rf, &release_heads);
959 for (unsigned int i = 0; i < release_heads.size(); i++) {
960 if (!act->has_synchronized_with(release_heads[i])) {
962 act->synchronize_with(release_heads[i]);
967 /* Re-check act for mo_graph edges */
968 work_queue->push_back(MOEdgeWorkEntry(act));
970 /* propagate synchronization to later actions */
971 action_list_t::reverse_iterator it = action_trace->rbegin();
972 while ((*it) != act) {
973 ModelAction *propagate = *it;
974 if (act->happens_before(propagate)) {
975 propagate->synchronize_with(act);
976 /* Re-check 'propagate' for mo_graph edges */
977 work_queue->push_back(MOEdgeWorkEntry(propagate));
982 it = list->erase(it);
988 // If we resolved promises or data races, see if we have realized a data race.
989 if (checkDataRaces()) {
997 * Performs various bookkeeping operations for the current ModelAction. For
998 * instance, adds action to the per-object, per-thread action vector and to the
999 * action trace list of all thread actions.
1001 * @param act is the ModelAction to add.
1003 void ModelChecker::add_action_to_lists(ModelAction *act)
1005 int tid = id_to_int(act->get_tid());
1006 action_trace->push_back(act);
1008 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1010 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1011 if (tid >= (int)vec->size())
1012 vec->resize(priv->next_thread_id);
1013 (*vec)[tid].push_back(act);
1015 if ((int)thrd_last_action->size() <= tid)
1016 thrd_last_action->resize(get_num_threads());
1017 (*thrd_last_action)[tid] = act;
1020 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1022 int nthreads = get_num_threads();
1023 if ((int)thrd_last_action->size() < nthreads)
1024 thrd_last_action->resize(nthreads);
1025 return (*thrd_last_action)[id_to_int(tid)];
1029 * Gets the last memory_order_seq_cst action (in the total global sequence)
1030 * performed on a particular object (i.e., memory location).
1031 * @param location The object location to check
1032 * @return The last seq_cst action performed
1034 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1036 action_list_t *list = obj_map->get_safe_ptr(location);
1037 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1038 action_list_t::reverse_iterator rit;
1039 for (rit = list->rbegin(); rit != list->rend(); rit++)
1040 if ((*rit)->is_write() && (*rit)->is_seqcst())
1045 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1047 ModelAction *parent = get_last_action(tid);
1049 parent = get_thread(tid)->get_creation();
1054 * Returns the clock vector for a given thread.
1055 * @param tid The thread whose clock vector we want
1056 * @return Desired clock vector
1058 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1060 return get_parent_action(tid)->get_cv();
1064 * Resolve a set of Promises with a current write. The set is provided in the
1065 * Node corresponding to @a write.
1066 * @param write The ModelAction that is fulfilling Promises
1067 * @return True if promises were resolved; false otherwise
1069 bool ModelChecker::resolve_promises(ModelAction *write)
1071 bool resolved = false;
1073 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1074 Promise *promise = (*promises)[promise_index];
1075 if (write->get_node()->get_promise(i)) {
1076 ModelAction *read = promise->get_action();
1077 read->read_from(write);
1078 if (read->is_rmw()) {
1079 mo_graph->addRMWEdge(write, read);
1081 r_modification_order(read, write);
1082 post_r_modification_order(read, write);
1083 promises->erase(promises->begin() + promise_index);
1092 * Compute the set of promises that could potentially be satisfied by this
1093 * action. Note that the set computation actually appears in the Node, not in
1095 * @param curr The ModelAction that may satisfy promises
1097 void ModelChecker::compute_promises(ModelAction *curr)
1099 for (unsigned int i = 0; i < promises->size(); i++) {
1100 Promise *promise = (*promises)[i];
1101 const ModelAction *act = promise->get_action();
1102 if (!act->happens_before(curr) &&
1104 !act->is_synchronizing(curr) &&
1105 !act->same_thread(curr) &&
1106 promise->get_value() == curr->get_value()) {
1107 curr->get_node()->set_promise(i);
1112 /** Checks promises in response to change in ClockVector Threads. */
1113 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1115 for (unsigned int i = 0; i < promises->size(); i++) {
1116 Promise *promise = (*promises)[i];
1117 const ModelAction *act = promise->get_action();
1118 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1119 merge_cv->synchronized_since(act)) {
1120 //This thread is no longer able to send values back to satisfy the promise
1121 int num_synchronized_threads = promise->increment_threads();
1122 if (num_synchronized_threads == get_num_threads()) {
1123 //Promise has failed
1124 failed_promise = true;
1132 * Build up an initial set of all past writes that this 'read' action may read
1133 * from. This set is determined by the clock vector's "happens before"
1135 * @param curr is the current ModelAction that we are exploring; it must be a
1138 void ModelChecker::build_reads_from_past(ModelAction *curr)
1140 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1142 ASSERT(curr->is_read());
1144 ModelAction *last_seq_cst = NULL;
1146 /* Track whether this object has been initialized */
1147 bool initialized = false;
1149 if (curr->is_seqcst()) {
1150 last_seq_cst = get_last_seq_cst(curr->get_location());
1151 /* We have to at least see the last sequentially consistent write,
1152 so we are initialized. */
1153 if (last_seq_cst != NULL)
1157 /* Iterate over all threads */
1158 for (i = 0; i < thrd_lists->size(); i++) {
1159 /* Iterate over actions in thread, starting from most recent */
1160 action_list_t *list = &(*thrd_lists)[i];
1161 action_list_t::reverse_iterator rit;
1162 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1163 ModelAction *act = *rit;
1165 /* Only consider 'write' actions */
1166 if (!act->is_write())
1169 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1170 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1171 DEBUG("Adding action to may_read_from:\n");
1172 if (DBG_ENABLED()) {
1176 curr->get_node()->add_read_from(act);
1179 /* Include at most one act per-thread that "happens before" curr */
1180 if (act->happens_before(curr)) {
1188 /** @todo Need a more informative way of reporting errors. */
1189 printf("ERROR: may read from uninitialized atomic\n");
1192 if (DBG_ENABLED() || !initialized) {
1193 printf("Reached read action:\n");
1195 printf("Printing may_read_from\n");
1196 curr->get_node()->print_may_read_from();
1197 printf("End printing may_read_from\n");
1200 ASSERT(initialized);
1203 static void print_list(action_list_t *list)
1205 action_list_t::iterator it;
1207 printf("---------------------------------------------------------------------\n");
1210 for (it = list->begin(); it != list->end(); it++) {
1213 printf("---------------------------------------------------------------------\n");
1216 void ModelChecker::print_summary()
1219 printf("Number of executions: %d\n", num_executions);
1220 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1224 if (!isfinalfeasible())
1225 printf("INFEASIBLE EXECUTION!\n");
1226 print_list(action_trace);
1231 * Add a Thread to the system for the first time. Should only be called once
1233 * @param t The Thread to add
1235 void ModelChecker::add_thread(Thread *t)
1237 thread_map->put(id_to_int(t->get_id()), t);
1238 scheduler->add_thread(t);
1241 void ModelChecker::remove_thread(Thread *t)
1243 scheduler->remove_thread(t);
1247 * Switch from a user-context to the "master thread" context (a.k.a. system
1248 * context). This switch is made with the intention of exploring a particular
1249 * model-checking action (described by a ModelAction object). Must be called
1250 * from a user-thread context.
1251 * @param act The current action that will be explored. Must not be NULL.
1252 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1254 int ModelChecker::switch_to_master(ModelAction *act)
1257 Thread *old = thread_current();
1258 set_current_action(act);
1259 old->set_state(THREAD_READY);
1260 return Thread::swap(old, &system_context);
1264 * Takes the next step in the execution, if possible.
1265 * @return Returns true (success) if a step was taken and false otherwise.
1267 bool ModelChecker::take_step() {
1268 Thread *curr, *next;
1273 curr = thread_current();
1275 if (curr->get_state() == THREAD_READY) {
1276 ASSERT(priv->current_action);
1278 priv->nextThread = check_current_action(priv->current_action);
1279 priv->current_action = NULL;
1280 if (!curr->is_blocked() && !curr->is_complete())
1281 scheduler->add_thread(curr);
1286 next = scheduler->next_thread(priv->nextThread);
1288 /* Infeasible -> don't take any more steps */
1293 next->set_state(THREAD_RUNNING);
1294 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1296 /* next == NULL -> don't take any more steps */
1299 /* Return false only if swap fails with an error */
1300 return (Thread::swap(&system_context, next) == 0);
1303 /** Runs the current execution until threre are no more steps to take. */
1304 void ModelChecker::finish_execution() {
1307 while (take_step());