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()),
37 mo_graph(new CycleGraph()),
38 failed_promise(false),
39 too_many_reads(false),
42 /* Allocate this "size" on the snapshotting heap */
43 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
44 /* First thread created will have id INITIAL_THREAD_ID */
45 priv->next_thread_id = INITIAL_THREAD_ID;
47 lazy_sync_size = &priv->lazy_sync_size;
50 /** @brief Destructor */
51 ModelChecker::~ModelChecker()
53 for (int i = 0; i < get_num_threads(); i++)
54 delete thread_map->get(i);
63 for (unsigned int i = 0; i < promises->size(); i++)
64 delete (*promises)[i];
67 delete lazy_sync_with_release;
69 delete thrd_last_action;
76 * Restores user program to initial state and resets all model-checker data
79 void ModelChecker::reset_to_initial_state()
81 DEBUG("+++ Resetting to initial state +++\n");
82 node_stack->reset_execution();
83 failed_promise = false;
84 too_many_reads = false;
86 snapshotObject->backTrackBeforeStep(0);
89 /** @returns a thread ID for a new Thread */
90 thread_id_t ModelChecker::get_next_id()
92 thread_id_t newid=priv->next_thread_id++;
93 bool * tmp=(bool *) malloc((newid+1)*sizeof(bool));
94 memcpy(tmp, is_enabled, newid*sizeof(bool));
101 /** @returns the number of user threads created during this execution */
102 int ModelChecker::get_num_threads()
104 return priv->next_thread_id;
107 /** @returns a sequence number for a new ModelAction */
108 modelclock_t ModelChecker::get_next_seq_num()
110 return ++priv->used_sequence_numbers;
114 * @brief Choose the next thread to execute.
116 * This function chooses the next thread that should execute. It can force the
117 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
118 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
119 * The model-checker may have no preference regarding the next thread (i.e.,
120 * when exploring a new execution ordering), in which case this will return
122 * @param curr The current ModelAction. This action might guide the choice of
124 * @return The next thread to run. If the model-checker has no preference, NULL.
126 Thread * ModelChecker::get_next_thread(ModelAction *curr)
130 /* Do not split atomic actions. */
132 return thread_current();
133 /* The THREAD_CREATE action points to the created Thread */
134 else if (curr->get_type() == THREAD_CREATE)
135 return (Thread *)curr->get_location();
137 /* Have we completed exploring the preselected path? */
141 /* Else, we are trying to replay an execution */
142 ModelAction *next = node_stack->get_next()->get_action();
144 if (next == diverge) {
145 Node *nextnode = next->get_node();
146 /* Reached divergence point */
147 if (nextnode->increment_promise()) {
148 /* The next node will try to satisfy a different set of promises. */
149 tid = next->get_tid();
150 node_stack->pop_restofstack(2);
151 } else if (nextnode->increment_read_from()) {
152 /* The next node will read from a different value. */
153 tid = next->get_tid();
154 node_stack->pop_restofstack(2);
155 } else if (nextnode->increment_future_value()) {
156 /* The next node will try to read from a different future value. */
157 tid = next->get_tid();
158 node_stack->pop_restofstack(2);
160 /* Make a different thread execute for next step */
161 Node *node = nextnode->get_parent();
162 tid = node->get_next_backtrack();
163 node_stack->pop_restofstack(1);
165 DEBUG("*** Divergence point ***\n");
168 tid = next->get_tid();
170 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
171 ASSERT(tid != THREAD_ID_T_NONE);
172 return thread_map->get(id_to_int(tid));
176 * Queries the model-checker for more executions to explore and, if one
177 * exists, resets the model-checker state to execute a new execution.
179 * @return If there are more executions to explore, return true. Otherwise,
182 bool ModelChecker::next_execution()
187 if (isfinalfeasible())
188 num_feasible_executions++;
190 if (isfinalfeasible() || DBG_ENABLED())
193 if ((diverge = get_next_backtrack()) == NULL)
197 printf("Next execution will diverge at:\n");
201 reset_to_initial_state();
205 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
207 action_type type = act->get_type();
209 if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
210 /* linear search: from most recent to oldest */
211 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
212 action_list_t::reverse_iterator rit;
213 for (rit = list->rbegin(); rit != list->rend(); rit++) {
214 ModelAction *prev = *rit;
215 if (act->is_synchronizing(prev))
218 } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
219 /* linear search: from most recent to oldest */
220 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
221 action_list_t::reverse_iterator rit;
222 for (rit = list->rbegin(); rit != list->rend(); rit++) {
223 ModelAction *prev = *rit;
224 if (prev->is_success_lock())
227 } else if (type==ATOMIC_UNLOCK) {
228 /* linear search: from most recent to oldest */
229 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
230 action_list_t::reverse_iterator rit;
231 for (rit = list->rbegin(); rit != list->rend(); rit++) {
232 ModelAction *prev = *rit;
233 if (prev->is_failed_trylock())
240 void ModelChecker::set_backtracking(ModelAction *act)
244 Thread *t = get_thread(act);
246 prev = get_last_conflict(act);
250 node = prev->get_node()->get_parent();
252 while (!node->is_enabled(t))
255 /* Check if this has been explored already */
256 if (node->has_been_explored(t->get_id()))
259 /* Cache the latest backtracking point */
260 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
261 priv->next_backtrack = prev;
263 /* If this is a new backtracking point, mark the tree */
264 if (!node->set_backtrack(t->get_id()))
266 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
267 prev->get_tid(), t->get_id());
275 * Returns last backtracking point. The model checker will explore a different
276 * path for this point in the next execution.
277 * @return The ModelAction at which the next execution should diverge.
279 ModelAction * ModelChecker::get_next_backtrack()
281 ModelAction *next = priv->next_backtrack;
282 priv->next_backtrack = NULL;
287 * Processes a read or rmw model action.
288 * @param curr is the read model action to process.
289 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
290 * @return True if processing this read updates the mo_graph.
292 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
295 bool updated = false;
297 const ModelAction *reads_from = curr->get_node()->get_read_from();
298 if (reads_from != NULL) {
299 mo_graph->startChanges();
301 value = reads_from->get_value();
302 bool r_status = false;
304 if (!second_part_of_rmw) {
305 check_recency(curr,false);
306 r_status = r_modification_order(curr, reads_from);
310 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
311 mo_graph->rollbackChanges();
312 too_many_reads = false;
316 curr->read_from(reads_from);
317 mo_graph->commitChanges();
319 } else if (!second_part_of_rmw) {
320 /* Read from future value */
321 value = curr->get_node()->get_future_value();
322 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
323 curr->read_from(NULL);
324 Promise *valuepromise = new Promise(curr, value, expiration);
325 promises->push_back(valuepromise);
327 get_thread(curr)->set_return_value(value);
333 * Process a write ModelAction
334 * @param curr The ModelAction to process
335 * @return True if the mo_graph was updated or promises were resolved
337 bool ModelChecker::process_write(ModelAction *curr)
339 bool updated_mod_order = w_modification_order(curr);
340 bool updated_promises = resolve_promises(curr);
342 if (promises->size() == 0) {
343 for (unsigned int i = 0; i<futurevalues->size(); i++) {
344 struct PendingFutureValue pfv = (*futurevalues)[i];
345 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
346 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
347 priv->next_backtrack = pfv.act;
349 futurevalues->resize(0);
352 mo_graph->commitChanges();
353 get_thread(curr)->set_return_value(VALUE_NONE);
354 return updated_mod_order || updated_promises;
358 * This is the heart of the model checker routine. It performs model-checking
359 * actions corresponding to a given "current action." Among other processes, it
360 * calculates reads-from relationships, updates synchronization clock vectors,
361 * forms a memory_order constraints graph, and handles replay/backtrack
362 * execution when running permutations of previously-observed executions.
364 * @param curr The current action to process
365 * @return The next Thread that must be executed. May be NULL if ModelChecker
366 * makes no choice (e.g., according to replay execution, combining RMW actions,
369 Thread * ModelChecker::check_current_action(ModelAction *curr)
371 bool second_part_of_rmw = false;
375 if (curr->is_rmwc() || curr->is_rmw()) {
376 ModelAction *tmp = process_rmw(curr);
377 second_part_of_rmw = true;
380 compute_promises(curr);
382 ModelAction *tmp = node_stack->explore_action(curr, NULL);
384 /* Discard duplicate ModelAction; use action from NodeStack */
385 /* First restore type and order in case of RMW operation */
387 tmp->copy_typeandorder(curr);
389 /* If we have diverged, we need to reset the clock vector. */
391 tmp->create_cv(get_parent_action(tmp->get_tid()));
397 * Perform one-time actions when pushing new ModelAction onto
400 curr->create_cv(get_parent_action(curr->get_tid()));
401 /* Build may_read_from set */
403 build_reads_from_past(curr);
404 if (curr->is_write())
405 compute_promises(curr);
409 /* Thread specific actions */
410 switch (curr->get_type()) {
411 case THREAD_CREATE: {
412 Thread *th = (Thread *)curr->get_location();
413 th->set_creation(curr);
417 Thread *waiting, *blocking;
418 waiting = get_thread(curr);
419 blocking = (Thread *)curr->get_location();
420 if (!blocking->is_complete()) {
421 blocking->push_wait_list(curr);
422 scheduler->sleep(waiting);
426 case THREAD_FINISH: {
427 Thread *th = get_thread(curr);
428 while (!th->wait_list_empty()) {
429 ModelAction *act = th->pop_wait_list();
430 Thread *wake = get_thread(act);
431 scheduler->wake(wake);
437 check_promises(NULL, curr->get_cv());
444 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
446 while (!work_queue.empty()) {
447 WorkQueueEntry work = work_queue.front();
448 work_queue.pop_front();
451 case WORK_CHECK_CURR_ACTION: {
452 ModelAction *act = work.action;
453 bool updated = false;
454 if (act->is_read() && process_read(act, second_part_of_rmw))
457 if (act->is_write() && process_write(act))
461 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
464 case WORK_CHECK_RELEASE_SEQ:
465 resolve_release_sequences(work.location, &work_queue);
467 case WORK_CHECK_MO_EDGES:
468 /** @todo Perform follow-up mo_graph checks */
475 /* Add action to list. */
476 if (!second_part_of_rmw)
477 add_action_to_lists(curr);
479 check_curr_backtracking(curr);
481 set_backtracking(curr);
483 return get_next_thread(curr);
486 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
487 Node *currnode = curr->get_node();
488 Node *parnode = currnode->get_parent();
490 if ((!parnode->backtrack_empty() ||
491 !currnode->read_from_empty() ||
492 !currnode->future_value_empty() ||
493 !currnode->promise_empty())
494 && (!priv->next_backtrack ||
495 *curr > *priv->next_backtrack)) {
496 priv->next_backtrack = curr;
500 bool ModelChecker::promises_expired() {
501 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
502 Promise *promise = (*promises)[promise_index];
503 if (promise->get_expiration()<priv->used_sequence_numbers) {
510 /** @returns whether the current partial trace must be a prefix of a
512 bool ModelChecker::isfeasibleprefix() {
513 return promises->size() == 0 && *lazy_sync_size == 0;
516 /** @returns whether the current partial trace is feasible. */
517 bool ModelChecker::isfeasible() {
518 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
521 /** @returns whether the current partial trace is feasible other than
522 * multiple RMW reading from the same store. */
523 bool ModelChecker::isfeasibleotherthanRMW() {
524 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
527 /** Returns whether the current completed trace is feasible. */
528 bool ModelChecker::isfinalfeasible() {
529 return isfeasible() && promises->size() == 0;
532 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
533 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
534 int tid = id_to_int(act->get_tid());
535 ModelAction *lastread = get_last_action(tid);
536 lastread->process_rmw(act);
537 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
538 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
539 mo_graph->commitChanges();
545 * Checks whether a thread has read from the same write for too many times
546 * without seeing the effects of a later write.
549 * 1) there must a different write that we could read from that would satisfy the modification order,
550 * 2) we must have read from the same value in excess of maxreads times, and
551 * 3) that other write must have been in the reads_from set for maxreads times.
553 * If so, we decide that the execution is no longer feasible.
555 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
556 if (params.maxreads != 0) {
557 if (curr->get_node()->get_read_from_size() <= 1)
560 //Must make sure that execution is currently feasible... We could
561 //accidentally clear by rolling back
565 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
566 int tid = id_to_int(curr->get_tid());
569 if ((int)thrd_lists->size() <= tid)
572 action_list_t *list = &(*thrd_lists)[tid];
574 action_list_t::reverse_iterator rit = list->rbegin();
577 for (; (*rit) != curr; rit++)
579 /* go past curr now */
583 action_list_t::reverse_iterator ritcopy = rit;
584 //See if we have enough reads from the same value
586 for (; count < params.maxreads; rit++,count++) {
587 if (rit==list->rend())
589 ModelAction *act = *rit;
592 if (act->get_reads_from() != curr->get_reads_from())
594 if (act->get_node()->get_read_from_size() <= 1)
598 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
600 const ModelAction * write = curr->get_node()->get_read_from_at(i);
601 //Need a different write
602 if (write==curr->get_reads_from())
605 /* Test to see whether this is a feasible write to read from*/
606 mo_graph->startChanges();
607 r_modification_order(curr, write);
608 bool feasiblereadfrom = isfeasible();
609 mo_graph->rollbackChanges();
611 if (!feasiblereadfrom)
615 bool feasiblewrite = true;
616 //new we need to see if this write works for everyone
618 for (int loop = count; loop>0; loop--,rit++) {
619 ModelAction *act=*rit;
620 bool foundvalue = false;
621 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
622 if (act->get_node()->get_read_from_at(i)==write) {
628 feasiblewrite = false;
633 too_many_reads = true;
641 * Updates the mo_graph with the constraints imposed from the current
644 * Basic idea is the following: Go through each other thread and find
645 * the lastest action that happened before our read. Two cases:
647 * (1) The action is a write => that write must either occur before
648 * the write we read from or be the write we read from.
650 * (2) The action is a read => the write that that action read from
651 * must occur before the write we read from or be the same write.
653 * @param curr The current action. Must be a read.
654 * @param rf The action that curr reads from. Must be a write.
655 * @return True if modification order edges were added; false otherwise
657 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
659 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
662 ASSERT(curr->is_read());
664 /* Iterate over all threads */
665 for (i = 0; i < thrd_lists->size(); i++) {
666 /* Iterate over actions in thread, starting from most recent */
667 action_list_t *list = &(*thrd_lists)[i];
668 action_list_t::reverse_iterator rit;
669 for (rit = list->rbegin(); rit != list->rend(); rit++) {
670 ModelAction *act = *rit;
672 /* Include at most one act per-thread that "happens before" curr */
673 if (act->happens_before(curr)) {
674 if (act->is_write()) {
675 if (rf != act && act != curr) {
676 mo_graph->addEdge(act, rf);
680 const ModelAction *prevreadfrom = act->get_reads_from();
681 if (prevreadfrom != NULL && rf != prevreadfrom) {
682 mo_graph->addEdge(prevreadfrom, rf);
695 /** This method fixes up the modification order when we resolve a
696 * promises. The basic problem is that actions that occur after the
697 * read curr could not property add items to the modification order
700 * So for each thread, we find the earliest item that happens after
701 * the read curr. This is the item we have to fix up with additional
702 * constraints. If that action is write, we add a MO edge between
703 * the Action rf and that action. If the action is a read, we add a
704 * MO edge between the Action rf, and whatever the read accessed.
706 * @param curr is the read ModelAction that we are fixing up MO edges for.
707 * @param rf is the write ModelAction that curr reads from.
711 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
713 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
715 ASSERT(curr->is_read());
717 /* Iterate over all threads */
718 for (i = 0; i < thrd_lists->size(); i++) {
719 /* Iterate over actions in thread, starting from most recent */
720 action_list_t *list = &(*thrd_lists)[i];
721 action_list_t::reverse_iterator rit;
722 ModelAction *lastact = NULL;
724 /* Find last action that happens after curr */
725 for (rit = list->rbegin(); rit != list->rend(); rit++) {
726 ModelAction *act = *rit;
727 if (curr->happens_before(act)) {
733 /* Include at most one act per-thread that "happens before" curr */
734 if (lastact != NULL) {
735 if (lastact->is_read()) {
736 const ModelAction *postreadfrom = lastact->get_reads_from();
737 if (postreadfrom != NULL&&rf != postreadfrom)
738 mo_graph->addEdge(rf, postreadfrom);
739 } else if (rf != lastact) {
740 mo_graph->addEdge(rf, lastact);
748 * Updates the mo_graph with the constraints imposed from the current write.
750 * Basic idea is the following: Go through each other thread and find
751 * the lastest action that happened before our write. Two cases:
753 * (1) The action is a write => that write must occur before
756 * (2) The action is a read => the write that that action read from
757 * must occur before the current write.
759 * This method also handles two other issues:
761 * (I) Sequential Consistency: Making sure that if the current write is
762 * seq_cst, that it occurs after the previous seq_cst write.
764 * (II) Sending the write back to non-synchronizing reads.
766 * @param curr The current action. Must be a write.
767 * @return True if modification order edges were added; false otherwise
769 bool ModelChecker::w_modification_order(ModelAction *curr)
771 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
774 ASSERT(curr->is_write());
776 if (curr->is_seqcst()) {
777 /* We have to at least see the last sequentially consistent write,
778 so we are initialized. */
779 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
780 if (last_seq_cst != NULL) {
781 mo_graph->addEdge(last_seq_cst, curr);
786 /* Iterate over all threads */
787 for (i = 0; i < thrd_lists->size(); i++) {
788 /* Iterate over actions in thread, starting from most recent */
789 action_list_t *list = &(*thrd_lists)[i];
790 action_list_t::reverse_iterator rit;
791 for (rit = list->rbegin(); rit != list->rend(); rit++) {
792 ModelAction *act = *rit;
794 /* Include at most one act per-thread that "happens before" curr */
795 if (act->happens_before(curr)) {
797 * Note: if act is RMW, just add edge:
799 * The following edge should be handled elsewhere:
800 * readfrom(act) --mo--> act
802 if (act->is_write()) {
803 //RMW shouldn't have an edge to themselves
805 mo_graph->addEdge(act, curr);
806 } else if (act->is_read() && act->get_reads_from() != NULL)
807 mo_graph->addEdge(act->get_reads_from(), curr);
810 } else if (act->is_read() && !act->is_synchronizing(curr) &&
811 !act->same_thread(curr)) {
812 /* We have an action that:
813 (1) did not happen before us
814 (2) is a read and we are a write
815 (3) cannot synchronize with us
816 (4) is in a different thread
818 that read could potentially read from our write.
820 if (thin_air_constraint_may_allow(curr, act)) {
822 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
823 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
824 futurevalues->push_back(pfv);
834 /** Arbitrary reads from the future are not allowed. Section 29.3
835 * part 9 places some constraints. This method checks one result of constraint
836 * constraint. Others require compiler support. */
838 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
839 if (!writer->is_rmw())
842 if (!reader->is_rmw())
845 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
848 if (search->get_tid() == reader->get_tid() &&
849 search->happens_before(reader))
857 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
858 * The ModelAction under consideration is expected to be taking part in
859 * release/acquire synchronization as an object of the "reads from" relation.
860 * Note that this can only provide release sequence support for RMW chains
861 * which do not read from the future, as those actions cannot be traced until
862 * their "promise" is fulfilled. Similarly, we may not even establish the
863 * presence of a release sequence with certainty, as some modification order
864 * constraints may be decided further in the future. Thus, this function
865 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
866 * and a boolean representing certainty.
868 * @todo Finish lazy updating, when promises are fulfilled in the future
869 * @param rf The action that might be part of a release sequence. Must be a
871 * @param release_heads A pass-by-reference style return parameter. After
872 * execution of this function, release_heads will contain the heads of all the
873 * relevant release sequences, if any exists
874 * @return true, if the ModelChecker is certain that release_heads is complete;
877 bool ModelChecker::release_seq_head(const ModelAction *rf,
878 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
881 /* read from future: need to settle this later */
882 return false; /* incomplete */
885 ASSERT(rf->is_write());
887 if (rf->is_release())
888 release_heads->push_back(rf);
890 /* We need a RMW action that is both an acquire and release to stop */
891 /** @todo Need to be smarter here... In the linux lock
892 * example, this will run to the beginning of the program for
894 if (rf->is_acquire() && rf->is_release())
895 return true; /* complete */
896 return release_seq_head(rf->get_reads_from(), release_heads);
898 if (rf->is_release())
899 return true; /* complete */
901 /* else relaxed write; check modification order for contiguous subsequence
902 * -> rf must be same thread as release */
903 int tid = id_to_int(rf->get_tid());
904 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
905 action_list_t *list = &(*thrd_lists)[tid];
906 action_list_t::const_reverse_iterator rit;
908 /* Find rf in the thread list */
909 rit = std::find(list->rbegin(), list->rend(), rf);
910 ASSERT(rit != list->rend());
912 /* Find the last write/release */
913 for (; rit != list->rend(); rit++)
914 if ((*rit)->is_release())
916 if (rit == list->rend()) {
917 /* No write-release in this thread */
918 return true; /* complete */
920 ModelAction *release = *rit;
922 ASSERT(rf->same_thread(release));
925 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
926 if (id_to_int(rf->get_tid()) == (int)i)
928 list = &(*thrd_lists)[i];
930 /* Can we ensure no future writes from this thread may break
931 * the release seq? */
932 bool future_ordered = false;
934 for (rit = list->rbegin(); rit != list->rend(); rit++) {
935 const ModelAction *act = *rit;
936 if (!act->is_write())
938 /* Reach synchronization -> this thread is complete */
939 if (act->happens_before(release))
941 if (rf->happens_before(act)) {
942 future_ordered = true;
946 /* Check modification order */
947 if (mo_graph->checkReachable(rf, act)) {
949 future_ordered = true;
952 if (mo_graph->checkReachable(act, release))
953 /* act --mo--> release */
955 if (mo_graph->checkReachable(release, act) &&
956 mo_graph->checkReachable(act, rf)) {
957 /* release --mo-> act --mo--> rf */
958 return true; /* complete */
963 return false; /* This thread is uncertain */
967 release_heads->push_back(release);
972 * A public interface for getting the release sequence head(s) with which a
973 * given ModelAction must synchronize. This function only returns a non-empty
974 * result when it can locate a release sequence head with certainty. Otherwise,
975 * it may mark the internal state of the ModelChecker so that it will handle
976 * the release sequence at a later time, causing @a act to update its
977 * synchronization at some later point in execution.
978 * @param act The 'acquire' action that may read from a release sequence
979 * @param release_heads A pass-by-reference return parameter. Will be filled
980 * with the head(s) of the release sequence(s), if they exists with certainty.
981 * @see ModelChecker::release_seq_head
983 void ModelChecker::get_release_seq_heads(ModelAction *act,
984 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
986 const ModelAction *rf = act->get_reads_from();
988 complete = release_seq_head(rf, release_heads);
990 /* add act to 'lazy checking' list */
991 std::list<ModelAction *> *list;
992 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
993 list->push_back(act);
999 * Attempt to resolve all stashed operations that might synchronize with a
1000 * release sequence for a given location. This implements the "lazy" portion of
1001 * determining whether or not a release sequence was contiguous, since not all
1002 * modification order information is present at the time an action occurs.
1004 * @param location The location/object that should be checked for release
1005 * sequence resolutions
1006 * @param work_queue The work queue to which to add work items as they are
1008 * @return True if any updates occurred (new synchronization, new mo_graph
1011 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1013 std::list<ModelAction *> *list;
1014 list = lazy_sync_with_release->getptr(location);
1018 bool updated = false;
1019 std::list<ModelAction *>::iterator it = list->begin();
1020 while (it != list->end()) {
1021 ModelAction *act = *it;
1022 const ModelAction *rf = act->get_reads_from();
1023 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
1025 complete = release_seq_head(rf, &release_heads);
1026 for (unsigned int i = 0; i < release_heads.size(); i++) {
1027 if (!act->has_synchronized_with(release_heads[i])) {
1029 act->synchronize_with(release_heads[i]);
1034 /* Re-check act for mo_graph edges */
1035 work_queue->push_back(MOEdgeWorkEntry(act));
1037 /* propagate synchronization to later actions */
1038 action_list_t::reverse_iterator it = action_trace->rbegin();
1039 while ((*it) != act) {
1040 ModelAction *propagate = *it;
1041 if (act->happens_before(propagate)) {
1042 propagate->synchronize_with(act);
1043 /* Re-check 'propagate' for mo_graph edges */
1044 work_queue->push_back(MOEdgeWorkEntry(propagate));
1049 it = list->erase(it);
1050 (*lazy_sync_size)--;
1055 // If we resolved promises or data races, see if we have realized a data race.
1056 if (checkDataRaces()) {
1064 * Performs various bookkeeping operations for the current ModelAction. For
1065 * instance, adds action to the per-object, per-thread action vector and to the
1066 * action trace list of all thread actions.
1068 * @param act is the ModelAction to add.
1070 void ModelChecker::add_action_to_lists(ModelAction *act)
1072 int tid = id_to_int(act->get_tid());
1073 action_trace->push_back(act);
1075 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1077 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1078 if (tid >= (int)vec->size())
1079 vec->resize(priv->next_thread_id);
1080 (*vec)[tid].push_back(act);
1082 if ((int)thrd_last_action->size() <= tid)
1083 thrd_last_action->resize(get_num_threads());
1084 (*thrd_last_action)[tid] = act;
1087 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1089 int nthreads = get_num_threads();
1090 if ((int)thrd_last_action->size() < nthreads)
1091 thrd_last_action->resize(nthreads);
1092 return (*thrd_last_action)[id_to_int(tid)];
1096 * Gets the last memory_order_seq_cst action (in the total global sequence)
1097 * performed on a particular object (i.e., memory location).
1098 * @param location The object location to check
1099 * @return The last seq_cst action performed
1101 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1103 action_list_t *list = obj_map->get_safe_ptr(location);
1104 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1105 action_list_t::reverse_iterator rit;
1106 for (rit = list->rbegin(); rit != list->rend(); rit++)
1107 if ((*rit)->is_write() && (*rit)->is_seqcst())
1112 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1114 ModelAction *parent = get_last_action(tid);
1116 parent = get_thread(tid)->get_creation();
1121 * Returns the clock vector for a given thread.
1122 * @param tid The thread whose clock vector we want
1123 * @return Desired clock vector
1125 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1127 return get_parent_action(tid)->get_cv();
1131 * Resolve a set of Promises with a current write. The set is provided in the
1132 * Node corresponding to @a write.
1133 * @param write The ModelAction that is fulfilling Promises
1134 * @return True if promises were resolved; false otherwise
1136 bool ModelChecker::resolve_promises(ModelAction *write)
1138 bool resolved = false;
1140 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1141 Promise *promise = (*promises)[promise_index];
1142 if (write->get_node()->get_promise(i)) {
1143 ModelAction *read = promise->get_action();
1144 read->read_from(write);
1145 if (read->is_rmw()) {
1146 mo_graph->addRMWEdge(write, read);
1148 //First fix up the modification order for actions that happened
1150 r_modification_order(read, write);
1151 //Next fix up the modification order for actions that happened
1153 post_r_modification_order(read, write);
1154 promises->erase(promises->begin() + promise_index);
1163 * Compute the set of promises that could potentially be satisfied by this
1164 * action. Note that the set computation actually appears in the Node, not in
1166 * @param curr The ModelAction that may satisfy promises
1168 void ModelChecker::compute_promises(ModelAction *curr)
1170 for (unsigned int i = 0; i < promises->size(); i++) {
1171 Promise *promise = (*promises)[i];
1172 const ModelAction *act = promise->get_action();
1173 if (!act->happens_before(curr) &&
1175 !act->is_synchronizing(curr) &&
1176 !act->same_thread(curr) &&
1177 promise->get_value() == curr->get_value()) {
1178 curr->get_node()->set_promise(i);
1183 /** Checks promises in response to change in ClockVector Threads. */
1184 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1186 for (unsigned int i = 0; i < promises->size(); i++) {
1187 Promise *promise = (*promises)[i];
1188 const ModelAction *act = promise->get_action();
1189 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1190 merge_cv->synchronized_since(act)) {
1191 //This thread is no longer able to send values back to satisfy the promise
1192 int num_synchronized_threads = promise->increment_threads();
1193 if (num_synchronized_threads == get_num_threads()) {
1194 //Promise has failed
1195 failed_promise = true;
1203 * Build up an initial set of all past writes that this 'read' action may read
1204 * from. This set is determined by the clock vector's "happens before"
1206 * @param curr is the current ModelAction that we are exploring; it must be a
1209 void ModelChecker::build_reads_from_past(ModelAction *curr)
1211 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1213 ASSERT(curr->is_read());
1215 ModelAction *last_seq_cst = NULL;
1217 /* Track whether this object has been initialized */
1218 bool initialized = false;
1220 if (curr->is_seqcst()) {
1221 last_seq_cst = get_last_seq_cst(curr->get_location());
1222 /* We have to at least see the last sequentially consistent write,
1223 so we are initialized. */
1224 if (last_seq_cst != NULL)
1228 /* Iterate over all threads */
1229 for (i = 0; i < thrd_lists->size(); i++) {
1230 /* Iterate over actions in thread, starting from most recent */
1231 action_list_t *list = &(*thrd_lists)[i];
1232 action_list_t::reverse_iterator rit;
1233 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1234 ModelAction *act = *rit;
1236 /* Only consider 'write' actions */
1237 if (!act->is_write())
1240 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1241 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1242 DEBUG("Adding action to may_read_from:\n");
1243 if (DBG_ENABLED()) {
1247 curr->get_node()->add_read_from(act);
1250 /* Include at most one act per-thread that "happens before" curr */
1251 if (act->happens_before(curr)) {
1259 /** @todo Need a more informative way of reporting errors. */
1260 printf("ERROR: may read from uninitialized atomic\n");
1263 if (DBG_ENABLED() || !initialized) {
1264 printf("Reached read action:\n");
1266 printf("Printing may_read_from\n");
1267 curr->get_node()->print_may_read_from();
1268 printf("End printing may_read_from\n");
1271 ASSERT(initialized);
1274 static void print_list(action_list_t *list)
1276 action_list_t::iterator it;
1278 printf("---------------------------------------------------------------------\n");
1281 for (it = list->begin(); it != list->end(); it++) {
1284 printf("---------------------------------------------------------------------\n");
1287 void ModelChecker::print_summary()
1290 printf("Number of executions: %d\n", num_executions);
1291 printf("Number of feasible executions: %d\n", num_feasible_executions);
1292 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1294 #if SUPPORT_MOD_ORDER_DUMP
1296 char buffername[100];
1297 sprintf(buffername, "exec%u",num_executions);
1298 mo_graph->dumpGraphToFile(buffername);
1301 if (!isfinalfeasible())
1302 printf("INFEASIBLE EXECUTION!\n");
1303 print_list(action_trace);
1308 * Add a Thread to the system for the first time. Should only be called once
1310 * @param t The Thread to add
1312 void ModelChecker::add_thread(Thread *t)
1314 thread_map->put(id_to_int(t->get_id()), t);
1315 scheduler->add_thread(t);
1318 void ModelChecker::remove_thread(Thread *t)
1320 scheduler->remove_thread(t);
1324 * Switch from a user-context to the "master thread" context (a.k.a. system
1325 * context). This switch is made with the intention of exploring a particular
1326 * model-checking action (described by a ModelAction object). Must be called
1327 * from a user-thread context.
1328 * @param act The current action that will be explored. Must not be NULL.
1329 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1331 int ModelChecker::switch_to_master(ModelAction *act)
1334 Thread *old = thread_current();
1335 set_current_action(act);
1336 old->set_state(THREAD_READY);
1337 return Thread::swap(old, &system_context);
1341 * Takes the next step in the execution, if possible.
1342 * @return Returns true (success) if a step was taken and false otherwise.
1344 bool ModelChecker::take_step() {
1345 Thread *curr, *next;
1350 curr = thread_current();
1352 if (curr->get_state() == THREAD_READY) {
1353 ASSERT(priv->current_action);
1355 priv->nextThread = check_current_action(priv->current_action);
1356 priv->current_action = NULL;
1357 if (!curr->is_blocked() && !curr->is_complete())
1358 scheduler->add_thread(curr);
1363 next = scheduler->next_thread(priv->nextThread);
1365 /* Infeasible -> don't take any more steps */
1370 next->set_state(THREAD_RUNNING);
1371 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1373 /* next == NULL -> don't take any more steps */
1376 /* Return false only if swap fails with an error */
1377 return (Thread::swap(&system_context, next) == 0);
1380 /** Runs the current execution until threre are no more steps to take. */
1381 void ModelChecker::finish_execution() {
1384 while (take_step());