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()
20 /* Initialize default scheduler */
21 scheduler(new Scheduler()),
22 /* First thread created will have id INITIAL_THREAD_ID */
23 next_thread_id(INITIAL_THREAD_ID),
24 used_sequence_numbers(0),
28 nextThread(THREAD_ID_T_NONE),
29 action_trace(new action_list_t()),
30 thread_map(new HashTable<int, Thread *, int>()),
31 obj_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 thrd_last_action(new std::vector<ModelAction *>(1)),
35 node_stack(new NodeStack()),
37 cyclegraph(new CycleGraph()),
42 /** @brief Destructor */
43 ModelChecker::~ModelChecker()
45 /* std::map<int, Thread *>::iterator it;
46 for (it = thread_map->begin(); it != thread_map->end(); it++)
47 delete (*it).second;*/
53 delete thrd_last_action;
60 * Restores user program to initial state and resets all model-checker data
63 void ModelChecker::reset_to_initial_state()
65 DEBUG("+++ Resetting to initial state +++\n");
66 node_stack->reset_execution();
67 current_action = NULL;
68 next_thread_id = INITIAL_THREAD_ID;
69 used_sequence_numbers = 0;
71 next_backtrack = NULL;
72 failed_promise = false;
73 snapshotObject->backTrackBeforeStep(0);
76 /** @returns a thread ID for a new Thread */
77 thread_id_t ModelChecker::get_next_id()
79 return next_thread_id++;
82 /** @returns the number of user threads created during this execution */
83 int ModelChecker::get_num_threads()
85 return next_thread_id;
88 /** @returns a sequence number for a new ModelAction */
89 modelclock_t ModelChecker::get_next_seq_num()
91 return ++used_sequence_numbers;
95 * Performs the "scheduling" for the model-checker. That is, it checks if the
96 * model-checker has selected a "next thread to run" and returns it, if
97 * available. This function should be called from the Scheduler routine, where
98 * the Scheduler falls back to a default scheduling routine if needed.
100 * @return The next thread chosen by the model-checker. If the model-checker
101 * makes no selection, retuns NULL.
103 Thread * ModelChecker::schedule_next_thread()
106 if (nextThread == THREAD_ID_T_NONE)
108 t = thread_map->get(id_to_int(nextThread));
116 * Choose the next thread in the replay sequence.
118 * If the replay sequence has reached the 'diverge' point, returns a thread
119 * from the backtracking set. Otherwise, simply returns the next thread in the
120 * sequence that is being replayed.
122 thread_id_t ModelChecker::get_next_replay_thread()
126 /* Have we completed exploring the preselected path? */
128 return THREAD_ID_T_NONE;
130 /* Else, we are trying to replay an execution */
131 ModelAction * next = node_stack->get_next()->get_action();
133 if (next == diverge) {
134 Node *nextnode = next->get_node();
135 /* Reached divergence point */
136 if (nextnode->increment_promises()) {
137 /* The next node will try to satisfy a different set of promises. */
138 tid = next->get_tid();
139 node_stack->pop_restofstack(2);
140 } else if (nextnode->increment_read_from()) {
141 /* The next node will read from a different value. */
142 tid = next->get_tid();
143 node_stack->pop_restofstack(2);
144 } else if (nextnode->increment_future_values()) {
145 /* The next node will try to read from a different future value. */
146 tid = next->get_tid();
147 node_stack->pop_restofstack(2);
149 /* Make a different thread execute for next step */
150 Node *node = nextnode->get_parent();
151 tid = node->get_next_backtrack();
152 node_stack->pop_restofstack(1);
154 DEBUG("*** Divergence point ***\n");
157 tid = next->get_tid();
159 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
164 * Queries the model-checker for more executions to explore and, if one
165 * exists, resets the model-checker state to execute a new execution.
167 * @return If there are more executions to explore, return true. Otherwise,
170 bool ModelChecker::next_execution()
176 if (isfinalfeasible() || DBG_ENABLED())
179 if ((diverge = model->get_next_backtrack()) == NULL)
183 printf("Next execution will diverge at:\n");
187 model->reset_to_initial_state();
191 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
193 action_type type = act->get_type();
203 /* linear search: from most recent to oldest */
204 action_list_t *list = obj_map->ensureptr(act->get_location());
205 action_list_t::reverse_iterator rit;
206 for (rit = list->rbegin(); rit != list->rend(); rit++) {
207 ModelAction *prev = *rit;
208 if (act->is_synchronizing(prev))
214 void ModelChecker::set_backtracking(ModelAction *act)
218 Thread *t = get_thread(act->get_tid());
220 prev = get_last_conflict(act);
224 node = prev->get_node()->get_parent();
226 while (!node->is_enabled(t))
229 /* Check if this has been explored already */
230 if (node->has_been_explored(t->get_id()))
233 /* Cache the latest backtracking point */
234 if (!next_backtrack || *prev > *next_backtrack)
235 next_backtrack = prev;
237 /* If this is a new backtracking point, mark the tree */
238 if (!node->set_backtrack(t->get_id()))
240 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
241 prev->get_tid(), t->get_id());
249 * Returns last backtracking point. The model checker will explore a different
250 * path for this point in the next execution.
251 * @return The ModelAction at which the next execution should diverge.
253 ModelAction * ModelChecker::get_next_backtrack()
255 ModelAction *next = next_backtrack;
256 next_backtrack = NULL;
260 void ModelChecker::check_current_action(void)
262 ModelAction *curr = this->current_action;
263 bool already_added = false;
264 this->current_action = NULL;
266 DEBUG("trying to push NULL action...\n");
270 if (curr->is_rmwc()||curr->is_rmw()) {
271 ModelAction *tmp=process_rmw(curr);
272 already_added = true;
276 ModelAction * tmp = node_stack->explore_action(curr);
278 /* Discard duplicate ModelAction; use action from NodeStack */
279 /* First restore type and order in case of RMW operation */
281 tmp->copy_typeandorder(curr);
283 /* If we have diverged, we need to reset the clock vector. */
285 tmp->create_cv(get_parent_action(tmp->get_tid()));
292 * Perform one-time actions when pushing new ModelAction onto
295 curr->create_cv(get_parent_action(curr->get_tid()));
296 /* Build may_read_from set */
298 build_reads_from_past(curr);
299 if (curr->is_write())
300 compute_promises(curr);
304 /* Assign 'creation' parent */
305 if (curr->get_type() == THREAD_CREATE) {
306 Thread *th = (Thread *)curr->get_location();
307 th->set_creation(curr);
310 /* Deal with new thread */
311 if (curr->get_type() == THREAD_START) {
312 check_promises(NULL, curr->get_cv());
315 /* Assign reads_from values */
316 Thread *th = get_thread(curr->get_tid());
317 uint64_t value = VALUE_NONE;
318 if (curr->is_read()) {
319 const ModelAction *reads_from = curr->get_node()->get_read_from();
320 if (reads_from!=NULL) {
321 value = reads_from->get_value();
322 /* Assign reads_from, perform release/acquire synchronization */
323 curr->read_from(reads_from);
324 r_modification_order(curr,reads_from);
326 /* Read from future value */
327 value = curr->get_node()->get_future_value();
328 curr->read_from(NULL);
329 Promise * valuepromise=new Promise(curr, value);
330 promises->push_back(valuepromise);
332 } else if (curr->is_write()) {
333 w_modification_order(curr);
334 resolve_promises(curr);
337 th->set_return_value(value);
339 /* Add action to list. */
341 add_action_to_lists(curr);
343 /* Is there a better interface for setting the next thread rather
344 than this field/convoluted approach? Perhaps like just returning
347 /* Do not split atomic actions. */
348 if (curr->is_rmwr()) {
349 nextThread = thread_current()->get_id();
351 nextThread = get_next_replay_thread();
354 Node *currnode = curr->get_node();
355 Node *parnode = currnode->get_parent();
357 if (!parnode->backtrack_empty()||!currnode->readsfrom_empty()||!currnode->futurevalues_empty()||!currnode->promises_empty())
358 if (!next_backtrack || *curr > *next_backtrack)
359 next_backtrack = curr;
361 set_backtracking(curr);
364 /** @returns whether the current trace is feasible. */
365 bool ModelChecker::isfeasible() {
366 return !cyclegraph->checkForCycles() && !failed_promise;
369 /** Returns whether the current trace is feasible. */
370 bool ModelChecker::isfinalfeasible() {
371 return isfeasible() && promises->size()==0;
374 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
375 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
376 int tid = id_to_int(act->get_tid());
377 ModelAction *lastread=get_last_action(tid);
378 lastread->process_rmw(act);
380 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
385 * Updates the cyclegraph with the constraints imposed from the current read.
386 * @param curr The current action. Must be a read.
387 * @param rf The action that curr reads from. Must be a write.
389 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
390 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
392 ASSERT(curr->is_read());
394 /* Iterate over all threads */
395 for (i = 0; i < thrd_lists->size(); i++) {
396 /* Iterate over actions in thread, starting from most recent */
397 action_list_t *list = &(*thrd_lists)[i];
398 action_list_t::reverse_iterator rit;
399 for (rit = list->rbegin(); rit != list->rend(); rit++) {
400 ModelAction *act = *rit;
402 /* Include at most one act per-thread that "happens before" curr */
403 if (act->happens_before(curr)) {
404 if (act->is_read()) {
405 const ModelAction * prevreadfrom=act->get_reads_from();
406 if (rf!=prevreadfrom)
407 cyclegraph->addEdge(rf, prevreadfrom);
408 } else if (rf!=act) {
409 cyclegraph->addEdge(rf, act);
418 * Updates the cyclegraph with the constraints imposed from the current write.
419 * @param curr The current action. Must be a write.
421 void ModelChecker::w_modification_order(ModelAction * curr) {
422 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
424 ASSERT(curr->is_write());
426 if (curr->is_seqcst()) {
427 /* We have to at least see the last sequentially consistent write,
428 so we are initialized. */
429 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
430 if (last_seq_cst!=NULL)
431 cyclegraph->addEdge(curr, last_seq_cst);
434 /* Iterate over all threads */
435 for (i = 0; i < thrd_lists->size(); i++) {
436 /* Iterate over actions in thread, starting from most recent */
437 action_list_t *list = &(*thrd_lists)[i];
438 action_list_t::reverse_iterator rit;
439 for (rit = list->rbegin(); rit != list->rend(); rit++) {
440 ModelAction *act = *rit;
442 /* Include at most one act per-thread that "happens before" curr */
443 if (act->happens_before(curr)) {
444 if (act->is_read()) {
445 cyclegraph->addEdge(curr, act->get_reads_from());
447 cyclegraph->addEdge(curr, act);
450 if (act->is_read()&&!act->is_synchronizing(curr)&&!act->same_thread(curr)) {
451 /* We have an action that:
452 (1) did not happen before us
453 (2) is a read and we are a write
454 (3) cannot synchronize with us
455 (4) is in a different thread
457 that read could potentially read from our write.
459 if (act->get_node()->add_future_value(curr->get_value())&&
460 (!next_backtrack || *act > * next_backtrack))
461 next_backtrack = act;
469 * Performs various bookkeeping operations for the current ModelAction. For
470 * instance, adds action to the per-object, per-thread action vector and to the
471 * action trace list of all thread actions.
473 * @param act is the ModelAction to add.
475 void ModelChecker::add_action_to_lists(ModelAction *act)
477 int tid = id_to_int(act->get_tid());
478 action_trace->push_back(act);
480 obj_map->ensureptr(act->get_location())->push_back(act);
482 std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
483 if (tid >= (int)vec->size())
484 vec->resize(next_thread_id);
485 (*vec)[tid].push_back(act);
487 if ((int)thrd_last_action->size() <= tid)
488 thrd_last_action->resize(get_num_threads());
489 (*thrd_last_action)[tid] = act;
492 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
494 int nthreads = get_num_threads();
495 if ((int)thrd_last_action->size() < nthreads)
496 thrd_last_action->resize(nthreads);
497 return (*thrd_last_action)[id_to_int(tid)];
501 * Gets the last memory_order_seq_cst action (in the total global sequence)
502 * performed on a particular object (i.e., memory location).
503 * @param location The object location to check
504 * @return The last seq_cst action performed
506 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
508 action_list_t *list = obj_map->ensureptr(location);
509 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
510 action_list_t::reverse_iterator rit;
511 for (rit = list->rbegin(); rit != list->rend(); rit++)
512 if ((*rit)->is_write() && (*rit)->is_seqcst())
517 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
519 ModelAction *parent = get_last_action(tid);
521 parent = get_thread(tid)->get_creation();
526 * Returns the clock vector for a given thread.
527 * @param tid The thread whose clock vector we want
528 * @return Desired clock vector
530 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
531 return get_parent_action(tid)->get_cv();
535 /** Resolve promises. */
537 void ModelChecker::resolve_promises(ModelAction *write) {
538 for(unsigned int i=0, promise_index=0;promise_index<promises->size(); i++) {
539 Promise * promise=(*promises)[promise_index];
540 if (write->get_node()->get_promise(i)) {
541 ModelAction * read=promise->get_action();
542 read->read_from(write);
543 r_modification_order(read, write);
544 promises->erase(promises->begin()+promise_index);
550 void ModelChecker::compute_promises(ModelAction *curr) {
551 for(unsigned int i=0;i<promises->size();i++) {
552 Promise * promise=(*promises)[i];
553 const ModelAction * act=promise->get_action();
554 if (!act->happens_before(curr)&&
556 !act->is_synchronizing(curr)&&
557 !act->same_thread(curr)&&
558 promise->get_value()==curr->get_value()) {
559 curr->get_node()->set_promise(i);
564 /** Checks promises in response to change in ClockVector Threads. */
566 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
567 for(unsigned int i=0;i<promises->size();i++) {
568 Promise * promise=(*promises)[i];
569 const ModelAction * act=promise->get_action();
570 if ((old_cv==NULL||!old_cv->synchronized_since(act))&&
571 merge_cv->synchronized_since(act)) {
572 //This thread is no longer able to send values back to satisfy the promise
573 int num_synchronized_threads=promise->increment_threads();
574 if (num_synchronized_threads==model->get_num_threads()) {
576 failed_promise = true;
584 * Build up an initial set of all past writes that this 'read' action may read
585 * from. This set is determined by the clock vector's "happens before"
587 * @param curr is the current ModelAction that we are exploring; it must be a
590 void ModelChecker::build_reads_from_past(ModelAction *curr)
592 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
594 ASSERT(curr->is_read());
596 ModelAction *last_seq_cst = NULL;
598 /* Track whether this object has been initialized */
599 bool initialized = false;
601 if (curr->is_seqcst()) {
602 last_seq_cst = get_last_seq_cst(curr->get_location());
603 /* We have to at least see the last sequentially consistent write,
604 so we are initialized. */
605 if (last_seq_cst != NULL)
609 /* Iterate over all threads */
610 for (i = 0; i < thrd_lists->size(); i++) {
611 /* Iterate over actions in thread, starting from most recent */
612 action_list_t *list = &(*thrd_lists)[i];
613 action_list_t::reverse_iterator rit;
614 for (rit = list->rbegin(); rit != list->rend(); rit++) {
615 ModelAction *act = *rit;
617 /* Only consider 'write' actions */
618 if (!act->is_write())
621 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
622 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
623 DEBUG("Adding action to may_read_from:\n");
628 curr->get_node()->add_read_from(act);
631 /* Include at most one act per-thread that "happens before" curr */
632 if (act->happens_before(curr)) {
640 /** @todo Need a more informative way of reporting errors. */
641 printf("ERROR: may read from uninitialized atomic\n");
644 if (DBG_ENABLED() || !initialized) {
645 printf("Reached read action:\n");
647 printf("Printing may_read_from\n");
648 curr->get_node()->print_may_read_from();
649 printf("End printing may_read_from\n");
655 static void print_list(action_list_t *list)
657 action_list_t::iterator it;
659 printf("---------------------------------------------------------------------\n");
662 for (it = list->begin(); it != list->end(); it++) {
665 printf("---------------------------------------------------------------------\n");
668 void ModelChecker::print_summary(void)
671 printf("Number of executions: %d\n", num_executions);
672 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
676 if (!isfinalfeasible())
677 printf("INFEASIBLE EXECUTION!\n");
678 print_list(action_trace);
682 int ModelChecker::add_thread(Thread *t)
684 thread_map->put(id_to_int(t->get_id()), t);
685 scheduler->add_thread(t);
689 void ModelChecker::remove_thread(Thread *t)
691 scheduler->remove_thread(t);
695 * Switch from a user-context to the "master thread" context (a.k.a. system
696 * context). This switch is made with the intention of exploring a particular
697 * model-checking action (described by a ModelAction object). Must be called
698 * from a user-thread context.
699 * @param act The current action that will be explored. May be NULL, although
700 * there is little reason to switch to the model-checker without an action to
701 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
702 * yield control without performing any progress; see thrd_join()).
703 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
705 int ModelChecker::switch_to_master(ModelAction *act)
708 Thread * old = thread_current();
709 set_current_action(act);
710 old->set_state(THREAD_READY);
711 return Thread::swap(old, get_system_context());