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 switch (act->get_type()) {
207 /* linear search: from most recent to oldest */
208 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
209 action_list_t::reverse_iterator rit;
210 for (rit = list->rbegin(); rit != list->rend(); rit++) {
211 ModelAction *prev = *rit;
212 if (act->is_synchronizing(prev))
218 case 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 (act->is_conflicting_lock(prev))
229 case ATOMIC_UNLOCK: {
230 /* linear search: from most recent to oldest */
231 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
232 action_list_t::reverse_iterator rit;
233 for (rit = list->rbegin(); rit != list->rend(); rit++) {
234 ModelAction *prev = *rit;
235 if (!act->same_thread(prev)&&prev->is_failed_trylock())
246 void ModelChecker::set_backtracking(ModelAction *act)
248 Thread *t = get_thread(act);
249 ModelAction * prev = get_last_conflict(act);
253 Node * node = prev->get_node()->get_parent();
255 int low_tid, high_tid;
256 if (node->is_enabled(t)) {
257 low_tid=id_to_int(act->get_tid());
261 high_tid=get_num_threads();
264 for(int i=low_tid;i<high_tid;i++) {
265 thread_id_t tid=int_to_id(i);
266 if (!node->is_enabled(tid))
269 /* Check if this has been explored already */
270 if (node->has_been_explored(tid))
273 /* Cache the latest backtracking point */
274 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
275 priv->next_backtrack = prev;
277 /* If this is a new backtracking point, mark the tree */
278 if (!node->set_backtrack(tid))
280 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
281 prev->get_tid(), t->get_id());
290 * Returns last backtracking point. The model checker will explore a different
291 * path for this point in the next execution.
292 * @return The ModelAction at which the next execution should diverge.
294 ModelAction * ModelChecker::get_next_backtrack()
296 ModelAction *next = priv->next_backtrack;
297 priv->next_backtrack = NULL;
302 * Processes a read or rmw model action.
303 * @param curr is the read model action to process.
304 * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
305 * @return True if processing this read updates the mo_graph.
307 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
310 bool updated = false;
312 const ModelAction *reads_from = curr->get_node()->get_read_from();
313 if (reads_from != NULL) {
314 mo_graph->startChanges();
316 value = reads_from->get_value();
317 bool r_status = false;
319 if (!second_part_of_rmw) {
321 r_status = r_modification_order(curr, reads_from);
325 if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
326 mo_graph->rollbackChanges();
327 too_many_reads = false;
331 curr->read_from(reads_from);
332 mo_graph->commitChanges();
334 } else if (!second_part_of_rmw) {
335 /* Read from future value */
336 value = curr->get_node()->get_future_value();
337 modelclock_t expiration = curr->get_node()->get_future_value_expiration();
338 curr->read_from(NULL);
339 Promise *valuepromise = new Promise(curr, value, expiration);
340 promises->push_back(valuepromise);
342 get_thread(curr)->set_return_value(value);
347 void ModelChecker::process_mutex(ModelAction *curr) {
348 std::mutex * mutex=(std::mutex *) curr->get_location();
349 struct std::mutex_state * state=mutex->get_state();
350 switch(curr->get_type()) {
351 case ATOMIC_TRYLOCK: {
352 bool success=!state->islocked;
353 curr->set_try_lock(success);
355 get_thread(curr)->set_return_value(0);
358 get_thread(curr)->set_return_value(1);
360 //otherwise fall into the lock case
362 if (curr->get_cv()->getClock(state->alloc_tid)<=state->alloc_clock) {
363 printf("Lock access before initialization\n");
366 state->islocked=true;
367 ModelAction *unlock=get_last_unlock(curr);
368 //synchronize with the previous unlock statement
369 if ( unlock != NULL )
370 curr->synchronize_with(unlock);
373 case ATOMIC_UNLOCK: {
375 state->islocked=false;
376 //wake up the other threads
377 action_list_t * waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
378 //activate all the waiting threads
379 for(action_list_t::iterator rit = waiters->begin(); rit!=waiters->end(); rit++) {
380 add_thread(get_thread((*rit)->get_tid()));
392 * Process a write ModelAction
393 * @param curr The ModelAction to process
394 * @return True if the mo_graph was updated or promises were resolved
396 bool ModelChecker::process_write(ModelAction *curr)
398 bool updated_mod_order = w_modification_order(curr);
399 bool updated_promises = resolve_promises(curr);
401 if (promises->size() == 0) {
402 for (unsigned int i = 0; i<futurevalues->size(); i++) {
403 struct PendingFutureValue pfv = (*futurevalues)[i];
404 if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
405 (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
406 priv->next_backtrack = pfv.act;
408 futurevalues->resize(0);
411 mo_graph->commitChanges();
412 get_thread(curr)->set_return_value(VALUE_NONE);
413 return updated_mod_order || updated_promises;
417 * Initialize the current action by performing one or more of the following
418 * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
419 * in the NodeStack, manipulating backtracking sets, allocating and
420 * initializing clock vectors, and computing the promises to fulfill.
422 * @param curr The current action, as passed from the user context; may be
423 * freed/invalidated after the execution of this function
424 * @return The current action, as processed by the ModelChecker. Is only the
425 * same as the parameter @a curr if this is a newly-explored action.
427 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
429 ModelAction *newcurr;
431 if (curr->is_rmwc() || curr->is_rmw()) {
432 newcurr = process_rmw(curr);
434 compute_promises(newcurr);
438 newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
440 /* First restore type and order in case of RMW operation */
442 newcurr->copy_typeandorder(curr);
444 ASSERT(curr->get_location()==newcurr->get_location());
445 newcurr->copy_from_new(curr);
447 /* Discard duplicate ModelAction; use action from NodeStack */
450 /* If we have diverged, we need to reset the clock vector. */
452 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
456 * Perform one-time actions when pushing new ModelAction onto
459 curr->create_cv(get_parent_action(curr->get_tid()));
460 if (curr->is_write())
461 compute_promises(curr);
466 bool ModelChecker::check_action_enabled(ModelAction *curr) {
467 if (curr->is_lock()) {
468 std::mutex * lock=(std::mutex *) curr->get_location();
469 struct std::mutex_state * state = lock->get_state();
470 if (state->islocked) {
471 //Stick the action in the appropriate waiting queue
472 lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
481 * This is the heart of the model checker routine. It performs model-checking
482 * actions corresponding to a given "current action." Among other processes, it
483 * calculates reads-from relationships, updates synchronization clock vectors,
484 * forms a memory_order constraints graph, and handles replay/backtrack
485 * execution when running permutations of previously-observed executions.
487 * @param curr The current action to process
488 * @return The next Thread that must be executed. May be NULL if ModelChecker
489 * makes no choice (e.g., according to replay execution, combining RMW actions,
492 Thread * ModelChecker::check_current_action(ModelAction *curr)
496 bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
498 if (!check_action_enabled(curr)) {
499 //we'll make the execution look like we chose to run this action
500 //much later...when a lock is actually available to relese
501 get_current_thread()->set_pending(curr);
502 remove_thread(get_current_thread());
503 return get_next_thread(NULL);
506 ModelAction *newcurr = initialize_curr_action(curr);
508 /* Add the action to lists before any other model-checking tasks */
509 if (!second_part_of_rmw)
510 add_action_to_lists(newcurr);
512 /* Build may_read_from set for newly-created actions */
513 if (curr == newcurr && curr->is_read())
514 build_reads_from_past(curr);
517 /* Thread specific actions */
518 switch (curr->get_type()) {
519 case THREAD_CREATE: {
520 Thread *th = (Thread *)curr->get_location();
521 th->set_creation(curr);
525 Thread *waiting, *blocking;
526 waiting = get_thread(curr);
527 blocking = (Thread *)curr->get_location();
528 if (!blocking->is_complete()) {
529 blocking->push_wait_list(curr);
530 scheduler->sleep(waiting);
532 do_complete_join(curr);
536 case THREAD_FINISH: {
537 Thread *th = get_thread(curr);
538 while (!th->wait_list_empty()) {
539 ModelAction *act = th->pop_wait_list();
540 Thread *wake = get_thread(act);
541 scheduler->wake(wake);
542 do_complete_join(act);
548 check_promises(NULL, curr->get_cv());
555 work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
557 while (!work_queue.empty()) {
558 WorkQueueEntry work = work_queue.front();
559 work_queue.pop_front();
562 case WORK_CHECK_CURR_ACTION: {
563 ModelAction *act = work.action;
564 bool updated = false;
565 if (act->is_read() && process_read(act, second_part_of_rmw))
568 if (act->is_write() && process_write(act))
571 if (act->is_mutex_op())
575 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
578 case WORK_CHECK_RELEASE_SEQ:
579 resolve_release_sequences(work.location, &work_queue);
581 case WORK_CHECK_MO_EDGES: {
582 /** @todo Complete verification of work_queue */
583 ModelAction *act = work.action;
584 bool updated = false;
586 if (act->is_read()) {
587 if (r_modification_order(act, act->get_reads_from()))
590 if (act->is_write()) {
591 if (w_modification_order(act))
596 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
605 check_curr_backtracking(curr);
607 set_backtracking(curr);
609 return get_next_thread(curr);
613 * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
614 * operation from the Thread it is joining with. Must be called after the
615 * completion of the Thread in question.
616 * @param join The THREAD_JOIN action
618 void ModelChecker::do_complete_join(ModelAction *join)
620 Thread *blocking = (Thread *)join->get_location();
621 ModelAction *act = get_last_action(blocking->get_id());
622 join->synchronize_with(act);
625 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
626 Node *currnode = curr->get_node();
627 Node *parnode = currnode->get_parent();
629 if ((!parnode->backtrack_empty() ||
630 !currnode->read_from_empty() ||
631 !currnode->future_value_empty() ||
632 !currnode->promise_empty())
633 && (!priv->next_backtrack ||
634 *curr > *priv->next_backtrack)) {
635 priv->next_backtrack = curr;
639 bool ModelChecker::promises_expired() {
640 for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
641 Promise *promise = (*promises)[promise_index];
642 if (promise->get_expiration()<priv->used_sequence_numbers) {
649 /** @returns whether the current partial trace must be a prefix of a
651 bool ModelChecker::isfeasibleprefix() {
652 return promises->size() == 0 && *lazy_sync_size == 0;
655 /** @returns whether the current partial trace is feasible. */
656 bool ModelChecker::isfeasible() {
657 return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
660 /** @returns whether the current partial trace is feasible other than
661 * multiple RMW reading from the same store. */
662 bool ModelChecker::isfeasibleotherthanRMW() {
664 if (mo_graph->checkForCycles())
665 DEBUG("Infeasible: modification order cycles\n");
667 DEBUG("Infeasible: failed promise\n");
669 DEBUG("Infeasible: too many reads\n");
670 if (promises_expired())
671 DEBUG("Infeasible: promises expired\n");
673 return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
676 /** Returns whether the current completed trace is feasible. */
677 bool ModelChecker::isfinalfeasible() {
678 if (DBG_ENABLED() && promises->size() != 0)
679 DEBUG("Infeasible: unrevolved promises\n");
681 return isfeasible() && promises->size() == 0;
684 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
685 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
686 int tid = id_to_int(act->get_tid());
687 ModelAction *lastread = get_last_action(tid);
688 lastread->process_rmw(act);
689 if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
690 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
691 mo_graph->commitChanges();
697 * Checks whether a thread has read from the same write for too many times
698 * without seeing the effects of a later write.
701 * 1) there must a different write that we could read from that would satisfy the modification order,
702 * 2) we must have read from the same value in excess of maxreads times, and
703 * 3) that other write must have been in the reads_from set for maxreads times.
705 * If so, we decide that the execution is no longer feasible.
707 void ModelChecker::check_recency(ModelAction *curr) {
708 if (params.maxreads != 0) {
709 if (curr->get_node()->get_read_from_size() <= 1)
712 //Must make sure that execution is currently feasible... We could
713 //accidentally clear by rolling back
717 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
718 int tid = id_to_int(curr->get_tid());
721 if ((int)thrd_lists->size() <= tid)
724 action_list_t *list = &(*thrd_lists)[tid];
726 action_list_t::reverse_iterator rit = list->rbegin();
728 for (; (*rit) != curr; rit++)
730 /* go past curr now */
733 action_list_t::reverse_iterator ritcopy = rit;
734 //See if we have enough reads from the same value
736 for (; count < params.maxreads; rit++,count++) {
737 if (rit==list->rend())
739 ModelAction *act = *rit;
742 if (act->get_reads_from() != curr->get_reads_from())
744 if (act->get_node()->get_read_from_size() <= 1)
748 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
750 const ModelAction * write = curr->get_node()->get_read_from_at(i);
751 //Need a different write
752 if (write==curr->get_reads_from())
755 /* Test to see whether this is a feasible write to read from*/
756 mo_graph->startChanges();
757 r_modification_order(curr, write);
758 bool feasiblereadfrom = isfeasible();
759 mo_graph->rollbackChanges();
761 if (!feasiblereadfrom)
765 bool feasiblewrite = true;
766 //new we need to see if this write works for everyone
768 for (int loop = count; loop>0; loop--,rit++) {
769 ModelAction *act=*rit;
770 bool foundvalue = false;
771 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
772 if (act->get_node()->get_read_from_at(i)==write) {
778 feasiblewrite = false;
783 too_many_reads = true;
791 * Updates the mo_graph with the constraints imposed from the current
794 * Basic idea is the following: Go through each other thread and find
795 * the lastest action that happened before our read. Two cases:
797 * (1) The action is a write => that write must either occur before
798 * the write we read from or be the write we read from.
800 * (2) The action is a read => the write that that action read from
801 * must occur before the write we read from or be the same write.
803 * @param curr The current action. Must be a read.
804 * @param rf The action that curr reads from. Must be a write.
805 * @return True if modification order edges were added; false otherwise
807 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
809 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
812 ASSERT(curr->is_read());
814 /* Iterate over all threads */
815 for (i = 0; i < thrd_lists->size(); i++) {
816 /* Iterate over actions in thread, starting from most recent */
817 action_list_t *list = &(*thrd_lists)[i];
818 action_list_t::reverse_iterator rit;
819 for (rit = list->rbegin(); rit != list->rend(); rit++) {
820 ModelAction *act = *rit;
823 * Include at most one act per-thread that "happens
824 * before" curr. Don't consider reflexively.
826 if (act->happens_before(curr) && act != curr) {
827 if (act->is_write()) {
829 mo_graph->addEdge(act, rf);
833 const ModelAction *prevreadfrom = act->get_reads_from();
834 if (prevreadfrom != NULL && rf != prevreadfrom) {
835 mo_graph->addEdge(prevreadfrom, rf);
847 /** This method fixes up the modification order when we resolve a
848 * promises. The basic problem is that actions that occur after the
849 * read curr could not property add items to the modification order
852 * So for each thread, we find the earliest item that happens after
853 * the read curr. This is the item we have to fix up with additional
854 * constraints. If that action is write, we add a MO edge between
855 * the Action rf and that action. If the action is a read, we add a
856 * MO edge between the Action rf, and whatever the read accessed.
858 * @param curr is the read ModelAction that we are fixing up MO edges for.
859 * @param rf is the write ModelAction that curr reads from.
863 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
865 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
867 ASSERT(curr->is_read());
869 /* Iterate over all threads */
870 for (i = 0; i < thrd_lists->size(); i++) {
871 /* Iterate over actions in thread, starting from most recent */
872 action_list_t *list = &(*thrd_lists)[i];
873 action_list_t::reverse_iterator rit;
874 ModelAction *lastact = NULL;
876 /* Find last action that happens after curr */
877 for (rit = list->rbegin(); rit != list->rend(); rit++) {
878 ModelAction *act = *rit;
879 if (curr->happens_before(act)) {
885 /* Include at most one act per-thread that "happens before" curr */
886 if (lastact != NULL) {
887 if (lastact->is_read()) {
888 const ModelAction *postreadfrom = lastact->get_reads_from();
889 if (postreadfrom != NULL&&rf != postreadfrom)
890 mo_graph->addEdge(rf, postreadfrom);
891 } else if (rf != lastact) {
892 mo_graph->addEdge(rf, lastact);
900 * Updates the mo_graph with the constraints imposed from the current write.
902 * Basic idea is the following: Go through each other thread and find
903 * the lastest action that happened before our write. Two cases:
905 * (1) The action is a write => that write must occur before
908 * (2) The action is a read => the write that that action read from
909 * must occur before the current write.
911 * This method also handles two other issues:
913 * (I) Sequential Consistency: Making sure that if the current write is
914 * seq_cst, that it occurs after the previous seq_cst write.
916 * (II) Sending the write back to non-synchronizing reads.
918 * @param curr The current action. Must be a write.
919 * @return True if modification order edges were added; false otherwise
921 bool ModelChecker::w_modification_order(ModelAction *curr)
923 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
926 ASSERT(curr->is_write());
928 if (curr->is_seqcst()) {
929 /* We have to at least see the last sequentially consistent write,
930 so we are initialized. */
931 ModelAction *last_seq_cst = get_last_seq_cst(curr);
932 if (last_seq_cst != NULL) {
933 mo_graph->addEdge(last_seq_cst, curr);
938 /* Iterate over all threads */
939 for (i = 0; i < thrd_lists->size(); i++) {
940 /* Iterate over actions in thread, starting from most recent */
941 action_list_t *list = &(*thrd_lists)[i];
942 action_list_t::reverse_iterator rit;
943 for (rit = list->rbegin(); rit != list->rend(); rit++) {
944 ModelAction *act = *rit;
947 * If RMW, we already have all relevant edges,
948 * so just skip to next thread.
949 * If normal write, we need to look at earlier
950 * actions, so continue processing list.
959 * Include at most one act per-thread that "happens
962 if (act->happens_before(curr)) {
964 * Note: if act is RMW, just add edge:
966 * The following edge should be handled elsewhere:
967 * readfrom(act) --mo--> act
970 mo_graph->addEdge(act, curr);
971 else if (act->is_read() && act->get_reads_from() != NULL)
972 mo_graph->addEdge(act->get_reads_from(), curr);
975 } else if (act->is_read() && !act->is_synchronizing(curr) &&
976 !act->same_thread(curr)) {
977 /* We have an action that:
978 (1) did not happen before us
979 (2) is a read and we are a write
980 (3) cannot synchronize with us
981 (4) is in a different thread
983 that read could potentially read from our write.
985 if (thin_air_constraint_may_allow(curr, act)) {
987 (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
988 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
989 futurevalues->push_back(pfv);
999 /** Arbitrary reads from the future are not allowed. Section 29.3
1000 * part 9 places some constraints. This method checks one result of constraint
1001 * constraint. Others require compiler support. */
1003 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1004 if (!writer->is_rmw())
1007 if (!reader->is_rmw())
1010 for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1013 if (search->get_tid() == reader->get_tid() &&
1014 search->happens_before(reader))
1022 * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1023 * The ModelAction under consideration is expected to be taking part in
1024 * release/acquire synchronization as an object of the "reads from" relation.
1025 * Note that this can only provide release sequence support for RMW chains
1026 * which do not read from the future, as those actions cannot be traced until
1027 * their "promise" is fulfilled. Similarly, we may not even establish the
1028 * presence of a release sequence with certainty, as some modification order
1029 * constraints may be decided further in the future. Thus, this function
1030 * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1031 * and a boolean representing certainty.
1033 * @todo Finish lazy updating, when promises are fulfilled in the future
1034 * @param rf The action that might be part of a release sequence. Must be a
1036 * @param release_heads A pass-by-reference style return parameter. After
1037 * execution of this function, release_heads will contain the heads of all the
1038 * relevant release sequences, if any exists
1039 * @return true, if the ModelChecker is certain that release_heads is complete;
1042 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1045 /* read from future: need to settle this later */
1046 return false; /* incomplete */
1049 ASSERT(rf->is_write());
1051 if (rf->is_release())
1052 release_heads->push_back(rf);
1054 /* We need a RMW action that is both an acquire and release to stop */
1055 /** @todo Need to be smarter here... In the linux lock
1056 * example, this will run to the beginning of the program for
1058 if (rf->is_acquire() && rf->is_release())
1059 return true; /* complete */
1060 return release_seq_head(rf->get_reads_from(), release_heads);
1062 if (rf->is_release())
1063 return true; /* complete */
1065 /* else relaxed write; check modification order for contiguous subsequence
1066 * -> rf must be same thread as release */
1067 int tid = id_to_int(rf->get_tid());
1068 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1069 action_list_t *list = &(*thrd_lists)[tid];
1070 action_list_t::const_reverse_iterator rit;
1072 /* Find rf in the thread list */
1073 rit = std::find(list->rbegin(), list->rend(), rf);
1074 ASSERT(rit != list->rend());
1076 /* Find the last write/release */
1077 for (; rit != list->rend(); rit++)
1078 if ((*rit)->is_release())
1080 if (rit == list->rend()) {
1081 /* No write-release in this thread */
1082 return true; /* complete */
1084 ModelAction *release = *rit;
1086 ASSERT(rf->same_thread(release));
1088 bool certain = true;
1089 for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1090 if (id_to_int(rf->get_tid()) == (int)i)
1092 list = &(*thrd_lists)[i];
1094 /* Can we ensure no future writes from this thread may break
1095 * the release seq? */
1096 bool future_ordered = false;
1098 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1099 const ModelAction *act = *rit;
1100 if (!act->is_write())
1102 /* Reach synchronization -> this thread is complete */
1103 if (act->happens_before(release))
1105 if (rf->happens_before(act)) {
1106 future_ordered = true;
1110 /* Check modification order */
1111 if (mo_graph->checkReachable(rf, act)) {
1112 /* rf --mo--> act */
1113 future_ordered = true;
1116 if (mo_graph->checkReachable(act, release))
1117 /* act --mo--> release */
1119 if (mo_graph->checkReachable(release, act) &&
1120 mo_graph->checkReachable(act, rf)) {
1121 /* release --mo-> act --mo--> rf */
1122 return true; /* complete */
1126 if (!future_ordered)
1127 return false; /* This thread is uncertain */
1131 release_heads->push_back(release);
1136 * A public interface for getting the release sequence head(s) with which a
1137 * given ModelAction must synchronize. This function only returns a non-empty
1138 * result when it can locate a release sequence head with certainty. Otherwise,
1139 * it may mark the internal state of the ModelChecker so that it will handle
1140 * the release sequence at a later time, causing @a act to update its
1141 * synchronization at some later point in execution.
1142 * @param act The 'acquire' action that may read from a release sequence
1143 * @param release_heads A pass-by-reference return parameter. Will be filled
1144 * with the head(s) of the release sequence(s), if they exists with certainty.
1145 * @see ModelChecker::release_seq_head
1147 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1149 const ModelAction *rf = act->get_reads_from();
1151 complete = release_seq_head(rf, release_heads);
1153 /* add act to 'lazy checking' list */
1154 action_list_t *list;
1155 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1156 list->push_back(act);
1157 (*lazy_sync_size)++;
1162 * Attempt to resolve all stashed operations that might synchronize with a
1163 * release sequence for a given location. This implements the "lazy" portion of
1164 * determining whether or not a release sequence was contiguous, since not all
1165 * modification order information is present at the time an action occurs.
1167 * @param location The location/object that should be checked for release
1168 * sequence resolutions
1169 * @param work_queue The work queue to which to add work items as they are
1171 * @return True if any updates occurred (new synchronization, new mo_graph
1174 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1176 action_list_t *list;
1177 list = lazy_sync_with_release->getptr(location);
1181 bool updated = false;
1182 action_list_t::iterator it = list->begin();
1183 while (it != list->end()) {
1184 ModelAction *act = *it;
1185 const ModelAction *rf = act->get_reads_from();
1186 rel_heads_list_t release_heads;
1188 complete = release_seq_head(rf, &release_heads);
1189 for (unsigned int i = 0; i < release_heads.size(); i++) {
1190 if (!act->has_synchronized_with(release_heads[i])) {
1192 act->synchronize_with(release_heads[i]);
1197 /* Re-check act for mo_graph edges */
1198 work_queue->push_back(MOEdgeWorkEntry(act));
1200 /* propagate synchronization to later actions */
1201 action_list_t::reverse_iterator it = action_trace->rbegin();
1202 while ((*it) != act) {
1203 ModelAction *propagate = *it;
1204 if (act->happens_before(propagate)) {
1205 propagate->synchronize_with(act);
1206 /* Re-check 'propagate' for mo_graph edges */
1207 work_queue->push_back(MOEdgeWorkEntry(propagate));
1212 it = list->erase(it);
1213 (*lazy_sync_size)--;
1218 // If we resolved promises or data races, see if we have realized a data race.
1219 if (checkDataRaces()) {
1227 * Performs various bookkeeping operations for the current ModelAction. For
1228 * instance, adds action to the per-object, per-thread action vector and to the
1229 * action trace list of all thread actions.
1231 * @param act is the ModelAction to add.
1233 void ModelChecker::add_action_to_lists(ModelAction *act)
1235 int tid = id_to_int(act->get_tid());
1236 action_trace->push_back(act);
1238 obj_map->get_safe_ptr(act->get_location())->push_back(act);
1240 std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1241 if (tid >= (int)vec->size())
1242 vec->resize(priv->next_thread_id);
1243 (*vec)[tid].push_back(act);
1245 if ((int)thrd_last_action->size() <= tid)
1246 thrd_last_action->resize(get_num_threads());
1247 (*thrd_last_action)[tid] = act;
1250 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1252 int threadid=id_to_int(tid);
1253 if (threadid<(int)thrd_last_action->size())
1254 return (*thrd_last_action)[id_to_int(tid)];
1260 * Gets the last memory_order_seq_cst write (in the total global sequence)
1261 * performed on a particular object (i.e., memory location), not including the
1263 * @param curr The current ModelAction; also denotes the object location to
1265 * @return The last seq_cst write
1267 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1269 void *location = curr->get_location();
1270 action_list_t *list = obj_map->get_safe_ptr(location);
1271 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1272 action_list_t::reverse_iterator rit;
1273 for (rit = list->rbegin(); rit != list->rend(); rit++)
1274 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1279 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr)
1281 void *location = curr->get_location();
1282 action_list_t *list = obj_map->get_safe_ptr(location);
1283 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1284 action_list_t::reverse_iterator rit;
1285 for (rit = list->rbegin(); rit != list->rend(); rit++)
1286 if ((*rit)->is_unlock())
1291 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1293 ModelAction *parent = get_last_action(tid);
1295 parent = get_thread(tid)->get_creation();
1300 * Returns the clock vector for a given thread.
1301 * @param tid The thread whose clock vector we want
1302 * @return Desired clock vector
1304 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1306 return get_parent_action(tid)->get_cv();
1310 * Resolve a set of Promises with a current write. The set is provided in the
1311 * Node corresponding to @a write.
1312 * @param write The ModelAction that is fulfilling Promises
1313 * @return True if promises were resolved; false otherwise
1315 bool ModelChecker::resolve_promises(ModelAction *write)
1317 bool resolved = false;
1319 for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1320 Promise *promise = (*promises)[promise_index];
1321 if (write->get_node()->get_promise(i)) {
1322 ModelAction *read = promise->get_action();
1323 read->read_from(write);
1324 if (read->is_rmw()) {
1325 mo_graph->addRMWEdge(write, read);
1327 //First fix up the modification order for actions that happened
1329 r_modification_order(read, write);
1330 //Next fix up the modification order for actions that happened
1332 post_r_modification_order(read, write);
1333 promises->erase(promises->begin() + promise_index);
1342 * Compute the set of promises that could potentially be satisfied by this
1343 * action. Note that the set computation actually appears in the Node, not in
1345 * @param curr The ModelAction that may satisfy promises
1347 void ModelChecker::compute_promises(ModelAction *curr)
1349 for (unsigned int i = 0; i < promises->size(); i++) {
1350 Promise *promise = (*promises)[i];
1351 const ModelAction *act = promise->get_action();
1352 if (!act->happens_before(curr) &&
1354 !act->is_synchronizing(curr) &&
1355 !act->same_thread(curr) &&
1356 promise->get_value() == curr->get_value()) {
1357 curr->get_node()->set_promise(i);
1362 /** Checks promises in response to change in ClockVector Threads. */
1363 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1365 for (unsigned int i = 0; i < promises->size(); i++) {
1366 Promise *promise = (*promises)[i];
1367 const ModelAction *act = promise->get_action();
1368 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1369 merge_cv->synchronized_since(act)) {
1370 //This thread is no longer able to send values back to satisfy the promise
1371 int num_synchronized_threads = promise->increment_threads();
1372 if (num_synchronized_threads == get_num_threads()) {
1373 //Promise has failed
1374 failed_promise = true;
1382 * Build up an initial set of all past writes that this 'read' action may read
1383 * from. This set is determined by the clock vector's "happens before"
1385 * @param curr is the current ModelAction that we are exploring; it must be a
1388 void ModelChecker::build_reads_from_past(ModelAction *curr)
1390 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1392 ASSERT(curr->is_read());
1394 ModelAction *last_seq_cst = NULL;
1396 /* Track whether this object has been initialized */
1397 bool initialized = false;
1399 if (curr->is_seqcst()) {
1400 last_seq_cst = get_last_seq_cst(curr);
1401 /* We have to at least see the last sequentially consistent write,
1402 so we are initialized. */
1403 if (last_seq_cst != NULL)
1407 /* Iterate over all threads */
1408 for (i = 0; i < thrd_lists->size(); i++) {
1409 /* Iterate over actions in thread, starting from most recent */
1410 action_list_t *list = &(*thrd_lists)[i];
1411 action_list_t::reverse_iterator rit;
1412 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1413 ModelAction *act = *rit;
1415 /* Only consider 'write' actions */
1416 if (!act->is_write() || act == curr)
1419 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1420 if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1421 DEBUG("Adding action to may_read_from:\n");
1422 if (DBG_ENABLED()) {
1426 curr->get_node()->add_read_from(act);
1429 /* Include at most one act per-thread that "happens before" curr */
1430 if (act->happens_before(curr)) {
1438 /** @todo Need a more informative way of reporting errors. */
1439 printf("ERROR: may read from uninitialized atomic\n");
1442 if (DBG_ENABLED() || !initialized) {
1443 printf("Reached read action:\n");
1445 printf("Printing may_read_from\n");
1446 curr->get_node()->print_may_read_from();
1447 printf("End printing may_read_from\n");
1450 ASSERT(initialized);
1453 static void print_list(action_list_t *list)
1455 action_list_t::iterator it;
1457 printf("---------------------------------------------------------------------\n");
1460 for (it = list->begin(); it != list->end(); it++) {
1463 printf("---------------------------------------------------------------------\n");
1466 void ModelChecker::print_summary()
1469 printf("Number of executions: %d\n", num_executions);
1470 printf("Number of feasible executions: %d\n", num_feasible_executions);
1471 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1473 #if SUPPORT_MOD_ORDER_DUMP
1475 char buffername[100];
1476 sprintf(buffername, "exec%u",num_executions);
1477 mo_graph->dumpGraphToFile(buffername);
1480 if (!isfinalfeasible())
1481 printf("INFEASIBLE EXECUTION!\n");
1482 print_list(action_trace);
1487 * Add a Thread to the system for the first time. Should only be called once
1489 * @param t The Thread to add
1491 void ModelChecker::add_thread(Thread *t)
1493 thread_map->put(id_to_int(t->get_id()), t);
1494 scheduler->add_thread(t);
1497 void ModelChecker::remove_thread(Thread *t)
1499 scheduler->remove_thread(t);
1503 * Switch from a user-context to the "master thread" context (a.k.a. system
1504 * context). This switch is made with the intention of exploring a particular
1505 * model-checking action (described by a ModelAction object). Must be called
1506 * from a user-thread context.
1507 * @param act The current action that will be explored. Must not be NULL.
1508 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1510 int ModelChecker::switch_to_master(ModelAction *act)
1513 Thread *old = thread_current();
1514 set_current_action(act);
1515 old->set_state(THREAD_READY);
1516 return Thread::swap(old, &system_context);
1520 * Takes the next step in the execution, if possible.
1521 * @return Returns true (success) if a step was taken and false otherwise.
1523 bool ModelChecker::take_step() {
1527 Thread * curr = thread_current();
1529 if (curr->get_state() == THREAD_READY) {
1530 ASSERT(priv->current_action);
1532 priv->nextThread = check_current_action(priv->current_action);
1533 priv->current_action = NULL;
1534 if (curr->is_blocked() || curr->is_complete())
1535 scheduler->remove_thread(curr);
1540 Thread * next = scheduler->next_thread(priv->nextThread);
1542 /* Infeasible -> don't take any more steps */
1547 next->set_state(THREAD_RUNNING);
1548 DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1550 /* next == NULL -> don't take any more steps */
1554 if ( next->get_pending() != NULL ) {
1555 //restart a pending action
1556 set_current_action(next->get_pending());
1557 next->set_pending(NULL);
1558 next->set_state(THREAD_READY);
1562 /* Return false only if swap fails with an error */
1563 return (Thread::swap(&system_context, next) == 0);
1566 /** Runs the current execution until threre are no more steps to take. */
1567 void ModelChecker::finish_execution() {
1570 while (take_step());