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()),
24 num_feasible_executions(0),
27 action_trace(new action_list_t()),
28 thread_map(new HashTable<int, Thread *, int>()),
29 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
30 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
31 promises(new std::vector<Promise *>()),
32 futurevalues(new std::vector<struct PendingFutureValue>()),
33 lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
34 thrd_last_action(new std::vector<ModelAction *>(1)),
35 node_stack(new NodeStack()),
36 mo_graph(new CycleGraph()),
37 failed_promise(false),
38 too_many_reads(false),
41 /* Allocate this "size" on the snapshotting heap */
42 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
43 /* First thread created will have id INITIAL_THREAD_ID */
44 priv->next_thread_id = INITIAL_THREAD_ID;
46 lazy_sync_size = &priv->lazy_sync_size;
49 /** @brief Destructor */
50 ModelChecker::~ModelChecker()
52 for (int i = 0; i < get_num_threads(); i++)
53 delete thread_map->get(i);
60 for (unsigned int i = 0; i < promises->size(); i++)
61 delete (*promises)[i];
64 delete lazy_sync_with_release;
66 delete thrd_last_action;
73 * Restores user program to initial state and resets all model-checker data
76 void ModelChecker::reset_to_initial_state()
78 DEBUG("+++ Resetting to initial state +++\n");
79 node_stack->reset_execution();
80 failed_promise = false;
81 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()
178 if (isfinalfeasible())
179 num_feasible_executions++;
181 if (isfinalfeasible() || DBG_ENABLED())
184 if ((diverge = get_next_backtrack()) == NULL)
188 printf("Next execution will diverge at:\n");
192 reset_to_initial_state();
196 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
198 action_type type = act->get_type();
208 /* linear search: from most recent to oldest */
209 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
210 action_list_t::reverse_iterator rit;
211 for (rit = list->rbegin(); rit != list->rend(); rit++) {
212 ModelAction *prev = *rit;
213 if (act->is_synchronizing(prev))
219 void ModelChecker::set_backtracking(ModelAction *act)
223 Thread *t = get_thread(act);
225 prev = get_last_conflict(act);
229 node = prev->get_node()->get_parent();
231 while (!node->is_enabled(t))
234 /* Check if this has been explored already */
235 if (node->has_been_explored(t->get_id()))
238 /* Cache the latest backtracking point */
239 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
240 priv->next_backtrack = prev;
242 /* If this is a new backtracking point, mark the tree */
243 if (!node->set_backtrack(t->get_id()))
245 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
246 prev->get_tid(), t->get_id());
254 * Returns last backtracking point. The model checker will explore a different
255 * path for this point in the next execution.
256 * @return The ModelAction at which the next execution should diverge.
258 ModelAction * ModelChecker::get_next_backtrack()
260 ModelAction *next = priv->next_backtrack;
261 priv->next_backtrack = NULL;
266 * Processes a read or rmw model action.
267 * @param curr is the read model action to process.
268 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
269 * @return True if processing this read updates the mo_graph.
271 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
274 bool updated = false;
276 const ModelAction *reads_from = curr->get_node()->get_read_from();
277 if (reads_from != NULL) {
278 mo_graph->startChanges();
280 value = reads_from->get_value();
281 bool r_status = false;
283 if (!second_part_of_rmw) {
284 check_recency(curr,false);
285 r_status = r_modification_order(curr, reads_from);
289 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
290 mo_graph->rollbackChanges();
291 too_many_reads = false;
295 curr->read_from(reads_from);
296 mo_graph->commitChanges();
298 } else if (!second_part_of_rmw) {
299 /* Read from future value */
300 value = curr->get_node()->get_future_value();
301 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
302 curr->read_from(NULL);
303 Promise *valuepromise = new Promise(curr, value, expiration);
304 promises->push_back(valuepromise);
306 get_thread(curr)->set_return_value(value);
312 * Process a write ModelAction
313 * @param curr The ModelAction to process
314 * @return True if the mo_graph was updated or promises were resolved
316 bool ModelChecker::process_write(ModelAction *curr)
318 bool updated_mod_order = w_modification_order(curr);
319 bool updated_promises = resolve_promises(curr);
321 if (promises->size() == 0) {
322 for (unsigned int i = 0; i<futurevalues->size(); i++) {
323 struct PendingFutureValue pfv = (*futurevalues)[i];
324 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
325 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
326 priv->next_backtrack = pfv.act;
328 futurevalues->resize(0);
331 mo_graph->commitChanges();
332 get_thread(curr)->set_return_value(VALUE_NONE);
333 return updated_mod_order || updated_promises;
337 * This is the heart of the model checker routine. It performs model-checking
338 * actions corresponding to a given "current action." Among other processes, it
339 * calculates reads-from relationships, updates synchronization clock vectors,
340 * forms a memory_order constraints graph, and handles replay/backtrack
341 * execution when running permutations of previously-observed executions.
343 * @param curr The current action to process
344 * @return The next Thread that must be executed. May be NULL if ModelChecker
345 * makes no choice (e.g., according to replay execution, combining RMW actions,
348 Thread * ModelChecker::check_current_action(ModelAction *curr)
350 bool second_part_of_rmw = false;
354 if (curr->is_rmwc() || curr->is_rmw()) {
355 ModelAction *tmp = process_rmw(curr);
356 second_part_of_rmw = true;
359 compute_promises(curr);
361 ModelAction *tmp = node_stack->explore_action(curr);
363 /* Discard duplicate ModelAction; use action from NodeStack */
364 /* First restore type and order in case of RMW operation */
366 tmp->copy_typeandorder(curr);
368 /* If we have diverged, we need to reset the clock vector. */
370 tmp->create_cv(get_parent_action(tmp->get_tid()));
376 * Perform one-time actions when pushing new ModelAction onto
379 curr->create_cv(get_parent_action(curr->get_tid()));
380 /* Build may_read_from set */
382 build_reads_from_past(curr);
383 if (curr->is_write())
384 compute_promises(curr);
388 /* Thread specific actions */
389 switch (curr->get_type()) {
390 case THREAD_CREATE: {
391 Thread *th = (Thread *)curr->get_location();
392 th->set_creation(curr);
396 Thread *waiting, *blocking;
397 waiting = get_thread(curr);
398 blocking = (Thread *)curr->get_location();
399 if (!blocking->is_complete()) {
400 blocking->push_wait_list(curr);
401 scheduler->sleep(waiting);
405 case THREAD_FINISH: {
406 Thread *th = get_thread(curr);
407 while (!th->wait_list_empty()) {
408 ModelAction *act = th->pop_wait_list();
409 Thread *wake = get_thread(act);
410 scheduler->wake(wake);
416 check_promises(NULL, curr->get_cv());
423 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
425 while (!work_queue.empty()) {
426 WorkQueueEntry work = work_queue.front();
427 work_queue.pop_front();
430 case WORK_CHECK_CURR_ACTION: {
431 ModelAction *act = work.action;
432 bool updated = false;
433 if (act->is_read() && process_read(act, second_part_of_rmw))
436 if (act->is_write() && process_write(act))
440 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
443 case WORK_CHECK_RELEASE_SEQ:
444 resolve_release_sequences(work.location, &work_queue);
446 case WORK_CHECK_MO_EDGES:
447 /** @todo Perform follow-up mo_graph checks */
454 /* Add action to list. */
455 if (!second_part_of_rmw)
456 add_action_to_lists(curr);
458 check_curr_backtracking(curr);
460 set_backtracking(curr);
462 return get_next_thread(curr);
465 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
466 Node *currnode = curr->get_node();
467 Node *parnode = currnode->get_parent();
469 if ((!parnode->backtrack_empty() ||
470 !currnode->read_from_empty() ||
471 !currnode->future_value_empty() ||
472 !currnode->promise_empty())
473 && (!priv->next_backtrack ||
474 *curr > *priv->next_backtrack)) {
475 priv->next_backtrack = curr;
479 bool ModelChecker::promises_expired() {
480 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
481 Promise *promise = (*promises)[promise_index];
482 if (promise->get_expiration()<priv->used_sequence_numbers) {
489 /** @returns whether the current partial trace must be a prefix of a
491 bool ModelChecker::isfeasibleprefix() {
492 return promises->size() == 0 && *lazy_sync_size == 0;
495 /** @returns whether the current partial trace is feasible. */
496 bool ModelChecker::isfeasible() {
497 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
500 /** @returns whether the current partial trace is feasible other than
501 * multiple RMW reading from the same store. */
502 bool ModelChecker::isfeasibleotherthanRMW() {
503 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
506 /** Returns whether the current completed trace is feasible. */
507 bool ModelChecker::isfinalfeasible() {
508 return isfeasible() && promises->size() == 0;
511 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
512 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
513 int tid = id_to_int(act->get_tid());
514 ModelAction *lastread = get_last_action(tid);
515 lastread->process_rmw(act);
516 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
517 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
518 mo_graph->commitChanges();
524 * Checks whether a thread has read from the same write for too many times
525 * without seeing the effects of a later write.
528 * 1) there must a different write that we could read from that would satisfy the modification order,
529 * 2) we must have read from the same value in excess of maxreads times, and
530 * 3) that other write must have been in the reads_from set for maxreads times.
532 * If so, we decide that the execution is no longer feasible.
534 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
535 if (params.maxreads != 0) {
536 if (curr->get_node()->get_read_from_size() <= 1)
539 //Must make sure that execution is currently feasible... We could
540 //accidentally clear by rolling back
544 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
545 int tid = id_to_int(curr->get_tid());
548 if ((int)thrd_lists->size() <= tid)
551 action_list_t *list = &(*thrd_lists)[tid];
553 action_list_t::reverse_iterator rit = list->rbegin();
556 for (; (*rit) != curr; rit++)
558 /* go past curr now */
562 action_list_t::reverse_iterator ritcopy = rit;
563 //See if we have enough reads from the same value
565 for (; count < params.maxreads; rit++,count++) {
566 if (rit==list->rend())
568 ModelAction *act = *rit;
571 if (act->get_reads_from() != curr->get_reads_from())
573 if (act->get_node()->get_read_from_size() <= 1)
577 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
579 const ModelAction * write = curr->get_node()->get_read_from_at(i);
580 //Need a different write
581 if (write==curr->get_reads_from())
584 /* Test to see whether this is a feasible write to read from*/
585 mo_graph->startChanges();
586 r_modification_order(curr, write);
587 bool feasiblereadfrom = isfeasible();
588 mo_graph->rollbackChanges();
590 if (!feasiblereadfrom)
594 bool feasiblewrite = true;
595 //new we need to see if this write works for everyone
597 for (int loop = count; loop>0; loop--,rit++) {
598 ModelAction *act=*rit;
599 bool foundvalue = false;
600 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
601 if (act->get_node()->get_read_from_at(i)==write) {
607 feasiblewrite = false;
612 too_many_reads = true;
620 * Updates the mo_graph with the constraints imposed from the current
623 * Basic idea is the following: Go through each other thread and find
624 * the lastest action that happened before our read. Two cases:
626 * (1) The action is a write => that write must either occur before
627 * the write we read from or be the write we read from.
629 * (2) The action is a read => the write that that action read from
630 * must occur before the write we read from or be the same write.
632 * @param curr The current action. Must be a read.
633 * @param rf The action that curr reads from. Must be a write.
634 * @return True if modification order edges were added; false otherwise
636 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
638 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
641 ASSERT(curr->is_read());
643 /* Iterate over all threads */
644 for (i = 0; i < thrd_lists->size(); i++) {
645 /* Iterate over actions in thread, starting from most recent */
646 action_list_t *list = &(*thrd_lists)[i];
647 action_list_t::reverse_iterator rit;
648 for (rit = list->rbegin(); rit != list->rend(); rit++) {
649 ModelAction *act = *rit;
651 /* Include at most one act per-thread that "happens before" curr */
652 if (act->happens_before(curr)) {
653 if (act->is_write()) {
654 if (rf != act && act != curr) {
655 mo_graph->addEdge(act, rf);
659 const ModelAction *prevreadfrom = act->get_reads_from();
660 if (prevreadfrom != NULL && rf != prevreadfrom) {
661 mo_graph->addEdge(prevreadfrom, rf);
674 /** This method fixes up the modification order when we resolve a
675 * promises. The basic problem is that actions that occur after the
676 * read curr could not property add items to the modification order
679 * So for each thread, we find the earliest item that happens after
680 * the read curr. This is the item we have to fix up with additional
681 * constraints. If that action is write, we add a MO edge between
682 * the Action rf and that action. If the action is a read, we add a
683 * MO edge between the Action rf, and whatever the read accessed.
685 * @param curr is the read ModelAction that we are fixing up MO edges for.
686 * @param rf is the write ModelAction that curr reads from.
690 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
692 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
694 ASSERT(curr->is_read());
696 /* Iterate over all threads */
697 for (i = 0; i < thrd_lists->size(); i++) {
698 /* Iterate over actions in thread, starting from most recent */
699 action_list_t *list = &(*thrd_lists)[i];
700 action_list_t::reverse_iterator rit;
701 ModelAction *lastact = NULL;
703 /* Find last action that happens after curr */
704 for (rit = list->rbegin(); rit != list->rend(); rit++) {
705 ModelAction *act = *rit;
706 if (curr->happens_before(act)) {
712 /* Include at most one act per-thread that "happens before" curr */
713 if (lastact != NULL) {
714 if (lastact->is_read()) {
715 const ModelAction *postreadfrom = lastact->get_reads_from();
716 if (postreadfrom != NULL&&rf != postreadfrom)
717 mo_graph->addEdge(rf, postreadfrom);
718 } else if (rf != lastact) {
719 mo_graph->addEdge(rf, lastact);
727 * Updates the mo_graph with the constraints imposed from the current write.
729 * Basic idea is the following: Go through each other thread and find
730 * the lastest action that happened before our write. Two cases:
732 * (1) The action is a write => that write must occur before
735 * (2) The action is a read => the write that that action read from
736 * must occur before the current write.
738 * This method also handles two other issues:
740 * (I) Sequential Consistency: Making sure that if the current write is
741 * seq_cst, that it occurs after the previous seq_cst write.
743 * (II) Sending the write back to non-synchronizing reads.
745 * @param curr The current action. Must be a write.
746 * @return True if modification order edges were added; false otherwise
748 bool ModelChecker::w_modification_order(ModelAction *curr)
750 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
753 ASSERT(curr->is_write());
755 if (curr->is_seqcst()) {
756 /* We have to at least see the last sequentially consistent write,
757 so we are initialized. */
758 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
759 if (last_seq_cst != NULL) {
760 mo_graph->addEdge(last_seq_cst, curr);
765 /* Iterate over all threads */
766 for (i = 0; i < thrd_lists->size(); i++) {
767 /* Iterate over actions in thread, starting from most recent */
768 action_list_t *list = &(*thrd_lists)[i];
769 action_list_t::reverse_iterator rit;
770 for (rit = list->rbegin(); rit != list->rend(); rit++) {
771 ModelAction *act = *rit;
773 /* Include at most one act per-thread that "happens before" curr */
774 if (act->happens_before(curr)) {
776 * Note: if act is RMW, just add edge:
778 * The following edge should be handled elsewhere:
779 * readfrom(act) --mo--> act
781 if (act->is_write()) {
782 //RMW shouldn't have an edge to themselves
784 mo_graph->addEdge(act, curr);
785 } else if (act->is_read() && act->get_reads_from() != NULL)
786 mo_graph->addEdge(act->get_reads_from(), curr);
789 } else if (act->is_read() && !act->is_synchronizing(curr) &&
790 !act->same_thread(curr)) {
791 /* We have an action that:
792 (1) did not happen before us
793 (2) is a read and we are a write
794 (3) cannot synchronize with us
795 (4) is in a different thread
797 that read could potentially read from our write.
799 if (thin_air_constraint_may_allow(curr, act)) {
801 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
802 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
803 futurevalues->push_back(pfv);
813 /** Arbitrary reads from the future are not allowed. Section 29.3
814 * part 9 places some constraints. This method checks one result of constraint
815 * constraint. Others require compiler support. */
817 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
818 if (!writer->is_rmw())
821 if (!reader->is_rmw())
824 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
827 if (search->get_tid() == reader->get_tid() &&
828 search->happens_before(reader))
836 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
837 * The ModelAction under consideration is expected to be taking part in
838 * release/acquire synchronization as an object of the "reads from" relation.
839 * Note that this can only provide release sequence support for RMW chains
840 * which do not read from the future, as those actions cannot be traced until
841 * their "promise" is fulfilled. Similarly, we may not even establish the
842 * presence of a release sequence with certainty, as some modification order
843 * constraints may be decided further in the future. Thus, this function
844 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
845 * and a boolean representing certainty.
847 * @todo Finish lazy updating, when promises are fulfilled in the future
848 * @param rf The action that might be part of a release sequence. Must be a
850 * @param release_heads A pass-by-reference style return parameter. After
851 * execution of this function, release_heads will contain the heads of all the
852 * relevant release sequences, if any exists
853 * @return true, if the ModelChecker is certain that release_heads is complete;
856 bool ModelChecker::release_seq_head(const ModelAction *rf,
857 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
860 /* read from future: need to settle this later */
861 return false; /* incomplete */
864 ASSERT(rf->is_write());
866 if (rf->is_release())
867 release_heads->push_back(rf);
869 /* We need a RMW action that is both an acquire and release to stop */
870 /** @todo Need to be smarter here... In the linux lock
871 * example, this will run to the beginning of the program for
873 if (rf->is_acquire() && rf->is_release())
874 return true; /* complete */
875 return release_seq_head(rf->get_reads_from(), release_heads);
877 if (rf->is_release())
878 return true; /* complete */
880 /* else relaxed write; check modification order for contiguous subsequence
881 * -> rf must be same thread as release */
882 int tid = id_to_int(rf->get_tid());
883 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
884 action_list_t *list = &(*thrd_lists)[tid];
885 action_list_t::const_reverse_iterator rit;
887 /* Find rf in the thread list */
888 rit = std::find(list->rbegin(), list->rend(), rf);
889 ASSERT(rit != list->rend());
891 /* Find the last write/release */
892 for (; rit != list->rend(); rit++)
893 if ((*rit)->is_release())
895 if (rit == list->rend()) {
896 /* No write-release in this thread */
897 return true; /* complete */
899 ModelAction *release = *rit;
901 ASSERT(rf->same_thread(release));
904 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
905 if (id_to_int(rf->get_tid()) == (int)i)
907 list = &(*thrd_lists)[i];
909 /* Can we ensure no future writes from this thread may break
910 * the release seq? */
911 bool future_ordered = false;
913 for (rit = list->rbegin(); rit != list->rend(); rit++) {
914 const ModelAction *act = *rit;
915 if (!act->is_write())
917 /* Reach synchronization -> this thread is complete */
918 if (act->happens_before(release))
920 if (rf->happens_before(act)) {
921 future_ordered = true;
925 /* Check modification order */
926 if (mo_graph->checkReachable(rf, act)) {
928 future_ordered = true;
931 if (mo_graph->checkReachable(act, release))
932 /* act --mo--> release */
934 if (mo_graph->checkReachable(release, act) &&
935 mo_graph->checkReachable(act, rf)) {
936 /* release --mo-> act --mo--> rf */
937 return true; /* complete */
942 return false; /* This thread is uncertain */
946 release_heads->push_back(release);
951 * A public interface for getting the release sequence head(s) with which a
952 * given ModelAction must synchronize. This function only returns a non-empty
953 * result when it can locate a release sequence head with certainty. Otherwise,
954 * it may mark the internal state of the ModelChecker so that it will handle
955 * the release sequence at a later time, causing @a act to update its
956 * synchronization at some later point in execution.
957 * @param act The 'acquire' action that may read from a release sequence
958 * @param release_heads A pass-by-reference return parameter. Will be filled
959 * with the head(s) of the release sequence(s), if they exists with certainty.
960 * @see ModelChecker::release_seq_head
962 void ModelChecker::get_release_seq_heads(ModelAction *act,
963 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
965 const ModelAction *rf = act->get_reads_from();
967 complete = release_seq_head(rf, release_heads);
969 /* add act to 'lazy checking' list */
970 std::list<ModelAction *> *list;
971 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
972 list->push_back(act);
978 * Attempt to resolve all stashed operations that might synchronize with a
979 * release sequence for a given location. This implements the "lazy" portion of
980 * determining whether or not a release sequence was contiguous, since not all
981 * modification order information is present at the time an action occurs.
983 * @param location The location/object that should be checked for release
984 * sequence resolutions
985 * @param work_queue The work queue to which to add work items as they are
987 * @return True if any updates occurred (new synchronization, new mo_graph
990 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
992 std::list<ModelAction *> *list;
993 list = lazy_sync_with_release->getptr(location);
997 bool updated = false;
998 std::list<ModelAction *>::iterator it = list->begin();
999 while (it != list->end()) {
1000 ModelAction *act = *it;
1001 const ModelAction *rf = act->get_reads_from();
1002 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
1004 complete = release_seq_head(rf, &release_heads);
1005 for (unsigned int i = 0; i < release_heads.size(); i++) {
1006 if (!act->has_synchronized_with(release_heads[i])) {
1008 act->synchronize_with(release_heads[i]);
1013 /* Re-check act for mo_graph edges */
1014 work_queue->push_back(MOEdgeWorkEntry(act));
1016 /* propagate synchronization to later actions */
1017 action_list_t::reverse_iterator it = action_trace->rbegin();
1018 while ((*it) != act) {
1019 ModelAction *propagate = *it;
1020 if (act->happens_before(propagate)) {
1021 propagate->synchronize_with(act);
1022 /* Re-check 'propagate' for mo_graph edges */
1023 work_queue->push_back(MOEdgeWorkEntry(propagate));
1028 it = list->erase(it);
1029 (*lazy_sync_size)--;
1034 // If we resolved promises or data races, see if we have realized a data race.
1035 if (checkDataRaces()) {
1043 * Performs various bookkeeping operations for the current ModelAction. For
1044 * instance, adds action to the per-object, per-thread action vector and to the
1045 * action trace list of all thread actions.
1047 * @param act is the ModelAction to add.
1049 void ModelChecker::add_action_to_lists(ModelAction *act)
1051 int tid = id_to_int(act->get_tid());
1052 action_trace->push_back(act);
1054 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1056 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1057 if (tid >= (int)vec->size())
1058 vec->resize(priv->next_thread_id);
1059 (*vec)[tid].push_back(act);
1061 if ((int)thrd_last_action->size() <= tid)
1062 thrd_last_action->resize(get_num_threads());
1063 (*thrd_last_action)[tid] = act;
1066 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1068 int nthreads = get_num_threads();
1069 if ((int)thrd_last_action->size() < nthreads)
1070 thrd_last_action->resize(nthreads);
1071 return (*thrd_last_action)[id_to_int(tid)];
1075 * Gets the last memory_order_seq_cst action (in the total global sequence)
1076 * performed on a particular object (i.e., memory location).
1077 * @param location The object location to check
1078 * @return The last seq_cst action performed
1080 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1082 action_list_t *list = obj_map->get_safe_ptr(location);
1083 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1084 action_list_t::reverse_iterator rit;
1085 for (rit = list->rbegin(); rit != list->rend(); rit++)
1086 if ((*rit)->is_write() && (*rit)->is_seqcst())
1091 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1093 ModelAction *parent = get_last_action(tid);
1095 parent = get_thread(tid)->get_creation();
1100 * Returns the clock vector for a given thread.
1101 * @param tid The thread whose clock vector we want
1102 * @return Desired clock vector
1104 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1106 return get_parent_action(tid)->get_cv();
1110 * Resolve a set of Promises with a current write. The set is provided in the
1111 * Node corresponding to @a write.
1112 * @param write The ModelAction that is fulfilling Promises
1113 * @return True if promises were resolved; false otherwise
1115 bool ModelChecker::resolve_promises(ModelAction *write)
1117 bool resolved = false;
1119 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1120 Promise *promise = (*promises)[promise_index];
1121 if (write->get_node()->get_promise(i)) {
1122 ModelAction *read = promise->get_action();
1123 read->read_from(write);
1124 if (read->is_rmw()) {
1125 mo_graph->addRMWEdge(write, read);
1127 //First fix up the modification order for actions that happened
1129 r_modification_order(read, write);
1130 //Next fix up the modification order for actions that happened
1132 post_r_modification_order(read, write);
1133 promises->erase(promises->begin() + promise_index);
1142 * Compute the set of promises that could potentially be satisfied by this
1143 * action. Note that the set computation actually appears in the Node, not in
1145 * @param curr The ModelAction that may satisfy promises
1147 void ModelChecker::compute_promises(ModelAction *curr)
1149 for (unsigned int i = 0; i < promises->size(); i++) {
1150 Promise *promise = (*promises)[i];
1151 const ModelAction *act = promise->get_action();
1152 if (!act->happens_before(curr) &&
1154 !act->is_synchronizing(curr) &&
1155 !act->same_thread(curr) &&
1156 promise->get_value() == curr->get_value()) {
1157 curr->get_node()->set_promise(i);
1162 /** Checks promises in response to change in ClockVector Threads. */
1163 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1165 for (unsigned int i = 0; i < promises->size(); i++) {
1166 Promise *promise = (*promises)[i];
1167 const ModelAction *act = promise->get_action();
1168 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1169 merge_cv->synchronized_since(act)) {
1170 //This thread is no longer able to send values back to satisfy the promise
1171 int num_synchronized_threads = promise->increment_threads();
1172 if (num_synchronized_threads == get_num_threads()) {
1173 //Promise has failed
1174 failed_promise = true;
1182 * Build up an initial set of all past writes that this 'read' action may read
1183 * from. This set is determined by the clock vector's "happens before"
1185 * @param curr is the current ModelAction that we are exploring; it must be a
1188 void ModelChecker::build_reads_from_past(ModelAction *curr)
1190 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1192 ASSERT(curr->is_read());
1194 ModelAction *last_seq_cst = NULL;
1196 /* Track whether this object has been initialized */
1197 bool initialized = false;
1199 if (curr->is_seqcst()) {
1200 last_seq_cst = get_last_seq_cst(curr->get_location());
1201 /* We have to at least see the last sequentially consistent write,
1202 so we are initialized. */
1203 if (last_seq_cst != NULL)
1207 /* Iterate over all threads */
1208 for (i = 0; i < thrd_lists->size(); i++) {
1209 /* Iterate over actions in thread, starting from most recent */
1210 action_list_t *list = &(*thrd_lists)[i];
1211 action_list_t::reverse_iterator rit;
1212 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1213 ModelAction *act = *rit;
1215 /* Only consider 'write' actions */
1216 if (!act->is_write())
1219 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1220 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1221 DEBUG("Adding action to may_read_from:\n");
1222 if (DBG_ENABLED()) {
1226 curr->get_node()->add_read_from(act);
1229 /* Include at most one act per-thread that "happens before" curr */
1230 if (act->happens_before(curr)) {
1238 /** @todo Need a more informative way of reporting errors. */
1239 printf("ERROR: may read from uninitialized atomic\n");
1242 if (DBG_ENABLED() || !initialized) {
1243 printf("Reached read action:\n");
1245 printf("Printing may_read_from\n");
1246 curr->get_node()->print_may_read_from();
1247 printf("End printing may_read_from\n");
1250 ASSERT(initialized);
1253 static void print_list(action_list_t *list)
1255 action_list_t::iterator it;
1257 printf("---------------------------------------------------------------------\n");
1260 for (it = list->begin(); it != list->end(); it++) {
1263 printf("---------------------------------------------------------------------\n");
1266 void ModelChecker::print_summary()
1269 printf("Number of executions: %d\n", num_executions);
1270 printf("Number of feasible executions: %d\n", num_feasible_executions);
1271 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1273 #if SUPPORT_MOD_ORDER_DUMP
1275 char buffername[100];
1276 sprintf(buffername, "exec%u",num_executions);
1277 mo_graph->dumpGraphToFile(buffername);
1280 if (!isfinalfeasible())
1281 printf("INFEASIBLE EXECUTION!\n");
1282 print_list(action_trace);
1287 * Add a Thread to the system for the first time. Should only be called once
1289 * @param t The Thread to add
1291 void ModelChecker::add_thread(Thread *t)
1293 thread_map->put(id_to_int(t->get_id()), t);
1294 scheduler->add_thread(t);
1297 void ModelChecker::remove_thread(Thread *t)
1299 scheduler->remove_thread(t);
1303 * Switch from a user-context to the "master thread" context (a.k.a. system
1304 * context). This switch is made with the intention of exploring a particular
1305 * model-checking action (described by a ModelAction object). Must be called
1306 * from a user-thread context.
1307 * @param act The current action that will be explored. Must not be NULL.
1308 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1310 int ModelChecker::switch_to_master(ModelAction *act)
1313 Thread *old = thread_current();
1314 set_current_action(act);
1315 old->set_state(THREAD_READY);
1316 return Thread::swap(old, &system_context);
1320 * Takes the next step in the execution, if possible.
1321 * @return Returns true (success) if a step was taken and false otherwise.
1323 bool ModelChecker::take_step() {
1324 Thread *curr, *next;
1329 curr = thread_current();
1331 if (curr->get_state() == THREAD_READY) {
1332 ASSERT(priv->current_action);
1334 priv->nextThread = check_current_action(priv->current_action);
1335 priv->current_action = NULL;
1336 if (!curr->is_blocked() && !curr->is_complete())
1337 scheduler->add_thread(curr);
1342 next = scheduler->next_thread(priv->nextThread);
1344 /* Infeasible -> don't take any more steps */
1349 next->set_state(THREAD_RUNNING);
1350 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1352 /* next == NULL -> don't take any more steps */
1355 /* Return false only if swap fails with an error */
1356 return (Thread::swap(&system_context, next) == 0);
1359 /** Runs the current execution until threre are no more steps to take. */
1360 void ModelChecker::finish_execution() {
1363 while (take_step());