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();
200 if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
201 /* linear search: from most recent to oldest */
202 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
203 action_list_t::reverse_iterator rit;
204 for (rit = list->rbegin(); rit != list->rend(); rit++) {
205 ModelAction *prev = *rit;
206 if (act->is_synchronizing(prev))
209 } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
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 (prev->is_success_lock())
218 } else if (type==ATOMIC_UNLOCK) {
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_failed_trylock())
231 void ModelChecker::set_backtracking(ModelAction *act)
235 Thread *t = get_thread(act);
237 prev = get_last_conflict(act);
241 node = prev->get_node()->get_parent();
243 while (!node->is_enabled(t))
246 /* Check if this has been explored already */
247 if (node->has_been_explored(t->get_id()))
250 /* Cache the latest backtracking point */
251 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
252 priv->next_backtrack = prev;
254 /* If this is a new backtracking point, mark the tree */
255 if (!node->set_backtrack(t->get_id()))
257 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
258 prev->get_tid(), t->get_id());
266 * Returns last backtracking point. The model checker will explore a different
267 * path for this point in the next execution.
268 * @return The ModelAction at which the next execution should diverge.
270 ModelAction * ModelChecker::get_next_backtrack()
272 ModelAction *next = priv->next_backtrack;
273 priv->next_backtrack = NULL;
278 * Processes a read or rmw model action.
279 * @param curr is the read model action to process.
280 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
281 * @return True if processing this read updates the mo_graph.
283 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
286 bool updated = false;
288 const ModelAction *reads_from = curr->get_node()->get_read_from();
289 if (reads_from != NULL) {
290 mo_graph->startChanges();
292 value = reads_from->get_value();
293 bool r_status = false;
295 if (!second_part_of_rmw) {
296 check_recency(curr,false);
297 r_status = r_modification_order(curr, reads_from);
301 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
302 mo_graph->rollbackChanges();
303 too_many_reads = false;
307 curr->read_from(reads_from);
308 mo_graph->commitChanges();
310 } else if (!second_part_of_rmw) {
311 /* Read from future value */
312 value = curr->get_node()->get_future_value();
313 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
314 curr->read_from(NULL);
315 Promise *valuepromise = new Promise(curr, value, expiration);
316 promises->push_back(valuepromise);
318 get_thread(curr)->set_return_value(value);
324 * Process a write ModelAction
325 * @param curr The ModelAction to process
326 * @return True if the mo_graph was updated or promises were resolved
328 bool ModelChecker::process_write(ModelAction *curr)
330 bool updated_mod_order = w_modification_order(curr);
331 bool updated_promises = resolve_promises(curr);
333 if (promises->size() == 0) {
334 for (unsigned int i = 0; i<futurevalues->size(); i++) {
335 struct PendingFutureValue pfv = (*futurevalues)[i];
336 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
337 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
338 priv->next_backtrack = pfv.act;
340 futurevalues->resize(0);
343 mo_graph->commitChanges();
344 get_thread(curr)->set_return_value(VALUE_NONE);
345 return updated_mod_order || updated_promises;
349 * This is the heart of the model checker routine. It performs model-checking
350 * actions corresponding to a given "current action." Among other processes, it
351 * calculates reads-from relationships, updates synchronization clock vectors,
352 * forms a memory_order constraints graph, and handles replay/backtrack
353 * execution when running permutations of previously-observed executions.
355 * @param curr The current action to process
356 * @return The next Thread that must be executed. May be NULL if ModelChecker
357 * makes no choice (e.g., according to replay execution, combining RMW actions,
360 Thread * ModelChecker::check_current_action(ModelAction *curr)
362 bool second_part_of_rmw = false;
366 if (curr->is_rmwc() || curr->is_rmw()) {
367 ModelAction *tmp = process_rmw(curr);
368 second_part_of_rmw = true;
371 compute_promises(curr);
373 ModelAction *tmp = node_stack->explore_action(curr, scheduler->get_enabled());
375 /* Discard duplicate ModelAction; use action from NodeStack */
376 /* First restore type and order in case of RMW operation */
378 tmp->copy_typeandorder(curr);
380 /* If we have diverged, we need to reset the clock vector. */
382 tmp->create_cv(get_parent_action(tmp->get_tid()));
388 * Perform one-time actions when pushing new ModelAction onto
391 curr->create_cv(get_parent_action(curr->get_tid()));
392 /* Build may_read_from set */
394 build_reads_from_past(curr);
395 if (curr->is_write())
396 compute_promises(curr);
400 /* Thread specific actions */
401 switch (curr->get_type()) {
402 case THREAD_CREATE: {
403 Thread *th = (Thread *)curr->get_location();
404 th->set_creation(curr);
408 Thread *waiting, *blocking;
409 waiting = get_thread(curr);
410 blocking = (Thread *)curr->get_location();
411 if (!blocking->is_complete()) {
412 blocking->push_wait_list(curr);
413 scheduler->sleep(waiting);
417 case THREAD_FINISH: {
418 Thread *th = get_thread(curr);
419 while (!th->wait_list_empty()) {
420 ModelAction *act = th->pop_wait_list();
421 Thread *wake = get_thread(act);
422 scheduler->wake(wake);
428 check_promises(NULL, curr->get_cv());
435 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
437 while (!work_queue.empty()) {
438 WorkQueueEntry work = work_queue.front();
439 work_queue.pop_front();
442 case WORK_CHECK_CURR_ACTION: {
443 ModelAction *act = work.action;
444 bool updated = false;
445 if (act->is_read() && process_read(act, second_part_of_rmw))
448 if (act->is_write() && process_write(act))
452 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
455 case WORK_CHECK_RELEASE_SEQ:
456 resolve_release_sequences(work.location, &work_queue);
458 case WORK_CHECK_MO_EDGES:
459 /** @todo Perform follow-up mo_graph checks */
466 /* Add action to list. */
467 if (!second_part_of_rmw)
468 add_action_to_lists(curr);
470 check_curr_backtracking(curr);
472 set_backtracking(curr);
474 return get_next_thread(curr);
477 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
478 Node *currnode = curr->get_node();
479 Node *parnode = currnode->get_parent();
481 if ((!parnode->backtrack_empty() ||
482 !currnode->read_from_empty() ||
483 !currnode->future_value_empty() ||
484 !currnode->promise_empty())
485 && (!priv->next_backtrack ||
486 *curr > *priv->next_backtrack)) {
487 priv->next_backtrack = curr;
491 bool ModelChecker::promises_expired() {
492 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
493 Promise *promise = (*promises)[promise_index];
494 if (promise->get_expiration()<priv->used_sequence_numbers) {
501 /** @returns whether the current partial trace must be a prefix of a
503 bool ModelChecker::isfeasibleprefix() {
504 return promises->size() == 0 && *lazy_sync_size == 0;
507 /** @returns whether the current partial trace is feasible. */
508 bool ModelChecker::isfeasible() {
509 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
512 /** @returns whether the current partial trace is feasible other than
513 * multiple RMW reading from the same store. */
514 bool ModelChecker::isfeasibleotherthanRMW() {
515 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
518 /** Returns whether the current completed trace is feasible. */
519 bool ModelChecker::isfinalfeasible() {
520 return isfeasible() && promises->size() == 0;
523 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
524 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
525 int tid = id_to_int(act->get_tid());
526 ModelAction *lastread = get_last_action(tid);
527 lastread->process_rmw(act);
528 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
529 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
530 mo_graph->commitChanges();
536 * Checks whether a thread has read from the same write for too many times
537 * without seeing the effects of a later write.
540 * 1) there must a different write that we could read from that would satisfy the modification order,
541 * 2) we must have read from the same value in excess of maxreads times, and
542 * 3) that other write must have been in the reads_from set for maxreads times.
544 * If so, we decide that the execution is no longer feasible.
546 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
547 if (params.maxreads != 0) {
548 if (curr->get_node()->get_read_from_size() <= 1)
551 //Must make sure that execution is currently feasible... We could
552 //accidentally clear by rolling back
556 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
557 int tid = id_to_int(curr->get_tid());
560 if ((int)thrd_lists->size() <= tid)
563 action_list_t *list = &(*thrd_lists)[tid];
565 action_list_t::reverse_iterator rit = list->rbegin();
568 for (; (*rit) != curr; rit++)
570 /* go past curr now */
574 action_list_t::reverse_iterator ritcopy = rit;
575 //See if we have enough reads from the same value
577 for (; count < params.maxreads; rit++,count++) {
578 if (rit==list->rend())
580 ModelAction *act = *rit;
583 if (act->get_reads_from() != curr->get_reads_from())
585 if (act->get_node()->get_read_from_size() <= 1)
589 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
591 const ModelAction * write = curr->get_node()->get_read_from_at(i);
592 //Need a different write
593 if (write==curr->get_reads_from())
596 /* Test to see whether this is a feasible write to read from*/
597 mo_graph->startChanges();
598 r_modification_order(curr, write);
599 bool feasiblereadfrom = isfeasible();
600 mo_graph->rollbackChanges();
602 if (!feasiblereadfrom)
606 bool feasiblewrite = true;
607 //new we need to see if this write works for everyone
609 for (int loop = count; loop>0; loop--,rit++) {
610 ModelAction *act=*rit;
611 bool foundvalue = false;
612 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
613 if (act->get_node()->get_read_from_at(i)==write) {
619 feasiblewrite = false;
624 too_many_reads = true;
632 * Updates the mo_graph with the constraints imposed from the current
635 * Basic idea is the following: Go through each other thread and find
636 * the lastest action that happened before our read. Two cases:
638 * (1) The action is a write => that write must either occur before
639 * the write we read from or be the write we read from.
641 * (2) The action is a read => the write that that action read from
642 * must occur before the write we read from or be the same write.
644 * @param curr The current action. Must be a read.
645 * @param rf The action that curr reads from. Must be a write.
646 * @return True if modification order edges were added; false otherwise
648 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
650 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
653 ASSERT(curr->is_read());
655 /* Iterate over all threads */
656 for (i = 0; i < thrd_lists->size(); i++) {
657 /* Iterate over actions in thread, starting from most recent */
658 action_list_t *list = &(*thrd_lists)[i];
659 action_list_t::reverse_iterator rit;
660 for (rit = list->rbegin(); rit != list->rend(); rit++) {
661 ModelAction *act = *rit;
663 /* Include at most one act per-thread that "happens before" curr */
664 if (act->happens_before(curr)) {
665 if (act->is_write()) {
666 if (rf != act && act != curr) {
667 mo_graph->addEdge(act, rf);
671 const ModelAction *prevreadfrom = act->get_reads_from();
672 if (prevreadfrom != NULL && rf != prevreadfrom) {
673 mo_graph->addEdge(prevreadfrom, rf);
686 /** This method fixes up the modification order when we resolve a
687 * promises. The basic problem is that actions that occur after the
688 * read curr could not property add items to the modification order
691 * So for each thread, we find the earliest item that happens after
692 * the read curr. This is the item we have to fix up with additional
693 * constraints. If that action is write, we add a MO edge between
694 * the Action rf and that action. If the action is a read, we add a
695 * MO edge between the Action rf, and whatever the read accessed.
697 * @param curr is the read ModelAction that we are fixing up MO edges for.
698 * @param rf is the write ModelAction that curr reads from.
702 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
704 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
706 ASSERT(curr->is_read());
708 /* Iterate over all threads */
709 for (i = 0; i < thrd_lists->size(); i++) {
710 /* Iterate over actions in thread, starting from most recent */
711 action_list_t *list = &(*thrd_lists)[i];
712 action_list_t::reverse_iterator rit;
713 ModelAction *lastact = NULL;
715 /* Find last action that happens after curr */
716 for (rit = list->rbegin(); rit != list->rend(); rit++) {
717 ModelAction *act = *rit;
718 if (curr->happens_before(act)) {
724 /* Include at most one act per-thread that "happens before" curr */
725 if (lastact != NULL) {
726 if (lastact->is_read()) {
727 const ModelAction *postreadfrom = lastact->get_reads_from();
728 if (postreadfrom != NULL&&rf != postreadfrom)
729 mo_graph->addEdge(rf, postreadfrom);
730 } else if (rf != lastact) {
731 mo_graph->addEdge(rf, lastact);
739 * Updates the mo_graph with the constraints imposed from the current write.
741 * Basic idea is the following: Go through each other thread and find
742 * the lastest action that happened before our write. Two cases:
744 * (1) The action is a write => that write must occur before
747 * (2) The action is a read => the write that that action read from
748 * must occur before the current write.
750 * This method also handles two other issues:
752 * (I) Sequential Consistency: Making sure that if the current write is
753 * seq_cst, that it occurs after the previous seq_cst write.
755 * (II) Sending the write back to non-synchronizing reads.
757 * @param curr The current action. Must be a write.
758 * @return True if modification order edges were added; false otherwise
760 bool ModelChecker::w_modification_order(ModelAction *curr)
762 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
765 ASSERT(curr->is_write());
767 if (curr->is_seqcst()) {
768 /* We have to at least see the last sequentially consistent write,
769 so we are initialized. */
770 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
771 if (last_seq_cst != NULL) {
772 mo_graph->addEdge(last_seq_cst, curr);
777 /* Iterate over all threads */
778 for (i = 0; i < thrd_lists->size(); i++) {
779 /* Iterate over actions in thread, starting from most recent */
780 action_list_t *list = &(*thrd_lists)[i];
781 action_list_t::reverse_iterator rit;
782 for (rit = list->rbegin(); rit != list->rend(); rit++) {
783 ModelAction *act = *rit;
785 /* Include at most one act per-thread that "happens before" curr */
786 if (act->happens_before(curr)) {
788 * Note: if act is RMW, just add edge:
790 * The following edge should be handled elsewhere:
791 * readfrom(act) --mo--> act
793 if (act->is_write()) {
794 //RMW shouldn't have an edge to themselves
796 mo_graph->addEdge(act, curr);
797 } else if (act->is_read() && act->get_reads_from() != NULL)
798 mo_graph->addEdge(act->get_reads_from(), curr);
801 } else if (act->is_read() && !act->is_synchronizing(curr) &&
802 !act->same_thread(curr)) {
803 /* We have an action that:
804 (1) did not happen before us
805 (2) is a read and we are a write
806 (3) cannot synchronize with us
807 (4) is in a different thread
809 that read could potentially read from our write.
811 if (thin_air_constraint_may_allow(curr, act)) {
813 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
814 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
815 futurevalues->push_back(pfv);
825 /** Arbitrary reads from the future are not allowed. Section 29.3
826 * part 9 places some constraints. This method checks one result of constraint
827 * constraint. Others require compiler support. */
829 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
830 if (!writer->is_rmw())
833 if (!reader->is_rmw())
836 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
839 if (search->get_tid() == reader->get_tid() &&
840 search->happens_before(reader))
848 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
849 * The ModelAction under consideration is expected to be taking part in
850 * release/acquire synchronization as an object of the "reads from" relation.
851 * Note that this can only provide release sequence support for RMW chains
852 * which do not read from the future, as those actions cannot be traced until
853 * their "promise" is fulfilled. Similarly, we may not even establish the
854 * presence of a release sequence with certainty, as some modification order
855 * constraints may be decided further in the future. Thus, this function
856 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
857 * and a boolean representing certainty.
859 * @todo Finish lazy updating, when promises are fulfilled in the future
860 * @param rf The action that might be part of a release sequence. Must be a
862 * @param release_heads A pass-by-reference style return parameter. After
863 * execution of this function, release_heads will contain the heads of all the
864 * relevant release sequences, if any exists
865 * @return true, if the ModelChecker is certain that release_heads is complete;
868 bool ModelChecker::release_seq_head(const ModelAction *rf,
869 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
872 /* read from future: need to settle this later */
873 return false; /* incomplete */
876 ASSERT(rf->is_write());
878 if (rf->is_release())
879 release_heads->push_back(rf);
881 /* We need a RMW action that is both an acquire and release to stop */
882 /** @todo Need to be smarter here... In the linux lock
883 * example, this will run to the beginning of the program for
885 if (rf->is_acquire() && rf->is_release())
886 return true; /* complete */
887 return release_seq_head(rf->get_reads_from(), release_heads);
889 if (rf->is_release())
890 return true; /* complete */
892 /* else relaxed write; check modification order for contiguous subsequence
893 * -> rf must be same thread as release */
894 int tid = id_to_int(rf->get_tid());
895 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
896 action_list_t *list = &(*thrd_lists)[tid];
897 action_list_t::const_reverse_iterator rit;
899 /* Find rf in the thread list */
900 rit = std::find(list->rbegin(), list->rend(), rf);
901 ASSERT(rit != list->rend());
903 /* Find the last write/release */
904 for (; rit != list->rend(); rit++)
905 if ((*rit)->is_release())
907 if (rit == list->rend()) {
908 /* No write-release in this thread */
909 return true; /* complete */
911 ModelAction *release = *rit;
913 ASSERT(rf->same_thread(release));
916 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
917 if (id_to_int(rf->get_tid()) == (int)i)
919 list = &(*thrd_lists)[i];
921 /* Can we ensure no future writes from this thread may break
922 * the release seq? */
923 bool future_ordered = false;
925 for (rit = list->rbegin(); rit != list->rend(); rit++) {
926 const ModelAction *act = *rit;
927 if (!act->is_write())
929 /* Reach synchronization -> this thread is complete */
930 if (act->happens_before(release))
932 if (rf->happens_before(act)) {
933 future_ordered = true;
937 /* Check modification order */
938 if (mo_graph->checkReachable(rf, act)) {
940 future_ordered = true;
943 if (mo_graph->checkReachable(act, release))
944 /* act --mo--> release */
946 if (mo_graph->checkReachable(release, act) &&
947 mo_graph->checkReachable(act, rf)) {
948 /* release --mo-> act --mo--> rf */
949 return true; /* complete */
954 return false; /* This thread is uncertain */
958 release_heads->push_back(release);
963 * A public interface for getting the release sequence head(s) with which a
964 * given ModelAction must synchronize. This function only returns a non-empty
965 * result when it can locate a release sequence head with certainty. Otherwise,
966 * it may mark the internal state of the ModelChecker so that it will handle
967 * the release sequence at a later time, causing @a act to update its
968 * synchronization at some later point in execution.
969 * @param act The 'acquire' action that may read from a release sequence
970 * @param release_heads A pass-by-reference return parameter. Will be filled
971 * with the head(s) of the release sequence(s), if they exists with certainty.
972 * @see ModelChecker::release_seq_head
974 void ModelChecker::get_release_seq_heads(ModelAction *act,
975 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
977 const ModelAction *rf = act->get_reads_from();
979 complete = release_seq_head(rf, release_heads);
981 /* add act to 'lazy checking' list */
982 std::list<ModelAction *> *list;
983 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
984 list->push_back(act);
990 * Attempt to resolve all stashed operations that might synchronize with a
991 * release sequence for a given location. This implements the "lazy" portion of
992 * determining whether or not a release sequence was contiguous, since not all
993 * modification order information is present at the time an action occurs.
995 * @param location The location/object that should be checked for release
996 * sequence resolutions
997 * @param work_queue The work queue to which to add work items as they are
999 * @return True if any updates occurred (new synchronization, new mo_graph
1002 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1004 std::list<ModelAction *> *list;
1005 list = lazy_sync_with_release->getptr(location);
1009 bool updated = false;
1010 std::list<ModelAction *>::iterator it = list->begin();
1011 while (it != list->end()) {
1012 ModelAction *act = *it;
1013 const ModelAction *rf = act->get_reads_from();
1014 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
1016 complete = release_seq_head(rf, &release_heads);
1017 for (unsigned int i = 0; i < release_heads.size(); i++) {
1018 if (!act->has_synchronized_with(release_heads[i])) {
1020 act->synchronize_with(release_heads[i]);
1025 /* Re-check act for mo_graph edges */
1026 work_queue->push_back(MOEdgeWorkEntry(act));
1028 /* propagate synchronization to later actions */
1029 action_list_t::reverse_iterator it = action_trace->rbegin();
1030 while ((*it) != act) {
1031 ModelAction *propagate = *it;
1032 if (act->happens_before(propagate)) {
1033 propagate->synchronize_with(act);
1034 /* Re-check 'propagate' for mo_graph edges */
1035 work_queue->push_back(MOEdgeWorkEntry(propagate));
1040 it = list->erase(it);
1041 (*lazy_sync_size)--;
1046 // If we resolved promises or data races, see if we have realized a data race.
1047 if (checkDataRaces()) {
1055 * Performs various bookkeeping operations for the current ModelAction. For
1056 * instance, adds action to the per-object, per-thread action vector and to the
1057 * action trace list of all thread actions.
1059 * @param act is the ModelAction to add.
1061 void ModelChecker::add_action_to_lists(ModelAction *act)
1063 int tid = id_to_int(act->get_tid());
1064 action_trace->push_back(act);
1066 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1068 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1069 if (tid >= (int)vec->size())
1070 vec->resize(priv->next_thread_id);
1071 (*vec)[tid].push_back(act);
1073 if ((int)thrd_last_action->size() <= tid)
1074 thrd_last_action->resize(get_num_threads());
1075 (*thrd_last_action)[tid] = act;
1078 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1080 int nthreads = get_num_threads();
1081 if ((int)thrd_last_action->size() < nthreads)
1082 thrd_last_action->resize(nthreads);
1083 return (*thrd_last_action)[id_to_int(tid)];
1087 * Gets the last memory_order_seq_cst action (in the total global sequence)
1088 * performed on a particular object (i.e., memory location).
1089 * @param location The object location to check
1090 * @return The last seq_cst action performed
1092 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1094 action_list_t *list = obj_map->get_safe_ptr(location);
1095 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1096 action_list_t::reverse_iterator rit;
1097 for (rit = list->rbegin(); rit != list->rend(); rit++)
1098 if ((*rit)->is_write() && (*rit)->is_seqcst())
1103 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1105 ModelAction *parent = get_last_action(tid);
1107 parent = get_thread(tid)->get_creation();
1112 * Returns the clock vector for a given thread.
1113 * @param tid The thread whose clock vector we want
1114 * @return Desired clock vector
1116 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1118 return get_parent_action(tid)->get_cv();
1122 * Resolve a set of Promises with a current write. The set is provided in the
1123 * Node corresponding to @a write.
1124 * @param write The ModelAction that is fulfilling Promises
1125 * @return True if promises were resolved; false otherwise
1127 bool ModelChecker::resolve_promises(ModelAction *write)
1129 bool resolved = false;
1131 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1132 Promise *promise = (*promises)[promise_index];
1133 if (write->get_node()->get_promise(i)) {
1134 ModelAction *read = promise->get_action();
1135 read->read_from(write);
1136 if (read->is_rmw()) {
1137 mo_graph->addRMWEdge(write, read);
1139 //First fix up the modification order for actions that happened
1141 r_modification_order(read, write);
1142 //Next fix up the modification order for actions that happened
1144 post_r_modification_order(read, write);
1145 promises->erase(promises->begin() + promise_index);
1154 * Compute the set of promises that could potentially be satisfied by this
1155 * action. Note that the set computation actually appears in the Node, not in
1157 * @param curr The ModelAction that may satisfy promises
1159 void ModelChecker::compute_promises(ModelAction *curr)
1161 for (unsigned int i = 0; i < promises->size(); i++) {
1162 Promise *promise = (*promises)[i];
1163 const ModelAction *act = promise->get_action();
1164 if (!act->happens_before(curr) &&
1166 !act->is_synchronizing(curr) &&
1167 !act->same_thread(curr) &&
1168 promise->get_value() == curr->get_value()) {
1169 curr->get_node()->set_promise(i);
1174 /** Checks promises in response to change in ClockVector Threads. */
1175 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1177 for (unsigned int i = 0; i < promises->size(); i++) {
1178 Promise *promise = (*promises)[i];
1179 const ModelAction *act = promise->get_action();
1180 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1181 merge_cv->synchronized_since(act)) {
1182 //This thread is no longer able to send values back to satisfy the promise
1183 int num_synchronized_threads = promise->increment_threads();
1184 if (num_synchronized_threads == get_num_threads()) {
1185 //Promise has failed
1186 failed_promise = true;
1194 * Build up an initial set of all past writes that this 'read' action may read
1195 * from. This set is determined by the clock vector's "happens before"
1197 * @param curr is the current ModelAction that we are exploring; it must be a
1200 void ModelChecker::build_reads_from_past(ModelAction *curr)
1202 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1204 ASSERT(curr->is_read());
1206 ModelAction *last_seq_cst = NULL;
1208 /* Track whether this object has been initialized */
1209 bool initialized = false;
1211 if (curr->is_seqcst()) {
1212 last_seq_cst = get_last_seq_cst(curr->get_location());
1213 /* We have to at least see the last sequentially consistent write,
1214 so we are initialized. */
1215 if (last_seq_cst != NULL)
1219 /* Iterate over all threads */
1220 for (i = 0; i < thrd_lists->size(); i++) {
1221 /* Iterate over actions in thread, starting from most recent */
1222 action_list_t *list = &(*thrd_lists)[i];
1223 action_list_t::reverse_iterator rit;
1224 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1225 ModelAction *act = *rit;
1227 /* Only consider 'write' actions */
1228 if (!act->is_write())
1231 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1232 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1233 DEBUG("Adding action to may_read_from:\n");
1234 if (DBG_ENABLED()) {
1238 curr->get_node()->add_read_from(act);
1241 /* Include at most one act per-thread that "happens before" curr */
1242 if (act->happens_before(curr)) {
1250 /** @todo Need a more informative way of reporting errors. */
1251 printf("ERROR: may read from uninitialized atomic\n");
1254 if (DBG_ENABLED() || !initialized) {
1255 printf("Reached read action:\n");
1257 printf("Printing may_read_from\n");
1258 curr->get_node()->print_may_read_from();
1259 printf("End printing may_read_from\n");
1262 ASSERT(initialized);
1265 static void print_list(action_list_t *list)
1267 action_list_t::iterator it;
1269 printf("---------------------------------------------------------------------\n");
1272 for (it = list->begin(); it != list->end(); it++) {
1275 printf("---------------------------------------------------------------------\n");
1278 void ModelChecker::print_summary()
1281 printf("Number of executions: %d\n", num_executions);
1282 printf("Number of feasible executions: %d\n", num_feasible_executions);
1283 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1285 #if SUPPORT_MOD_ORDER_DUMP
1287 char buffername[100];
1288 sprintf(buffername, "exec%u",num_executions);
1289 mo_graph->dumpGraphToFile(buffername);
1292 if (!isfinalfeasible())
1293 printf("INFEASIBLE EXECUTION!\n");
1294 print_list(action_trace);
1299 * Add a Thread to the system for the first time. Should only be called once
1301 * @param t The Thread to add
1303 void ModelChecker::add_thread(Thread *t)
1305 thread_map->put(id_to_int(t->get_id()), t);
1306 scheduler->add_thread(t);
1309 void ModelChecker::remove_thread(Thread *t)
1311 scheduler->remove_thread(t);
1315 * Switch from a user-context to the "master thread" context (a.k.a. system
1316 * context). This switch is made with the intention of exploring a particular
1317 * model-checking action (described by a ModelAction object). Must be called
1318 * from a user-thread context.
1319 * @param act The current action that will be explored. Must not be NULL.
1320 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1322 int ModelChecker::switch_to_master(ModelAction *act)
1325 Thread *old = thread_current();
1326 set_current_action(act);
1327 old->set_state(THREAD_READY);
1328 return Thread::swap(old, &system_context);
1332 * Takes the next step in the execution, if possible.
1333 * @return Returns true (success) if a step was taken and false otherwise.
1335 bool ModelChecker::take_step() {
1339 Thread * curr = thread_current();
1341 if (curr->get_state() == THREAD_READY) {
1342 ASSERT(priv->current_action);
1344 priv->nextThread = check_current_action(priv->current_action);
1345 priv->current_action = NULL;
1346 if (curr->is_blocked() || curr->is_complete())
1347 scheduler->remove_thread(curr);
1352 Thread * next = scheduler->next_thread(priv->nextThread);
1354 /* Infeasible -> don't take any more steps */
1359 next->set_state(THREAD_RUNNING);
1360 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1362 /* next == NULL -> don't take any more steps */
1365 /* Return false only if swap fails with an error */
1366 return (Thread::swap(&system_context, next) == 0);
1369 /** Runs the current execution until threre are no more steps to take. */
1370 void ModelChecker::finish_execution() {
1373 while (take_step());