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),
29 nextThread(THREAD_ID_T_NONE),
30 action_trace(new action_list_t()),
31 thread_map(new HashTable<int, Thread *, int>()),
32 obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33 obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
34 promises(new std::vector<Promise *>()),
35 thrd_last_action(new std::vector<ModelAction *>(1)),
36 node_stack(new NodeStack()),
38 cyclegraph(new CycleGraph()),
43 /** @brief Destructor */
44 ModelChecker::~ModelChecker()
46 /* std::map<int, Thread *>::iterator it;
47 for (it = thread_map->begin(); it != thread_map->end(); it++)
48 delete (*it).second;*/
54 delete thrd_last_action;
61 * Restores user program to initial state and resets all model-checker data
64 void ModelChecker::reset_to_initial_state()
66 DEBUG("+++ Resetting to initial state +++\n");
67 node_stack->reset_execution();
68 current_action = NULL;
69 next_thread_id = INITIAL_THREAD_ID;
70 used_sequence_numbers = 0;
72 next_backtrack = NULL;
73 failed_promise = false;
74 snapshotObject->backTrackBeforeStep(0);
77 /** @returns a thread ID for a new Thread */
78 thread_id_t ModelChecker::get_next_id()
80 return next_thread_id++;
83 /** @returns the number of user threads created during this execution */
84 int ModelChecker::get_num_threads()
86 return next_thread_id;
89 /** @returns a sequence number for a new ModelAction */
90 modelclock_t ModelChecker::get_next_seq_num()
92 return ++used_sequence_numbers;
96 * Performs the "scheduling" for the model-checker. That is, it checks if the
97 * model-checker has selected a "next thread to run" and returns it, if
98 * available. This function should be called from the Scheduler routine, where
99 * the Scheduler falls back to a default scheduling routine if needed.
101 * @return The next thread chosen by the model-checker. If the model-checker
102 * makes no selection, retuns NULL.
104 Thread * ModelChecker::schedule_next_thread()
107 if (nextThread == THREAD_ID_T_NONE)
109 t = thread_map->get(id_to_int(nextThread));
117 * Choose the next thread in the replay sequence.
119 * If the replay sequence has reached the 'diverge' point, returns a thread
120 * from the backtracking set. Otherwise, simply returns the next thread in the
121 * sequence that is being replayed.
123 thread_id_t ModelChecker::get_next_replay_thread()
127 /* Have we completed exploring the preselected path? */
129 return THREAD_ID_T_NONE;
131 /* Else, we are trying to replay an execution */
132 ModelAction * next = node_stack->get_next()->get_action();
134 if (next == diverge) {
135 Node *nextnode = next->get_node();
136 /* Reached divergence point */
137 if (nextnode->increment_read_from()) {
138 /* The next node will read from a different value. */
139 tid = next->get_tid();
140 node_stack->pop_restofstack(2);
141 } else if (nextnode->increment_future_values()) {
142 /* The next node will try to read from a different future value. */
143 tid = next->get_tid();
144 node_stack->pop_restofstack(2);
146 /* Make a different thread execute for next step */
147 Node *node = nextnode->get_parent();
148 tid = node->get_next_backtrack();
149 node_stack->pop_restofstack(1);
151 DEBUG("*** Divergence point ***\n");
154 tid = next->get_tid();
156 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
161 * Queries the model-checker for more executions to explore and, if one
162 * exists, resets the model-checker state to execute a new execution.
164 * @return If there are more executions to explore, return true. Otherwise,
167 bool ModelChecker::next_execution()
173 if (isfeasible() || DBG_ENABLED())
176 if ((diverge = model->get_next_backtrack()) == NULL)
180 printf("Next execution will diverge at:\n");
184 model->reset_to_initial_state();
188 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
190 action_type type = act->get_type();
200 /* linear search: from most recent to oldest */
201 action_list_t *list = obj_map->ensureptr(act->get_location());
202 action_list_t::reverse_iterator rit;
203 for (rit = list->rbegin(); rit != list->rend(); rit++) {
204 ModelAction *prev = *rit;
205 if (act->is_synchronizing(prev))
211 void ModelChecker::set_backtracking(ModelAction *act)
215 Thread *t = get_thread(act->get_tid());
217 prev = get_last_conflict(act);
221 node = prev->get_node()->get_parent();
223 while (!node->is_enabled(t))
226 /* Check if this has been explored already */
227 if (node->has_been_explored(t->get_id()))
230 /* Cache the latest backtracking point */
231 if (!next_backtrack || *prev > *next_backtrack)
232 next_backtrack = prev;
234 /* If this is a new backtracking point, mark the tree */
235 if (!node->set_backtrack(t->get_id()))
237 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
238 prev->get_tid(), t->get_id());
246 * Returns last backtracking point. The model checker will explore a different
247 * path for this point in the next execution.
248 * @return The ModelAction at which the next execution should diverge.
250 ModelAction * ModelChecker::get_next_backtrack()
252 ModelAction *next = next_backtrack;
253 next_backtrack = NULL;
257 void ModelChecker::check_current_action(void)
259 ModelAction *curr = this->current_action;
260 bool already_added = false;
261 this->current_action = NULL;
263 DEBUG("trying to push NULL action...\n");
267 if (curr->is_rmwc()||curr->is_rmw()) {
268 ModelAction *tmp=process_rmw(curr);
269 already_added = true;
273 ModelAction * tmp = node_stack->explore_action(curr);
275 /* Discard duplicate ModelAction; use action from NodeStack */
276 /* First restore type and order in case of RMW operation */
278 tmp->copy_typeandorder(curr);
283 * Perform one-time actions when pushing new ModelAction onto
286 curr->create_cv(get_parent_action(curr->get_tid()));
287 /* Build may_read_from set */
289 build_reads_from_past(curr);
293 /* Assign 'creation' parent */
294 if (curr->get_type() == THREAD_CREATE) {
295 Thread *th = (Thread *)curr->get_location();
296 th->set_creation(curr);
299 /* Deal with new thread */
300 if (curr->get_type() == THREAD_START) {
301 check_promises(NULL, curr->get_cv());
304 /* Assign reads_from values */
305 Thread *th = get_thread(curr->get_tid());
306 uint64_t value = VALUE_NONE;
307 if (curr->is_read()) {
308 const ModelAction *reads_from = curr->get_node()->get_read_from();
309 if (reads_from!=NULL) {
310 value = reads_from->get_value();
311 /* Assign reads_from, perform release/acquire synchronization */
312 curr->read_from(reads_from);
313 r_modification_order(curr,reads_from);
315 /* Read from future value */
316 value = curr->get_node()->get_future_value();
317 curr->read_from(NULL);
318 Promise * valuepromise=new Promise(curr, value);
319 promises->push_back(valuepromise);
321 } else if (curr->is_write()) {
322 w_modification_order(curr);
325 th->set_return_value(value);
327 /* Add action to list. */
329 add_action_to_lists(curr);
331 /* Is there a better interface for setting the next thread rather
332 than this field/convoluted approach? Perhaps like just returning
335 /* Do not split atomic actions. */
336 if (curr->is_rmwr()) {
337 nextThread = thread_current()->get_id();
339 nextThread = get_next_replay_thread();
342 Node *currnode = curr->get_node();
343 Node *parnode = currnode->get_parent();
345 if (!parnode->backtrack_empty()||!currnode->readsfrom_empty()||!currnode->futurevalues_empty())
346 if (!next_backtrack || *curr > *next_backtrack)
347 next_backtrack = curr;
349 set_backtracking(curr);
352 /** @returns whether the current trace is feasible. */
353 bool ModelChecker::isfeasible() {
354 return !cyclegraph->checkForCycles() && !failed_promise;
357 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
358 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
359 int tid = id_to_int(act->get_tid());
360 ModelAction *lastread=get_last_action(tid);
361 lastread->process_rmw(act);
363 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
368 * Updates the cyclegraph with the constraints imposed from the current read.
369 * @param curr The current action. Must be a read.
370 * @param rf The action that curr reads from. Must be a write.
372 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
373 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
375 ASSERT(curr->is_read());
377 /* Iterate over all threads */
378 for (i = 0; i < thrd_lists->size(); i++) {
379 /* Iterate over actions in thread, starting from most recent */
380 action_list_t *list = &(*thrd_lists)[i];
381 action_list_t::reverse_iterator rit;
382 for (rit = list->rbegin(); rit != list->rend(); rit++) {
383 ModelAction *act = *rit;
385 /* Include at most one act per-thread that "happens before" curr */
386 if (act->happens_before(curr)) {
387 if (act->is_read()) {
388 const ModelAction * prevreadfrom=act->get_reads_from();
389 if (rf!=prevreadfrom)
390 cyclegraph->addEdge(rf, prevreadfrom);
391 } else if (rf!=act) {
392 cyclegraph->addEdge(rf, act);
401 * Updates the cyclegraph with the constraints imposed from the current write.
402 * @param curr The current action. Must be a write.
404 void ModelChecker::w_modification_order(ModelAction * curr) {
405 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
407 ASSERT(curr->is_write());
409 if (curr->is_seqcst()) {
410 /* We have to at least see the last sequentially consistent write,
411 so we are initialized. */
412 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
413 if (last_seq_cst!=NULL)
414 cyclegraph->addEdge(curr, last_seq_cst);
417 /* Iterate over all threads */
418 for (i = 0; i < thrd_lists->size(); i++) {
419 /* Iterate over actions in thread, starting from most recent */
420 action_list_t *list = &(*thrd_lists)[i];
421 action_list_t::reverse_iterator rit;
422 for (rit = list->rbegin(); rit != list->rend(); rit++) {
423 ModelAction *act = *rit;
425 /* Include at most one act per-thread that "happens before" curr */
426 if (act->happens_before(curr)) {
427 if (act->is_read()) {
428 cyclegraph->addEdge(curr, act->get_reads_from());
430 cyclegraph->addEdge(curr, act);
433 if (act->is_read()&&!act->is_synchronizing(curr)&&!act->same_thread(curr)) {
434 /* We have an action that:
435 (1) did not happen before us
436 (2) is a read and we are a write
437 (3) cannot synchronize with us
438 (4) is in a different thread
440 that read could potentially read from our write.
443 if (act->get_node()->add_future_value(curr->get_value())&&
444 (!next_backtrack || *act > * next_backtrack))
445 next_backtrack = act;
453 * Performs various bookkeeping operations for the current ModelAction. For
454 * instance, adds action to the per-object, per-thread action vector and to the
455 * action trace list of all thread actions.
457 * @param act is the ModelAction to add.
459 void ModelChecker::add_action_to_lists(ModelAction *act)
461 int tid = id_to_int(act->get_tid());
462 action_trace->push_back(act);
464 obj_map->ensureptr(act->get_location())->push_back(act);
466 std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
467 if (tid >= (int)vec->size())
468 vec->resize(next_thread_id);
469 (*vec)[tid].push_back(act);
471 if ((int)thrd_last_action->size() <= tid)
472 thrd_last_action->resize(get_num_threads());
473 (*thrd_last_action)[tid] = act;
476 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
478 int nthreads = get_num_threads();
479 if ((int)thrd_last_action->size() < nthreads)
480 thrd_last_action->resize(nthreads);
481 return (*thrd_last_action)[id_to_int(tid)];
485 * Gets the last memory_order_seq_cst action (in the total global sequence)
486 * performed on a particular object (i.e., memory location).
487 * @param location The object location to check
488 * @return The last seq_cst action performed
490 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
492 action_list_t *list = obj_map->ensureptr(location);
493 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
494 action_list_t::reverse_iterator rit;
495 for (rit = list->rbegin(); rit != list->rend(); rit++)
496 if ((*rit)->is_write() && (*rit)->is_seqcst())
501 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
503 ModelAction *parent = get_last_action(tid);
505 parent = get_thread(tid)->get_creation();
510 * Returns the clock vector for a given thread.
511 * @param tid The thread whose clock vector we want
512 * @return Desired clock vector
514 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
515 return get_parent_action(tid)->get_cv();
518 /** Checks promises in response to change in ClockVector Threads. */
520 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
521 for(unsigned int i=0;i<promises->size();i++) {
522 Promise * promise=(*promises)[i];
523 const ModelAction * act=promise->get_action();
524 if ((old_cv==NULL||!old_cv->synchronized_since(act))&&
525 merge_cv->synchronized_since(act)) {
526 //This thread is no longer able to send values back to satisfy the promise
527 int num_synchronized_threads=promise->increment_threads();
528 if (num_synchronized_threads==model->get_num_threads()) {
530 failed_promise = true;
538 * Build up an initial set of all past writes that this 'read' action may read
539 * from. This set is determined by the clock vector's "happens before"
541 * @param curr is the current ModelAction that we are exploring; it must be a
544 void ModelChecker::build_reads_from_past(ModelAction *curr)
546 std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
548 ASSERT(curr->is_read());
550 ModelAction *last_seq_cst = NULL;
552 /* Track whether this object has been initialized */
553 bool initialized = false;
555 if (curr->is_seqcst()) {
556 last_seq_cst = get_last_seq_cst(curr->get_location());
557 /* We have to at least see the last sequentially consistent write,
558 so we are initialized. */
559 if (last_seq_cst != NULL)
563 /* Iterate over all threads */
564 for (i = 0; i < thrd_lists->size(); i++) {
565 /* Iterate over actions in thread, starting from most recent */
566 action_list_t *list = &(*thrd_lists)[i];
567 action_list_t::reverse_iterator rit;
568 for (rit = list->rbegin(); rit != list->rend(); rit++) {
569 ModelAction *act = *rit;
571 /* Only consider 'write' actions */
572 if (!act->is_write())
575 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
576 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
577 DEBUG("Adding action to may_read_from:\n");
582 curr->get_node()->add_read_from(act);
585 /* Include at most one act per-thread that "happens before" curr */
586 if (act->happens_before(curr)) {
594 /** @todo Need a more informative way of reporting errors. */
595 printf("ERROR: may read from uninitialized atomic\n");
598 if (DBG_ENABLED() || !initialized) {
599 printf("Reached read action:\n");
601 printf("Printing may_read_from\n");
602 curr->get_node()->print_may_read_from();
603 printf("End printing may_read_from\n");
609 static void print_list(action_list_t *list)
611 action_list_t::iterator it;
613 printf("---------------------------------------------------------------------\n");
616 for (it = list->begin(); it != list->end(); it++) {
619 printf("---------------------------------------------------------------------\n");
622 void ModelChecker::print_summary(void)
625 printf("Number of executions: %d\n", num_executions);
626 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
631 printf("INFEASIBLE EXECUTION!\n");
632 print_list(action_trace);
636 int ModelChecker::add_thread(Thread *t)
638 thread_map->put(id_to_int(t->get_id()), t);
639 scheduler->add_thread(t);
643 void ModelChecker::remove_thread(Thread *t)
645 scheduler->remove_thread(t);
649 * Switch from a user-context to the "master thread" context (a.k.a. system
650 * context). This switch is made with the intention of exploring a particular
651 * model-checking action (described by a ModelAction object). Must be called
652 * from a user-thread context.
653 * @param act The current action that will be explored. May be NULL, although
654 * there is little reason to switch to the model-checker without an action to
655 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
656 * yield control without performing any progress; see thrd_join()).
657 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
659 int ModelChecker::switch_to_master(ModelAction *act)
662 Thread * old = thread_current();
663 set_current_action(act);
664 old->set_state(THREAD_READY);
665 return Thread::swap(old, get_system_context());