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 (isfeasible() || 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);
286 * Perform one-time actions when pushing new ModelAction onto
289 curr->create_cv(get_parent_action(curr->get_tid()));
290 /* Build may_read_from set */
292 build_reads_from_past(curr);
293 if (curr->is_write())
294 compute_promises(curr);
298 /* Assign 'creation' parent */
299 if (curr->get_type() == THREAD_CREATE) {
300 Thread *th = (Thread *)curr->get_location();
301 th->set_creation(curr);
304 /* Deal with new thread */
305 if (curr->get_type() == THREAD_START) {
306 check_promises(NULL, curr->get_cv());
309 /* Assign reads_from values */
310 Thread *th = get_thread(curr->get_tid());
311 uint64_t value = VALUE_NONE;
312 if (curr->is_read()) {
313 const ModelAction *reads_from = curr->get_node()->get_read_from();
314 if (reads_from!=NULL) {
315 value = reads_from->get_value();
316 /* Assign reads_from, perform release/acquire synchronization */
317 curr->read_from(reads_from);
318 r_modification_order(curr,reads_from);
320 /* Read from future value */
321 value = curr->get_node()->get_future_value();
322 curr->read_from(NULL);
323 Promise * valuepromise=new Promise(curr, value);
324 promises->push_back(valuepromise);
326 } else if (curr->is_write()) {
327 w_modification_order(curr);
328 resolve_promises(curr);
331 th->set_return_value(value);
333 /* Add action to list. */
335 add_action_to_lists(curr);
337 /* Is there a better interface for setting the next thread rather
338 than this field/convoluted approach? Perhaps like just returning
341 /* Do not split atomic actions. */
342 if (curr->is_rmwr()) {
343 nextThread = thread_current()->get_id();
345 nextThread = get_next_replay_thread();
348 Node *currnode = curr->get_node();
349 Node *parnode = currnode->get_parent();
351 if (!parnode->backtrack_empty()||!currnode->readsfrom_empty()||!currnode->futurevalues_empty()||!currnode->promises_empty())
352 if (!next_backtrack || *curr > *next_backtrack)
353 next_backtrack = curr;
355 set_backtracking(curr);
358 /** @returns whether the current trace is feasible. */
359 bool ModelChecker::isfeasible() {
360 return !cyclegraph->checkForCycles() && !failed_promise;
363 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
364 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
365 int tid = id_to_int(act->get_tid());
366 ModelAction *lastread=get_last_action(tid);
367 lastread->process_rmw(act);
369 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
374 * Updates the cyclegraph with the constraints imposed from the current read.
375 * @param curr The current action. Must be a read.
376 * @param rf The action that curr reads from. Must be a write.
378 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
379 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
381 ASSERT(curr->is_read());
383 /* Iterate over all threads */
384 for (i = 0; i < thrd_lists->size(); i++) {
385 /* Iterate over actions in thread, starting from most recent */
386 action_list_t *list = &(*thrd_lists)[i];
387 action_list_t::reverse_iterator rit;
388 for (rit = list->rbegin(); rit != list->rend(); rit++) {
389 ModelAction *act = *rit;
391 /* Include at most one act per-thread that "happens before" curr */
392 if (act->happens_before(curr)) {
393 if (act->is_read()) {
394 const ModelAction * prevreadfrom=act->get_reads_from();
395 if (rf!=prevreadfrom)
396 cyclegraph->addEdge(rf, prevreadfrom);
397 } else if (rf!=act) {
398 cyclegraph->addEdge(rf, act);
407 * Updates the cyclegraph with the constraints imposed from the current write.
408 * @param curr The current action. Must be a write.
410 void ModelChecker::w_modification_order(ModelAction * curr) {
411 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
413 ASSERT(curr->is_write());
415 if (curr->is_seqcst()) {
416 /* We have to at least see the last sequentially consistent write,
417 so we are initialized. */
418 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
419 if (last_seq_cst!=NULL)
420 cyclegraph->addEdge(curr, last_seq_cst);
423 /* Iterate over all threads */
424 for (i = 0; i < thrd_lists->size(); i++) {
425 /* Iterate over actions in thread, starting from most recent */
426 action_list_t *list = &(*thrd_lists)[i];
427 action_list_t::reverse_iterator rit;
428 for (rit = list->rbegin(); rit != list->rend(); rit++) {
429 ModelAction *act = *rit;
431 /* Include at most one act per-thread that "happens before" curr */
432 if (act->happens_before(curr)) {
433 if (act->is_read()) {
434 cyclegraph->addEdge(curr, act->get_reads_from());
436 cyclegraph->addEdge(curr, act);
439 if (act->is_read()&&!act->is_synchronizing(curr)&&!act->same_thread(curr)) {
440 /* We have an action that:
441 (1) did not happen before us
442 (2) is a read and we are a write
443 (3) cannot synchronize with us
444 (4) is in a different thread
446 that read could potentially read from our write.
449 if (act->get_node()->add_future_value(curr->get_value())&&
450 (!next_backtrack || *act > * next_backtrack))
451 next_backtrack = act;
459 * Performs various bookkeeping operations for the current ModelAction. For
460 * instance, adds action to the per-object, per-thread action vector and to the
461 * action trace list of all thread actions.
463 * @param act is the ModelAction to add.
465 void ModelChecker::add_action_to_lists(ModelAction *act)
467 int tid = id_to_int(act->get_tid());
468 action_trace->push_back(act);
470 obj_map->ensureptr(act->get_location())->push_back(act);
472 std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
473 if (tid >= (int)vec->size())
474 vec->resize(next_thread_id);
475 (*vec)[tid].push_back(act);
477 if ((int)thrd_last_action->size() <= tid)
478 thrd_last_action->resize(get_num_threads());
479 (*thrd_last_action)[tid] = act;
482 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
484 int nthreads = get_num_threads();
485 if ((int)thrd_last_action->size() < nthreads)
486 thrd_last_action->resize(nthreads);
487 return (*thrd_last_action)[id_to_int(tid)];
491 * Gets the last memory_order_seq_cst action (in the total global sequence)
492 * performed on a particular object (i.e., memory location).
493 * @param location The object location to check
494 * @return The last seq_cst action performed
496 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
498 action_list_t *list = obj_map->ensureptr(location);
499 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
500 action_list_t::reverse_iterator rit;
501 for (rit = list->rbegin(); rit != list->rend(); rit++)
502 if ((*rit)->is_write() && (*rit)->is_seqcst())
507 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
509 ModelAction *parent = get_last_action(tid);
511 parent = get_thread(tid)->get_creation();
516 * Returns the clock vector for a given thread.
517 * @param tid The thread whose clock vector we want
518 * @return Desired clock vector
520 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
521 return get_parent_action(tid)->get_cv();
525 /** Resolve promises. */
527 void ModelChecker::resolve_promises(ModelAction *write) {
528 for(unsigned int i=0;i<promises->size();i++) {
529 Promise * promise=(*promises)[i];
530 if (write->get_node()->get_promise(i)) {
531 ModelAction * read=promise->get_action();
532 read->read_from(write);
533 r_modification_order(read, write);
538 void ModelChecker::compute_promises(ModelAction *curr) {
539 for(unsigned int i=0;i<promises->size();i++) {
540 Promise * promise=(*promises)[i];
541 const ModelAction * act=promise->get_action();
542 if (!act->happens_before(curr)&&
544 !act->is_synchronizing(curr)&&
545 !act->same_thread(curr)&&
546 promise->get_value()==curr->get_value()) {
547 curr->get_node()->set_promise(i);
552 /** Checks promises in response to change in ClockVector Threads. */
554 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
555 for(unsigned int i=0;i<promises->size();i++) {
556 Promise * promise=(*promises)[i];
557 const ModelAction * act=promise->get_action();
558 if ((old_cv==NULL||!old_cv->synchronized_since(act))&&
559 merge_cv->synchronized_since(act)) {
560 //This thread is no longer able to send values back to satisfy the promise
561 int num_synchronized_threads=promise->increment_threads();
562 if (num_synchronized_threads==model->get_num_threads()) {
564 failed_promise = true;
572 * Build up an initial set of all past writes that this 'read' action may read
573 * from. This set is determined by the clock vector's "happens before"
575 * @param curr is the current ModelAction that we are exploring; it must be a
578 void ModelChecker::build_reads_from_past(ModelAction *curr)
580 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
582 ASSERT(curr->is_read());
584 ModelAction *last_seq_cst = NULL;
586 /* Track whether this object has been initialized */
587 bool initialized = false;
589 if (curr->is_seqcst()) {
590 last_seq_cst = get_last_seq_cst(curr->get_location());
591 /* We have to at least see the last sequentially consistent write,
592 so we are initialized. */
593 if (last_seq_cst != NULL)
597 /* Iterate over all threads */
598 for (i = 0; i < thrd_lists->size(); i++) {
599 /* Iterate over actions in thread, starting from most recent */
600 action_list_t *list = &(*thrd_lists)[i];
601 action_list_t::reverse_iterator rit;
602 for (rit = list->rbegin(); rit != list->rend(); rit++) {
603 ModelAction *act = *rit;
605 /* Only consider 'write' actions */
606 if (!act->is_write())
609 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
610 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
611 DEBUG("Adding action to may_read_from:\n");
616 curr->get_node()->add_read_from(act);
619 /* Include at most one act per-thread that "happens before" curr */
620 if (act->happens_before(curr)) {
628 /** @todo Need a more informative way of reporting errors. */
629 printf("ERROR: may read from uninitialized atomic\n");
632 if (DBG_ENABLED() || !initialized) {
633 printf("Reached read action:\n");
635 printf("Printing may_read_from\n");
636 curr->get_node()->print_may_read_from();
637 printf("End printing may_read_from\n");
643 static void print_list(action_list_t *list)
645 action_list_t::iterator it;
647 printf("---------------------------------------------------------------------\n");
650 for (it = list->begin(); it != list->end(); it++) {
653 printf("---------------------------------------------------------------------\n");
656 void ModelChecker::print_summary(void)
659 printf("Number of executions: %d\n", num_executions);
660 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
665 printf("INFEASIBLE EXECUTION!\n");
666 print_list(action_trace);
670 int ModelChecker::add_thread(Thread *t)
672 thread_map->put(id_to_int(t->get_id()), t);
673 scheduler->add_thread(t);
677 void ModelChecker::remove_thread(Thread *t)
679 scheduler->remove_thread(t);
683 * Switch from a user-context to the "master thread" context (a.k.a. system
684 * context). This switch is made with the intention of exploring a particular
685 * model-checking action (described by a ModelAction object). Must be called
686 * from a user-thread context.
687 * @param act The current action that will be explored. May be NULL, although
688 * there is little reason to switch to the model-checker without an action to
689 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
690 * yield control without performing any progress; see thrd_join()).
691 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
693 int ModelChecker::switch_to_master(ModelAction *act)
696 Thread * old = thread_current();
697 set_current_action(act);
698 old->set_state(THREAD_READY);
699 return Thread::swap(old, get_system_context());