8 #include "snapshot-interface.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
16 #define INITIAL_THREAD_ID 0
20 /** @brief Constructor */
21 ModelChecker::ModelChecker(struct model_params params) :
22 /* Initialize default scheduler */
23 scheduler(new Scheduler()),
25 num_feasible_executions(0),
28 action_trace(new action_list_t()),
29 thread_map(new HashTable<int, Thread *, int>()),
30 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
31 lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
33 promises(new std::vector<Promise *>()),
34 futurevalues(new std::vector<struct PendingFutureValue>()),
35 lazy_sync_with_release(new HashTable<void *, action_list_t, uintptr_t, 4>()),
36 thrd_last_action(new std::vector<ModelAction *>(1)),
37 node_stack(new NodeStack()),
38 mo_graph(new CycleGraph()),
39 failed_promise(false),
40 too_many_reads(false),
43 /* Allocate this "size" on the snapshotting heap */
44 priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
45 /* First thread created will have id INITIAL_THREAD_ID */
46 priv->next_thread_id = INITIAL_THREAD_ID;
48 lazy_sync_size = &priv->lazy_sync_size;
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
54 for (int i = 0; i < get_num_threads(); i++)
55 delete thread_map->get(i);
60 delete lock_waiters_map;
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 return priv->next_thread_id++;
95 /** @returns the number of user threads created during this execution */
96 int ModelChecker::get_num_threads()
98 return priv->next_thread_id;
101 /** @returns a sequence number for a new ModelAction */
102 modelclock_t ModelChecker::get_next_seq_num()
104 return ++priv->used_sequence_numbers;
108 * @brief Choose the next thread to execute.
110 * This function chooses the next thread that should execute. It can force the
111 * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
112 * followed by a THREAD_START, or it can enforce execution replay/backtracking.
113 * The model-checker may have no preference regarding the next thread (i.e.,
114 * when exploring a new execution ordering), in which case this will return
116 * @param curr The current ModelAction. This action might guide the choice of
118 * @return The next thread to run. If the model-checker has no preference, NULL.
120 Thread * ModelChecker::get_next_thread(ModelAction *curr)
125 /* Do not split atomic actions. */
127 return thread_current();
128 /* The THREAD_CREATE action points to the created Thread */
129 else if (curr->get_type() == THREAD_CREATE)
130 return (Thread *)curr->get_location();
133 /* Have we completed exploring the preselected path? */
137 /* Else, we are trying to replay an execution */
138 ModelAction *next = node_stack->get_next()->get_action();
140 if (next == diverge) {
141 Node *nextnode = next->get_node();
142 /* Reached divergence point */
143 if (nextnode->increment_promise()) {
144 /* The next node will try to satisfy a different set of promises. */
145 tid = next->get_tid();
146 node_stack->pop_restofstack(2);
147 } else if (nextnode->increment_read_from()) {
148 /* The next node will read from a different value. */
149 tid = next->get_tid();
150 node_stack->pop_restofstack(2);
151 } else if (nextnode->increment_future_value()) {
152 /* The next node will try to read from a different future value. */
153 tid = next->get_tid();
154 node_stack->pop_restofstack(2);
156 /* Make a different thread execute for next step */
157 Node *node = nextnode->get_parent();
158 tid = node->get_next_backtrack();
159 node_stack->pop_restofstack(1);
161 DEBUG("*** Divergence point ***\n");
164 tid = next->get_tid();
166 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
167 ASSERT(tid != THREAD_ID_T_NONE);
168 return thread_map->get(id_to_int(tid));
172 * Queries the model-checker for more executions to explore and, if one
173 * exists, resets the model-checker state to execute a new execution.
175 * @return If there are more executions to explore, return true. Otherwise,
178 bool ModelChecker::next_execution()
183 if (isfinalfeasible())
184 num_feasible_executions++;
186 if (isfinalfeasible() || DBG_ENABLED())
189 if ((diverge = get_next_backtrack()) == NULL)
193 printf("Next execution will diverge at:\n");
197 reset_to_initial_state();
201 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
203 action_type type = act->get_type();
205 if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
206 /* linear search: from most recent to oldest */
207 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
208 action_list_t::reverse_iterator rit;
209 for (rit = list->rbegin(); rit != list->rend(); rit++) {
210 ModelAction *prev = *rit;
211 if (act->is_synchronizing(prev))
214 } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
215 /* linear search: from most recent to oldest */
216 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
217 action_list_t::reverse_iterator rit;
218 for (rit = list->rbegin(); rit != list->rend(); rit++) {
219 ModelAction *prev = *rit;
220 if (prev->is_success_lock())
223 } else if (type==ATOMIC_UNLOCK) {
224 /* linear search: from most recent to oldest */
225 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
226 action_list_t::reverse_iterator rit;
227 for (rit = list->rbegin(); rit != list->rend(); rit++) {
228 ModelAction *prev = *rit;
229 if (prev->is_failed_trylock())
236 void ModelChecker::set_backtracking(ModelAction *act)
240 Thread *t = get_thread(act);
242 prev = get_last_conflict(act);
246 node = prev->get_node()->get_parent();
248 while (!node->is_enabled(t))
251 /* Check if this has been explored already */
252 if (node->has_been_explored(t->get_id()))
255 /* Cache the latest backtracking point */
256 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
257 priv->next_backtrack = prev;
259 /* If this is a new backtracking point, mark the tree */
260 if (!node->set_backtrack(t->get_id()))
262 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
263 prev->get_tid(), t->get_id());
271 * Returns last backtracking point. The model checker will explore a different
272 * path for this point in the next execution.
273 * @return The ModelAction at which the next execution should diverge.
275 ModelAction * ModelChecker::get_next_backtrack()
277 ModelAction *next = priv->next_backtrack;
278 priv->next_backtrack = NULL;
283 * Processes a read or rmw model action.
284 * @param curr is the read model action to process.
285 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
286 * @return True if processing this read updates the mo_graph.
288 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
291 bool updated = false;
293 const ModelAction *reads_from = curr->get_node()->get_read_from();
294 if (reads_from != NULL) {
295 mo_graph->startChanges();
297 value = reads_from->get_value();
298 bool r_status = false;
300 if (!second_part_of_rmw) {
302 r_status = r_modification_order(curr, reads_from);
306 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
307 mo_graph->rollbackChanges();
308 too_many_reads = false;
312 curr->read_from(reads_from);
313 mo_graph->commitChanges();
315 } else if (!second_part_of_rmw) {
316 /* Read from future value */
317 value = curr->get_node()->get_future_value();
318 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
319 curr->read_from(NULL);
320 Promise *valuepromise = new Promise(curr, value, expiration);
321 promises->push_back(valuepromise);
323 get_thread(curr)->set_return_value(value);
328 void ModelChecker::process_mutex(ModelAction *curr) {
329 std::mutex * mutex=(std::mutex *) curr->get_location();
330 struct std::mutex_state * state=mutex->get_state();
331 switch(curr->get_type()) {
332 case ATOMIC_TRYLOCK: {
333 bool success=!state->islocked;
334 curr->set_try_lock(success);
338 //otherwise fall into the lock case
340 if (curr->get_cv()->getClock(state->alloc_tid)<=state->alloc_clock) {
341 printf("Lock access before initialization\n");
344 state->islocked=true;
345 ModelAction *unlock=get_last_unlock(curr);
346 //synchronize with the previous unlock statement
347 curr->synchronize_with(unlock);
350 case ATOMIC_UNLOCK: {
352 state->islocked=false;
353 //wake up the other threads
354 action_list_t * waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
355 //activate all the waiting threads
356 for(action_list_t::iterator rit = waiters->begin(); rit!=waiters->end(); rit++) {
357 add_thread(get_thread((*rit)->get_tid()));
369 * Process a write ModelAction
370 * @param curr The ModelAction to process
371 * @return True if the mo_graph was updated or promises were resolved
373 bool ModelChecker::process_write(ModelAction *curr)
375 bool updated_mod_order = w_modification_order(curr);
376 bool updated_promises = resolve_promises(curr);
378 if (promises->size() == 0) {
379 for (unsigned int i = 0; i<futurevalues->size(); i++) {
380 struct PendingFutureValue pfv = (*futurevalues)[i];
381 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
382 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
383 priv->next_backtrack = pfv.act;
385 futurevalues->resize(0);
388 mo_graph->commitChanges();
389 get_thread(curr)->set_return_value(VALUE_NONE);
390 return updated_mod_order || updated_promises;
394 * Initialize the current action by performing one or more of the following
395 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
396 * in the NodeStack, manipulating backtracking sets, allocating and
397 * initializing clock vectors, and computing the promises to fulfill.
399 * @param curr The current action, as passed from the user context; may be
400 * freed/invalidated after the execution of this function
401 * @return The current action, as processed by the ModelChecker. Is only the
402 * same as the parameter @a curr if this is a newly-explored action.
404 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
406 ModelAction *newcurr;
408 if (curr->is_rmwc() || curr->is_rmw()) {
409 newcurr = process_rmw(curr);
411 compute_promises(newcurr);
415 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
417 /* First restore type and order in case of RMW operation */
419 newcurr->copy_typeandorder(curr);
421 ASSERT(curr->get_location()==newcurr->get_location());
423 /* Discard duplicate ModelAction; use action from NodeStack */
426 /* If we have diverged, we need to reset the clock vector. */
428 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
432 * Perform one-time actions when pushing new ModelAction onto
435 curr->create_cv(get_parent_action(curr->get_tid()));
436 if (curr->is_write())
437 compute_promises(curr);
442 bool ModelChecker::check_action_enabled(ModelAction *curr) {
443 if (curr->is_lock()) {
444 std::mutex * lock=(std::mutex *) curr->get_location();
445 struct std::mutex_state * state = lock->get_state();
446 if (state->islocked) {
447 //Stick the action in the appropriate waiting queue
448 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
457 * This is the heart of the model checker routine. It performs model-checking
458 * actions corresponding to a given "current action." Among other processes, it
459 * calculates reads-from relationships, updates synchronization clock vectors,
460 * forms a memory_order constraints graph, and handles replay/backtrack
461 * execution when running permutations of previously-observed executions.
463 * @param curr The current action to process
464 * @return The next Thread that must be executed. May be NULL if ModelChecker
465 * makes no choice (e.g., according to replay execution, combining RMW actions,
468 Thread * ModelChecker::check_current_action(ModelAction *curr)
472 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
474 if (!check_action_enabled(curr)) {
475 //we'll make the execution look like we chose to run this action
476 //much later...when a lock is actually available to relese
477 remove_thread(get_current_thread());
478 get_current_thread()->set_pending(curr);
479 return get_next_thread(NULL);
482 ModelAction *newcurr = initialize_curr_action(curr);
484 /* Add the action to lists before any other model-checking tasks */
485 if (!second_part_of_rmw)
486 add_action_to_lists(newcurr);
488 /* Build may_read_from set for newly-created actions */
489 if (curr == newcurr && curr->is_read())
490 build_reads_from_past(curr);
493 /* Add the action to lists before any other model-checking tasks */
494 if (!second_part_of_rmw)
495 add_action_to_lists(newcurr);
497 /* Build may_read_from set for newly-created actions */
498 if (curr == newcurr && curr->is_read())
499 build_reads_from_past(curr);
502 /* Thread specific actions */
503 switch (curr->get_type()) {
504 case THREAD_CREATE: {
505 Thread *th = (Thread *)curr->get_location();
506 th->set_creation(curr);
510 Thread *waiting, *blocking;
511 waiting = get_thread(curr);
512 blocking = (Thread *)curr->get_location();
513 if (!blocking->is_complete()) {
514 blocking->push_wait_list(curr);
515 scheduler->sleep(waiting);
517 do_complete_join(curr);
521 case THREAD_FINISH: {
522 Thread *th = get_thread(curr);
523 while (!th->wait_list_empty()) {
524 ModelAction *act = th->pop_wait_list();
525 Thread *wake = get_thread(act);
526 scheduler->wake(wake);
527 do_complete_join(act);
533 check_promises(NULL, curr->get_cv());
540 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
542 while (!work_queue.empty()) {
543 WorkQueueEntry work = work_queue.front();
544 work_queue.pop_front();
547 case WORK_CHECK_CURR_ACTION: {
548 ModelAction *act = work.action;
549 bool updated = false;
550 if (act->is_read() && process_read(act, second_part_of_rmw))
553 if (act->is_write() && process_write(act))
556 if (act->is_mutex_op())
560 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
563 case WORK_CHECK_RELEASE_SEQ:
564 resolve_release_sequences(work.location, &work_queue);
566 case WORK_CHECK_MO_EDGES: {
567 /** @todo Complete verification of work_queue */
568 ModelAction *act = work.action;
569 bool updated = false;
571 if (act->is_read()) {
572 if (r_modification_order(act, act->get_reads_from()))
575 if (act->is_write()) {
576 if (w_modification_order(act))
581 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
590 check_curr_backtracking(curr);
592 set_backtracking(curr);
594 return get_next_thread(curr);
598 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
599 * operation from the Thread it is joining with. Must be called after the
600 * completion of the Thread in question.
601 * @param join The THREAD_JOIN action
603 void ModelChecker::do_complete_join(ModelAction *join)
605 Thread *blocking = (Thread *)join->get_location();
606 ModelAction *act = get_last_action(blocking->get_id());
607 join->synchronize_with(act);
610 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
611 Node *currnode = curr->get_node();
612 Node *parnode = currnode->get_parent();
614 if ((!parnode->backtrack_empty() ||
615 !currnode->read_from_empty() ||
616 !currnode->future_value_empty() ||
617 !currnode->promise_empty())
618 && (!priv->next_backtrack ||
619 *curr > *priv->next_backtrack)) {
620 priv->next_backtrack = curr;
624 bool ModelChecker::promises_expired() {
625 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
626 Promise *promise = (*promises)[promise_index];
627 if (promise->get_expiration()<priv->used_sequence_numbers) {
634 /** @returns whether the current partial trace must be a prefix of a
636 bool ModelChecker::isfeasibleprefix() {
637 return promises->size() == 0 && *lazy_sync_size == 0;
640 /** @returns whether the current partial trace is feasible. */
641 bool ModelChecker::isfeasible() {
642 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
645 /** @returns whether the current partial trace is feasible other than
646 * multiple RMW reading from the same store. */
647 bool ModelChecker::isfeasibleotherthanRMW() {
649 if (mo_graph->checkForCycles())
650 DEBUG("Infeasible: modification order cycles\n");
652 DEBUG("Infeasible: failed promise\n");
654 DEBUG("Infeasible: too many reads\n");
655 if (promises_expired())
656 DEBUG("Infeasible: promises expired\n");
658 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
661 /** Returns whether the current completed trace is feasible. */
662 bool ModelChecker::isfinalfeasible() {
663 if (DBG_ENABLED() && promises->size() != 0)
664 DEBUG("Infeasible: unrevolved promises\n");
666 return isfeasible() && promises->size() == 0;
669 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
670 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
671 int tid = id_to_int(act->get_tid());
672 ModelAction *lastread = get_last_action(tid);
673 lastread->process_rmw(act);
674 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
675 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
676 mo_graph->commitChanges();
682 * Checks whether a thread has read from the same write for too many times
683 * without seeing the effects of a later write.
686 * 1) there must a different write that we could read from that would satisfy the modification order,
687 * 2) we must have read from the same value in excess of maxreads times, and
688 * 3) that other write must have been in the reads_from set for maxreads times.
690 * If so, we decide that the execution is no longer feasible.
692 void ModelChecker::check_recency(ModelAction *curr) {
693 if (params.maxreads != 0) {
694 if (curr->get_node()->get_read_from_size() <= 1)
697 //Must make sure that execution is currently feasible... We could
698 //accidentally clear by rolling back
702 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
703 int tid = id_to_int(curr->get_tid());
706 if ((int)thrd_lists->size() <= tid)
709 action_list_t *list = &(*thrd_lists)[tid];
711 action_list_t::reverse_iterator rit = list->rbegin();
713 for (; (*rit) != curr; rit++)
715 /* go past curr now */
718 action_list_t::reverse_iterator ritcopy = rit;
719 //See if we have enough reads from the same value
721 for (; count < params.maxreads; rit++,count++) {
722 if (rit==list->rend())
724 ModelAction *act = *rit;
727 if (act->get_reads_from() != curr->get_reads_from())
729 if (act->get_node()->get_read_from_size() <= 1)
733 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
735 const ModelAction * write = curr->get_node()->get_read_from_at(i);
736 //Need a different write
737 if (write==curr->get_reads_from())
740 /* Test to see whether this is a feasible write to read from*/
741 mo_graph->startChanges();
742 r_modification_order(curr, write);
743 bool feasiblereadfrom = isfeasible();
744 mo_graph->rollbackChanges();
746 if (!feasiblereadfrom)
750 bool feasiblewrite = true;
751 //new we need to see if this write works for everyone
753 for (int loop = count; loop>0; loop--,rit++) {
754 ModelAction *act=*rit;
755 bool foundvalue = false;
756 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
757 if (act->get_node()->get_read_from_at(i)==write) {
763 feasiblewrite = false;
768 too_many_reads = true;
776 * Updates the mo_graph with the constraints imposed from the current
779 * Basic idea is the following: Go through each other thread and find
780 * the lastest action that happened before our read. Two cases:
782 * (1) The action is a write => that write must either occur before
783 * the write we read from or be the write we read from.
785 * (2) The action is a read => the write that that action read from
786 * must occur before the write we read from or be the same write.
788 * @param curr The current action. Must be a read.
789 * @param rf The action that curr reads from. Must be a write.
790 * @return True if modification order edges were added; false otherwise
792 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
794 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
797 ASSERT(curr->is_read());
799 /* Iterate over all threads */
800 for (i = 0; i < thrd_lists->size(); i++) {
801 /* Iterate over actions in thread, starting from most recent */
802 action_list_t *list = &(*thrd_lists)[i];
803 action_list_t::reverse_iterator rit;
804 for (rit = list->rbegin(); rit != list->rend(); rit++) {
805 ModelAction *act = *rit;
808 * Include at most one act per-thread that "happens
809 * before" curr. Don't consider reflexively.
811 if (act->happens_before(curr) && act != curr) {
812 if (act->is_write()) {
814 mo_graph->addEdge(act, rf);
818 const ModelAction *prevreadfrom = act->get_reads_from();
819 if (prevreadfrom != NULL && rf != prevreadfrom) {
820 mo_graph->addEdge(prevreadfrom, rf);
832 /** This method fixes up the modification order when we resolve a
833 * promises. The basic problem is that actions that occur after the
834 * read curr could not property add items to the modification order
837 * So for each thread, we find the earliest item that happens after
838 * the read curr. This is the item we have to fix up with additional
839 * constraints. If that action is write, we add a MO edge between
840 * the Action rf and that action. If the action is a read, we add a
841 * MO edge between the Action rf, and whatever the read accessed.
843 * @param curr is the read ModelAction that we are fixing up MO edges for.
844 * @param rf is the write ModelAction that curr reads from.
848 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
850 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
852 ASSERT(curr->is_read());
854 /* Iterate over all threads */
855 for (i = 0; i < thrd_lists->size(); i++) {
856 /* Iterate over actions in thread, starting from most recent */
857 action_list_t *list = &(*thrd_lists)[i];
858 action_list_t::reverse_iterator rit;
859 ModelAction *lastact = NULL;
861 /* Find last action that happens after curr */
862 for (rit = list->rbegin(); rit != list->rend(); rit++) {
863 ModelAction *act = *rit;
864 if (curr->happens_before(act)) {
870 /* Include at most one act per-thread that "happens before" curr */
871 if (lastact != NULL) {
872 if (lastact->is_read()) {
873 const ModelAction *postreadfrom = lastact->get_reads_from();
874 if (postreadfrom != NULL&&rf != postreadfrom)
875 mo_graph->addEdge(rf, postreadfrom);
876 } else if (rf != lastact) {
877 mo_graph->addEdge(rf, lastact);
885 * Updates the mo_graph with the constraints imposed from the current write.
887 * Basic idea is the following: Go through each other thread and find
888 * the lastest action that happened before our write. Two cases:
890 * (1) The action is a write => that write must occur before
893 * (2) The action is a read => the write that that action read from
894 * must occur before the current write.
896 * This method also handles two other issues:
898 * (I) Sequential Consistency: Making sure that if the current write is
899 * seq_cst, that it occurs after the previous seq_cst write.
901 * (II) Sending the write back to non-synchronizing reads.
903 * @param curr The current action. Must be a write.
904 * @return True if modification order edges were added; false otherwise
906 bool ModelChecker::w_modification_order(ModelAction *curr)
908 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
911 ASSERT(curr->is_write());
913 if (curr->is_seqcst()) {
914 /* We have to at least see the last sequentially consistent write,
915 so we are initialized. */
916 ModelAction *last_seq_cst = get_last_seq_cst(curr);
917 if (last_seq_cst != NULL) {
918 mo_graph->addEdge(last_seq_cst, curr);
923 /* Iterate over all threads */
924 for (i = 0; i < thrd_lists->size(); i++) {
925 /* Iterate over actions in thread, starting from most recent */
926 action_list_t *list = &(*thrd_lists)[i];
927 action_list_t::reverse_iterator rit;
928 for (rit = list->rbegin(); rit != list->rend(); rit++) {
929 ModelAction *act = *rit;
932 * If RMW, we already have all relevant edges,
933 * so just skip to next thread.
934 * If normal write, we need to look at earlier
935 * actions, so continue processing list.
944 * Include at most one act per-thread that "happens
947 if (act->happens_before(curr)) {
949 * Note: if act is RMW, just add edge:
951 * The following edge should be handled elsewhere:
952 * readfrom(act) --mo--> act
955 mo_graph->addEdge(act, curr);
956 else if (act->is_read() && act->get_reads_from() != NULL)
957 mo_graph->addEdge(act->get_reads_from(), curr);
960 } else if (act->is_read() && !act->is_synchronizing(curr) &&
961 !act->same_thread(curr)) {
962 /* We have an action that:
963 (1) did not happen before us
964 (2) is a read and we are a write
965 (3) cannot synchronize with us
966 (4) is in a different thread
968 that read could potentially read from our write.
970 if (thin_air_constraint_may_allow(curr, act)) {
972 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
973 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
974 futurevalues->push_back(pfv);
984 /** Arbitrary reads from the future are not allowed. Section 29.3
985 * part 9 places some constraints. This method checks one result of constraint
986 * constraint. Others require compiler support. */
988 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
989 if (!writer->is_rmw())
992 if (!reader->is_rmw())
995 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
998 if (search->get_tid() == reader->get_tid() &&
999 search->happens_before(reader))
1007 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1008 * The ModelAction under consideration is expected to be taking part in
1009 * release/acquire synchronization as an object of the "reads from" relation.
1010 * Note that this can only provide release sequence support for RMW chains
1011 * which do not read from the future, as those actions cannot be traced until
1012 * their "promise" is fulfilled. Similarly, we may not even establish the
1013 * presence of a release sequence with certainty, as some modification order
1014 * constraints may be decided further in the future. Thus, this function
1015 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1016 * and a boolean representing certainty.
1018 * @todo Finish lazy updating, when promises are fulfilled in the future
1019 * @param rf The action that might be part of a release sequence. Must be a
1021 * @param release_heads A pass-by-reference style return parameter. After
1022 * execution of this function, release_heads will contain the heads of all the
1023 * relevant release sequences, if any exists
1024 * @return true, if the ModelChecker is certain that release_heads is complete;
1027 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1030 /* read from future: need to settle this later */
1031 return false; /* incomplete */
1034 ASSERT(rf->is_write());
1036 if (rf->is_release())
1037 release_heads->push_back(rf);
1039 /* We need a RMW action that is both an acquire and release to stop */
1040 /** @todo Need to be smarter here... In the linux lock
1041 * example, this will run to the beginning of the program for
1043 if (rf->is_acquire() && rf->is_release())
1044 return true; /* complete */
1045 return release_seq_head(rf->get_reads_from(), release_heads);
1047 if (rf->is_release())
1048 return true; /* complete */
1050 /* else relaxed write; check modification order for contiguous subsequence
1051 * -> rf must be same thread as release */
1052 int tid = id_to_int(rf->get_tid());
1053 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1054 action_list_t *list = &(*thrd_lists)[tid];
1055 action_list_t::const_reverse_iterator rit;
1057 /* Find rf in the thread list */
1058 rit = std::find(list->rbegin(), list->rend(), rf);
1059 ASSERT(rit != list->rend());
1061 /* Find the last write/release */
1062 for (; rit != list->rend(); rit++)
1063 if ((*rit)->is_release())
1065 if (rit == list->rend()) {
1066 /* No write-release in this thread */
1067 return true; /* complete */
1069 ModelAction *release = *rit;
1071 ASSERT(rf->same_thread(release));
1073 bool certain = true;
1074 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1075 if (id_to_int(rf->get_tid()) == (int)i)
1077 list = &(*thrd_lists)[i];
1079 /* Can we ensure no future writes from this thread may break
1080 * the release seq? */
1081 bool future_ordered = false;
1083 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1084 const ModelAction *act = *rit;
1085 if (!act->is_write())
1087 /* Reach synchronization -> this thread is complete */
1088 if (act->happens_before(release))
1090 if (rf->happens_before(act)) {
1091 future_ordered = true;
1095 /* Check modification order */
1096 if (mo_graph->checkReachable(rf, act)) {
1097 /* rf --mo--> act */
1098 future_ordered = true;
1101 if (mo_graph->checkReachable(act, release))
1102 /* act --mo--> release */
1104 if (mo_graph->checkReachable(release, act) &&
1105 mo_graph->checkReachable(act, rf)) {
1106 /* release --mo-> act --mo--> rf */
1107 return true; /* complete */
1111 if (!future_ordered)
1112 return false; /* This thread is uncertain */
1116 release_heads->push_back(release);
1121 * A public interface for getting the release sequence head(s) with which a
1122 * given ModelAction must synchronize. This function only returns a non-empty
1123 * result when it can locate a release sequence head with certainty. Otherwise,
1124 * it may mark the internal state of the ModelChecker so that it will handle
1125 * the release sequence at a later time, causing @a act to update its
1126 * synchronization at some later point in execution.
1127 * @param act The 'acquire' action that may read from a release sequence
1128 * @param release_heads A pass-by-reference return parameter. Will be filled
1129 * with the head(s) of the release sequence(s), if they exists with certainty.
1130 * @see ModelChecker::release_seq_head
1132 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1134 const ModelAction *rf = act->get_reads_from();
1136 complete = release_seq_head(rf, release_heads);
1138 /* add act to 'lazy checking' list */
1139 action_list_t *list;
1140 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1141 list->push_back(act);
1142 (*lazy_sync_size)++;
1147 * Attempt to resolve all stashed operations that might synchronize with a
1148 * release sequence for a given location. This implements the "lazy" portion of
1149 * determining whether or not a release sequence was contiguous, since not all
1150 * modification order information is present at the time an action occurs.
1152 * @param location The location/object that should be checked for release
1153 * sequence resolutions
1154 * @param work_queue The work queue to which to add work items as they are
1156 * @return True if any updates occurred (new synchronization, new mo_graph
1159 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1161 action_list_t *list;
1162 list = lazy_sync_with_release->getptr(location);
1166 bool updated = false;
1167 action_list_t::iterator it = list->begin();
1168 while (it != list->end()) {
1169 ModelAction *act = *it;
1170 const ModelAction *rf = act->get_reads_from();
1171 rel_heads_list_t release_heads;
1173 complete = release_seq_head(rf, &release_heads);
1174 for (unsigned int i = 0; i < release_heads.size(); i++) {
1175 if (!act->has_synchronized_with(release_heads[i])) {
1177 act->synchronize_with(release_heads[i]);
1182 /* Re-check act for mo_graph edges */
1183 work_queue->push_back(MOEdgeWorkEntry(act));
1185 /* propagate synchronization to later actions */
1186 action_list_t::reverse_iterator it = action_trace->rbegin();
1187 while ((*it) != act) {
1188 ModelAction *propagate = *it;
1189 if (act->happens_before(propagate)) {
1190 propagate->synchronize_with(act);
1191 /* Re-check 'propagate' for mo_graph edges */
1192 work_queue->push_back(MOEdgeWorkEntry(propagate));
1197 it = list->erase(it);
1198 (*lazy_sync_size)--;
1203 // If we resolved promises or data races, see if we have realized a data race.
1204 if (checkDataRaces()) {
1212 * Performs various bookkeeping operations for the current ModelAction. For
1213 * instance, adds action to the per-object, per-thread action vector and to the
1214 * action trace list of all thread actions.
1216 * @param act is the ModelAction to add.
1218 void ModelChecker::add_action_to_lists(ModelAction *act)
1220 int tid = id_to_int(act->get_tid());
1221 action_trace->push_back(act);
1223 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1225 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1226 if (tid >= (int)vec->size())
1227 vec->resize(priv->next_thread_id);
1228 (*vec)[tid].push_back(act);
1230 if ((int)thrd_last_action->size() <= tid)
1231 thrd_last_action->resize(get_num_threads());
1232 (*thrd_last_action)[tid] = act;
1235 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1237 int threadid=id_to_int(tid);
1238 if (threadid<(int)thrd_last_action->size())
1239 return (*thrd_last_action)[id_to_int(tid)];
1245 * Gets the last memory_order_seq_cst write (in the total global sequence)
1246 * performed on a particular object (i.e., memory location), not including the
1248 * @param curr The current ModelAction; also denotes the object location to
1250 * @return The last seq_cst write
1252 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1254 void *location = curr->get_location();
1255 action_list_t *list = obj_map->get_safe_ptr(location);
1256 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1257 action_list_t::reverse_iterator rit;
1258 for (rit = list->rbegin(); rit != list->rend(); rit++)
1259 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1264 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr)
1266 void *location = curr->get_location();
1267 action_list_t *list = obj_map->get_safe_ptr(location);
1268 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1269 action_list_t::reverse_iterator rit;
1270 for (rit = list->rbegin(); rit != list->rend(); rit++)
1271 if ((*rit)->is_unlock())
1276 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1278 ModelAction *parent = get_last_action(tid);
1280 parent = get_thread(tid)->get_creation();
1285 * Returns the clock vector for a given thread.
1286 * @param tid The thread whose clock vector we want
1287 * @return Desired clock vector
1289 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1291 return get_parent_action(tid)->get_cv();
1295 * Resolve a set of Promises with a current write. The set is provided in the
1296 * Node corresponding to @a write.
1297 * @param write The ModelAction that is fulfilling Promises
1298 * @return True if promises were resolved; false otherwise
1300 bool ModelChecker::resolve_promises(ModelAction *write)
1302 bool resolved = false;
1304 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1305 Promise *promise = (*promises)[promise_index];
1306 if (write->get_node()->get_promise(i)) {
1307 ModelAction *read = promise->get_action();
1308 read->read_from(write);
1309 if (read->is_rmw()) {
1310 mo_graph->addRMWEdge(write, read);
1312 //First fix up the modification order for actions that happened
1314 r_modification_order(read, write);
1315 //Next fix up the modification order for actions that happened
1317 post_r_modification_order(read, write);
1318 promises->erase(promises->begin() + promise_index);
1327 * Compute the set of promises that could potentially be satisfied by this
1328 * action. Note that the set computation actually appears in the Node, not in
1330 * @param curr The ModelAction that may satisfy promises
1332 void ModelChecker::compute_promises(ModelAction *curr)
1334 for (unsigned int i = 0; i < promises->size(); i++) {
1335 Promise *promise = (*promises)[i];
1336 const ModelAction *act = promise->get_action();
1337 if (!act->happens_before(curr) &&
1339 !act->is_synchronizing(curr) &&
1340 !act->same_thread(curr) &&
1341 promise->get_value() == curr->get_value()) {
1342 curr->get_node()->set_promise(i);
1347 /** Checks promises in response to change in ClockVector Threads. */
1348 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1350 for (unsigned int i = 0; i < promises->size(); i++) {
1351 Promise *promise = (*promises)[i];
1352 const ModelAction *act = promise->get_action();
1353 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1354 merge_cv->synchronized_since(act)) {
1355 //This thread is no longer able to send values back to satisfy the promise
1356 int num_synchronized_threads = promise->increment_threads();
1357 if (num_synchronized_threads == get_num_threads()) {
1358 //Promise has failed
1359 failed_promise = true;
1367 * Build up an initial set of all past writes that this 'read' action may read
1368 * from. This set is determined by the clock vector's "happens before"
1370 * @param curr is the current ModelAction that we are exploring; it must be a
1373 void ModelChecker::build_reads_from_past(ModelAction *curr)
1375 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1377 ASSERT(curr->is_read());
1379 ModelAction *last_seq_cst = NULL;
1381 /* Track whether this object has been initialized */
1382 bool initialized = false;
1384 if (curr->is_seqcst()) {
1385 last_seq_cst = get_last_seq_cst(curr);
1386 /* We have to at least see the last sequentially consistent write,
1387 so we are initialized. */
1388 if (last_seq_cst != NULL)
1392 /* Iterate over all threads */
1393 for (i = 0; i < thrd_lists->size(); i++) {
1394 /* Iterate over actions in thread, starting from most recent */
1395 action_list_t *list = &(*thrd_lists)[i];
1396 action_list_t::reverse_iterator rit;
1397 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1398 ModelAction *act = *rit;
1400 /* Only consider 'write' actions */
1401 if (!act->is_write() || act == curr)
1404 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1405 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1406 DEBUG("Adding action to may_read_from:\n");
1407 if (DBG_ENABLED()) {
1411 curr->get_node()->add_read_from(act);
1414 /* Include at most one act per-thread that "happens before" curr */
1415 if (act->happens_before(curr)) {
1423 /** @todo Need a more informative way of reporting errors. */
1424 printf("ERROR: may read from uninitialized atomic\n");
1427 if (DBG_ENABLED() || !initialized) {
1428 printf("Reached read action:\n");
1430 printf("Printing may_read_from\n");
1431 curr->get_node()->print_may_read_from();
1432 printf("End printing may_read_from\n");
1435 ASSERT(initialized);
1438 static void print_list(action_list_t *list)
1440 action_list_t::iterator it;
1442 printf("---------------------------------------------------------------------\n");
1445 for (it = list->begin(); it != list->end(); it++) {
1448 printf("---------------------------------------------------------------------\n");
1451 void ModelChecker::print_summary()
1454 printf("Number of executions: %d\n", num_executions);
1455 printf("Number of feasible executions: %d\n", num_feasible_executions);
1456 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1458 #if SUPPORT_MOD_ORDER_DUMP
1460 char buffername[100];
1461 sprintf(buffername, "exec%u",num_executions);
1462 mo_graph->dumpGraphToFile(buffername);
1465 if (!isfinalfeasible())
1466 printf("INFEASIBLE EXECUTION!\n");
1467 print_list(action_trace);
1472 * Add a Thread to the system for the first time. Should only be called once
1474 * @param t The Thread to add
1476 void ModelChecker::add_thread(Thread *t)
1478 thread_map->put(id_to_int(t->get_id()), t);
1479 scheduler->add_thread(t);
1482 void ModelChecker::remove_thread(Thread *t)
1484 scheduler->remove_thread(t);
1488 * Switch from a user-context to the "master thread" context (a.k.a. system
1489 * context). This switch is made with the intention of exploring a particular
1490 * model-checking action (described by a ModelAction object). Must be called
1491 * from a user-thread context.
1492 * @param act The current action that will be explored. Must not be NULL.
1493 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1495 int ModelChecker::switch_to_master(ModelAction *act)
1498 Thread *old = thread_current();
1499 set_current_action(act);
1500 old->set_state(THREAD_READY);
1501 return Thread::swap(old, &system_context);
1505 * Takes the next step in the execution, if possible.
1506 * @return Returns true (success) if a step was taken and false otherwise.
1508 bool ModelChecker::take_step() {
1512 Thread * curr = thread_current();
1514 if (curr->get_state() == THREAD_READY) {
1515 ASSERT(priv->current_action);
1517 priv->nextThread = check_current_action(priv->current_action);
1518 priv->current_action = NULL;
1519 if (curr->is_blocked() || curr->is_complete())
1520 scheduler->remove_thread(curr);
1525 Thread * next = scheduler->next_thread(priv->nextThread);
1527 /* Infeasible -> don't take any more steps */
1532 next->set_state(THREAD_RUNNING);
1533 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1535 /* next == NULL -> don't take any more steps */
1539 if ( next->get_pending() != NULL ) {
1540 //restart a pending action
1541 set_current_action(next->get_pending());
1542 next->set_pending(NULL);
1543 next->set_state(THREAD_READY);
1547 /* Return false only if swap fails with an error */
1548 return (Thread::swap(&system_context, next) == 0);
1551 /** Runs the current execution until threre are no more steps to take. */
1552 void ModelChecker::finish_execution() {
1555 while (take_step());