7 #include "snapshot-interface.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
13 #define INITIAL_THREAD_ID 0
17 /** @brief Constructor */
18 ModelChecker::ModelChecker() :
19 /* Initialize default scheduler */
20 scheduler(new Scheduler()),
21 /* First thread created will have id INITIAL_THREAD_ID */
22 next_thread_id(INITIAL_THREAD_ID),
23 used_sequence_numbers(0),
27 nextThread(THREAD_ID_T_NONE),
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 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
32 promises(new std::vector<Promise *>()),
33 thrd_last_action(new std::vector<ModelAction *>(1)),
34 node_stack(new NodeStack()),
36 cyclegraph(new CycleGraph()),
41 /** @brief Destructor */
42 ModelChecker::~ModelChecker()
44 for (int i = 0; i < get_num_threads(); i++)
45 delete thread_map->get(i);
51 delete thrd_last_action;
58 * Restores user program to initial state and resets all model-checker data
61 void ModelChecker::reset_to_initial_state()
63 DEBUG("+++ Resetting to initial state +++\n");
64 node_stack->reset_execution();
65 current_action = NULL;
66 next_thread_id = INITIAL_THREAD_ID;
67 used_sequence_numbers = 0;
69 next_backtrack = NULL;
70 failed_promise = false;
71 snapshotObject->backTrackBeforeStep(0);
74 /** @returns a thread ID for a new Thread */
75 thread_id_t ModelChecker::get_next_id()
77 return next_thread_id++;
80 /** @returns the number of user threads created during this execution */
81 int ModelChecker::get_num_threads()
83 return next_thread_id;
86 /** @returns a sequence number for a new ModelAction */
87 modelclock_t ModelChecker::get_next_seq_num()
89 return ++used_sequence_numbers;
93 * Performs the "scheduling" for the model-checker. That is, it checks if the
94 * model-checker has selected a "next thread to run" and returns it, if
95 * available. This function should be called from the Scheduler routine, where
96 * the Scheduler falls back to a default scheduling routine if needed.
98 * @return The next thread chosen by the model-checker. If the model-checker
99 * makes no selection, retuns NULL.
101 Thread * ModelChecker::schedule_next_thread()
104 if (nextThread == THREAD_ID_T_NONE)
106 t = thread_map->get(id_to_int(nextThread));
114 * Choose the next thread in the replay sequence.
116 * If the replay sequence has reached the 'diverge' point, returns a thread
117 * from the backtracking set. Otherwise, simply returns the next thread in the
118 * sequence that is being replayed.
120 thread_id_t ModelChecker::get_next_replay_thread()
124 /* Have we completed exploring the preselected path? */
126 return THREAD_ID_T_NONE;
128 /* Else, we are trying to replay an execution */
129 ModelAction * next = node_stack->get_next()->get_action();
131 if (next == diverge) {
132 Node *nextnode = next->get_node();
133 /* Reached divergence point */
134 if (nextnode->increment_promise()) {
135 /* The next node will try to satisfy a different set of promises. */
136 tid = next->get_tid();
137 node_stack->pop_restofstack(2);
138 } else if (nextnode->increment_read_from()) {
139 /* The next node will read from a different value. */
140 tid = next->get_tid();
141 node_stack->pop_restofstack(2);
142 } else if (nextnode->increment_future_value()) {
143 /* The next node will try to read from a different future value. */
144 tid = next->get_tid();
145 node_stack->pop_restofstack(2);
147 /* Make a different thread execute for next step */
148 Node *node = nextnode->get_parent();
149 tid = node->get_next_backtrack();
150 node_stack->pop_restofstack(1);
152 DEBUG("*** Divergence point ***\n");
155 tid = next->get_tid();
157 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
162 * Queries the model-checker for more executions to explore and, if one
163 * exists, resets the model-checker state to execute a new execution.
165 * @return If there are more executions to explore, return true. Otherwise,
168 bool ModelChecker::next_execution()
174 bool feasible = isfinalfeasible();
175 if (feasible || DBG_ENABLED())
176 print_summary(feasible);
178 if ((diverge = model->get_next_backtrack()) == NULL)
182 printf("Next execution will diverge at:\n");
186 model->reset_to_initial_state();
190 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
192 action_type type = act->get_type();
202 /* linear search: from most recent to oldest */
203 action_list_t *list = obj_map->ensureptr(act->get_location());
204 action_list_t::reverse_iterator rit;
205 for (rit = list->rbegin(); rit != list->rend(); rit++) {
206 ModelAction *prev = *rit;
207 if (act->is_synchronizing(prev))
213 void ModelChecker::set_backtracking(ModelAction *act)
217 Thread *t = get_thread(act->get_tid());
219 prev = get_last_conflict(act);
223 node = prev->get_node()->get_parent();
225 while (!node->is_enabled(t))
228 /* Check if this has been explored already */
229 if (node->has_been_explored(t->get_id()))
232 /* Cache the latest backtracking point */
233 if (!next_backtrack || *prev > *next_backtrack)
234 next_backtrack = prev;
236 /* If this is a new backtracking point, mark the tree */
237 if (!node->set_backtrack(t->get_id()))
239 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
240 prev->get_tid(), t->get_id());
248 * Returns last backtracking point. The model checker will explore a different
249 * path for this point in the next execution.
250 * @return The ModelAction at which the next execution should diverge.
252 ModelAction * ModelChecker::get_next_backtrack()
254 ModelAction *next = next_backtrack;
255 next_backtrack = NULL;
259 void ModelChecker::check_current_action(void)
261 ModelAction *curr = this->current_action;
262 bool already_added = false;
263 this->current_action = NULL;
265 DEBUG("trying to push NULL action...\n");
269 if (curr->is_rmwc() || curr->is_rmw()) {
270 ModelAction *tmp = process_rmw(curr);
271 already_added = true;
275 ModelAction * tmp = node_stack->explore_action(curr);
277 /* Discard duplicate ModelAction; use action from NodeStack */
278 /* First restore type and order in case of RMW operation */
280 tmp->copy_typeandorder(curr);
282 /* If we have diverged, we need to reset the clock vector. */
284 tmp->create_cv(get_parent_action(tmp->get_tid()));
290 * Perform one-time actions when pushing new ModelAction onto
293 curr->create_cv(get_parent_action(curr->get_tid()));
294 /* Build may_read_from set */
296 build_reads_from_past(curr);
297 if (curr->is_write())
298 compute_promises(curr);
302 /* Assign 'creation' parent */
303 if (curr->get_type() == THREAD_CREATE) {
304 Thread *th = (Thread *)curr->get_location();
305 th->set_creation(curr);
308 /* Deal with new thread */
309 if (curr->get_type() == THREAD_START)
310 check_promises(NULL, curr->get_cv());
312 /* Assign reads_from values */
313 Thread *th = get_thread(curr->get_tid());
314 uint64_t value = VALUE_NONE;
315 if (curr->is_read()) {
316 const ModelAction *reads_from = curr->get_node()->get_read_from();
317 if (reads_from != NULL) {
318 value = reads_from->get_value();
319 /* Assign reads_from, perform release/acquire synchronization */
320 curr->read_from(reads_from);
321 r_modification_order(curr,reads_from);
323 /* Read from future value */
324 value = curr->get_node()->get_future_value();
325 curr->read_from(NULL);
326 Promise * valuepromise = new Promise(curr, value);
327 promises->push_back(valuepromise);
329 } else if (curr->is_write()) {
330 w_modification_order(curr);
331 resolve_promises(curr);
334 th->set_return_value(value);
336 /* Add action to list. */
338 add_action_to_lists(curr);
340 /** @todo Is there a better interface for setting the next thread rather
341 than this field/convoluted approach? Perhaps like just returning
344 /* Do not split atomic actions. */
346 nextThread = thread_current()->get_id();
348 nextThread = get_next_replay_thread();
350 Node *currnode = curr->get_node();
351 Node *parnode = currnode->get_parent();
353 if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
354 !currnode->future_value_empty() || !currnode->promise_empty())
355 if (!next_backtrack || *curr > *next_backtrack)
356 next_backtrack = curr;
358 set_backtracking(curr);
361 /** @returns whether the current partial trace is feasible. */
362 bool ModelChecker::isfeasible() {
363 return !cyclegraph->checkForCycles() && !failed_promise;
366 /** Returns whether the current completed trace is feasible. */
367 bool ModelChecker::isfinalfeasible() {
368 return isfeasible() && promises->size() == 0;
371 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
372 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
373 int tid = id_to_int(act->get_tid());
374 ModelAction *lastread = get_last_action(tid);
375 lastread->process_rmw(act);
377 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
382 * Updates the cyclegraph with the constraints imposed from the current read.
383 * @param curr The current action. Must be a read.
384 * @param rf The action that curr reads from. Must be a write.
386 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
387 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
389 ASSERT(curr->is_read());
391 /* Iterate over all threads */
392 for (i = 0; i < thrd_lists->size(); i++) {
393 /* Iterate over actions in thread, starting from most recent */
394 action_list_t *list = &(*thrd_lists)[i];
395 action_list_t::reverse_iterator rit;
396 for (rit = list->rbegin(); rit != list->rend(); rit++) {
397 ModelAction *act = *rit;
399 /* Include at most one act per-thread that "happens before" curr */
400 if (act->happens_before(curr)) {
401 if (act->is_read()) {
402 const ModelAction * prevreadfrom = act->get_reads_from();
403 if (prevreadfrom != NULL && rf != prevreadfrom)
404 cyclegraph->addEdge(rf, prevreadfrom);
405 } else if (rf != act) {
406 cyclegraph->addEdge(rf, act);
414 /** Updates the cyclegraph with the constraints imposed from the
416 void ModelChecker::post_r_modification_order(ModelAction * curr, const ModelAction *rf) {
417 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
419 ASSERT(curr->is_read());
421 /* Iterate over all threads */
422 for (i = 0; i < thrd_lists->size(); i++) {
423 /* Iterate over actions in thread, starting from most recent */
424 action_list_t *list = &(*thrd_lists)[i];
425 action_list_t::reverse_iterator rit;
426 ModelAction *lastact = NULL;
428 /* Find last action that happens after curr */
429 for (rit = list->rbegin(); rit != list->rend(); rit++) {
430 ModelAction *act = *rit;
431 if (curr->happens_before(act)) {
437 /* Include at most one act per-thread that "happens before" curr */
438 if (lastact != NULL) {
439 if (lastact->is_read()) {
440 const ModelAction * postreadfrom = lastact->get_reads_from();
441 if (postreadfrom != NULL&&rf != postreadfrom)
442 cyclegraph->addEdge(postreadfrom, rf);
443 } else if (rf != lastact) {
444 cyclegraph->addEdge(lastact, rf);
452 * Updates the cyclegraph with the constraints imposed from the current write.
453 * @param curr The current action. Must be a write.
455 void ModelChecker::w_modification_order(ModelAction * curr) {
456 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
458 ASSERT(curr->is_write());
460 if (curr->is_seqcst()) {
461 /* We have to at least see the last sequentially consistent write,
462 so we are initialized. */
463 ModelAction * last_seq_cst = get_last_seq_cst(curr->get_location());
464 if (last_seq_cst != NULL)
465 cyclegraph->addEdge(curr, last_seq_cst);
468 /* Iterate over all threads */
469 for (i = 0; i < thrd_lists->size(); i++) {
470 /* Iterate over actions in thread, starting from most recent */
471 action_list_t *list = &(*thrd_lists)[i];
472 action_list_t::reverse_iterator rit;
473 for (rit = list->rbegin(); rit != list->rend(); rit++) {
474 ModelAction *act = *rit;
476 /* Include at most one act per-thread that "happens before" curr */
477 if (act->happens_before(curr)) {
478 if (act->is_read()) {
479 cyclegraph->addEdge(curr, act->get_reads_from());
481 cyclegraph->addEdge(curr, act);
484 if (act->is_read()&&!act->is_synchronizing(curr)&&!act->same_thread(curr)) {
485 /* We have an action that:
486 (1) did not happen before us
487 (2) is a read and we are a write
488 (3) cannot synchronize with us
489 (4) is in a different thread
491 that read could potentially read from our write.
493 if (act->get_node()->add_future_value(curr->get_value())&&
494 (!next_backtrack || *act > * next_backtrack))
495 next_backtrack = act;
503 * Performs various bookkeeping operations for the current ModelAction. For
504 * instance, adds action to the per-object, per-thread action vector and to the
505 * action trace list of all thread actions.
507 * @param act is the ModelAction to add.
509 void ModelChecker::add_action_to_lists(ModelAction *act)
511 int tid = id_to_int(act->get_tid());
512 action_trace->push_back(act);
514 obj_map->ensureptr(act->get_location())->push_back(act);
516 std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
517 if (tid >= (int)vec->size())
518 vec->resize(next_thread_id);
519 (*vec)[tid].push_back(act);
521 if ((int)thrd_last_action->size() <= tid)
522 thrd_last_action->resize(get_num_threads());
523 (*thrd_last_action)[tid] = act;
526 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
528 int nthreads = get_num_threads();
529 if ((int)thrd_last_action->size() < nthreads)
530 thrd_last_action->resize(nthreads);
531 return (*thrd_last_action)[id_to_int(tid)];
535 * Gets the last memory_order_seq_cst action (in the total global sequence)
536 * performed on a particular object (i.e., memory location).
537 * @param location The object location to check
538 * @return The last seq_cst action performed
540 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
542 action_list_t *list = obj_map->ensureptr(location);
543 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
544 action_list_t::reverse_iterator rit;
545 for (rit = list->rbegin(); rit != list->rend(); rit++)
546 if ((*rit)->is_write() && (*rit)->is_seqcst())
551 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
553 ModelAction *parent = get_last_action(tid);
555 parent = get_thread(tid)->get_creation();
560 * Returns the clock vector for a given thread.
561 * @param tid The thread whose clock vector we want
562 * @return Desired clock vector
564 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
565 return get_parent_action(tid)->get_cv();
569 /** Resolve the given promises. */
571 void ModelChecker::resolve_promises(ModelAction *write) {
572 for (unsigned int i = 0, promise_index = 0;promise_index<promises->size(); i++) {
573 Promise * promise = (*promises)[promise_index];
574 if (write->get_node()->get_promise(i)) {
575 ModelAction * read = promise->get_action();
576 read->read_from(write);
577 r_modification_order(read, write);
578 post_r_modification_order(read, write);
579 promises->erase(promises->begin()+promise_index);
585 /** Compute the set of promises that could potentially be satisfied by
588 void ModelChecker::compute_promises(ModelAction *curr) {
589 for (unsigned int i = 0;i<promises->size();i++) {
590 Promise * promise = (*promises)[i];
591 const ModelAction * act = promise->get_action();
592 if (!act->happens_before(curr)&&
594 !act->is_synchronizing(curr)&&
595 !act->same_thread(curr)&&
596 promise->get_value() == curr->get_value()) {
597 curr->get_node()->set_promise(i);
602 /** Checks promises in response to change in ClockVector Threads. */
604 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
605 for (unsigned int i = 0;i<promises->size();i++) {
606 Promise * promise = (*promises)[i];
607 const ModelAction * act = promise->get_action();
608 if ((old_cv == NULL||!old_cv->synchronized_since(act))&&
609 merge_cv->synchronized_since(act)) {
610 //This thread is no longer able to send values back to satisfy the promise
611 int num_synchronized_threads = promise->increment_threads();
612 if (num_synchronized_threads == model->get_num_threads()) {
614 failed_promise = true;
622 * Build up an initial set of all past writes that this 'read' action may read
623 * from. This set is determined by the clock vector's "happens before"
625 * @param curr is the current ModelAction that we are exploring; it must be a
628 void ModelChecker::build_reads_from_past(ModelAction *curr)
630 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
632 ASSERT(curr->is_read());
634 ModelAction *last_seq_cst = NULL;
636 /* Track whether this object has been initialized */
637 bool initialized = false;
639 if (curr->is_seqcst()) {
640 last_seq_cst = get_last_seq_cst(curr->get_location());
641 /* We have to at least see the last sequentially consistent write,
642 so we are initialized. */
643 if (last_seq_cst != NULL)
647 /* Iterate over all threads */
648 for (i = 0; i < thrd_lists->size(); i++) {
649 /* Iterate over actions in thread, starting from most recent */
650 action_list_t *list = &(*thrd_lists)[i];
651 action_list_t::reverse_iterator rit;
652 for (rit = list->rbegin(); rit != list->rend(); rit++) {
653 ModelAction *act = *rit;
655 /* Only consider 'write' actions */
656 if (!act->is_write())
659 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
660 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
661 DEBUG("Adding action to may_read_from:\n");
666 curr->get_node()->add_read_from(act);
669 /* Include at most one act per-thread that "happens before" curr */
670 if (act->happens_before(curr)) {
678 /** @todo Need a more informative way of reporting errors. */
679 printf("ERROR: may read from uninitialized atomic\n");
682 if (DBG_ENABLED() || !initialized) {
683 printf("Reached read action:\n");
685 printf("Printing may_read_from\n");
686 curr->get_node()->print_may_read_from();
687 printf("End printing may_read_from\n");
693 static void print_list(action_list_t *list)
695 action_list_t::iterator it;
697 printf("---------------------------------------------------------------------\n");
700 for (it = list->begin(); it != list->end(); it++) {
703 printf("---------------------------------------------------------------------\n");
706 void ModelChecker::print_summary(bool feasible)
709 printf("Number of executions: %d\n", num_executions);
710 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
715 printf("INFEASIBLE EXECUTION!\n");
716 print_list(action_trace);
720 int ModelChecker::add_thread(Thread *t)
722 thread_map->put(id_to_int(t->get_id()), t);
723 scheduler->add_thread(t);
727 void ModelChecker::remove_thread(Thread *t)
729 scheduler->remove_thread(t);
733 * Switch from a user-context to the "master thread" context (a.k.a. system
734 * context). This switch is made with the intention of exploring a particular
735 * model-checking action (described by a ModelAction object). Must be called
736 * from a user-thread context.
737 * @param act The current action that will be explored. May be NULL, although
738 * there is little reason to switch to the model-checker without an action to
739 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
740 * yield control without performing any progress; see thrd_join()).
741 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
743 int ModelChecker::switch_to_master(ModelAction *act)
746 Thread * old = thread_current();
747 set_current_action(act);
748 old->set_state(THREAD_READY);
749 return Thread::swap(old, get_system_context());