7 #include "snapshot-interface.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
12 #define INITIAL_THREAD_ID 0
16 /** @brief Constructor */
17 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),
28 nextThread(THREAD_ID_T_NONE),
29 action_trace(new action_list_t()),
30 thread_map(new std::map<int, Thread *>),
31 obj_map(new std::map<const void *, action_list_t>()),
32 obj_thrd_map(new std::map<void *, std::vector<action_list_t> >()),
33 thrd_last_action(new std::vector<ModelAction *>(1)),
34 node_stack(new NodeStack()),
36 cyclegraph(new CycleGraph())
40 /** @brief Destructor */
41 ModelChecker::~ModelChecker()
43 std::map<int, Thread *>::iterator it;
44 for (it = thread_map->begin(); it != thread_map->end(); it++)
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 snapshotObject->backTrackBeforeStep(0);
73 /** @returns a thread ID for a new Thread */
74 thread_id_t ModelChecker::get_next_id()
76 return next_thread_id++;
79 /** @returns the number of user threads created during this execution */
80 int ModelChecker::get_num_threads()
82 return next_thread_id;
85 /** @returns a sequence number for a new ModelAction */
86 modelclock_t ModelChecker::get_next_seq_num()
88 return ++used_sequence_numbers;
92 * Performs the "scheduling" for the model-checker. That is, it checks if the
93 * model-checker has selected a "next thread to run" and returns it, if
94 * available. This function should be called from the Scheduler routine, where
95 * the Scheduler falls back to a default scheduling routine if needed.
97 * @return The next thread chosen by the model-checker. If the model-checker
98 * makes no selection, retuns NULL.
100 Thread * ModelChecker::schedule_next_thread()
103 if (nextThread == THREAD_ID_T_NONE)
105 t = (*thread_map)[id_to_int(nextThread)];
113 * Choose the next thread in the replay sequence.
115 * If the replay sequence has reached the 'diverge' point, returns a thread
116 * from the backtracking set. Otherwise, simply returns the next thread in the
117 * sequence that is being replayed.
119 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 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_read_from()) {
135 /* The next node will read from a different value */
136 tid = next->get_tid();
137 node_stack->pop_restofstack(2);
139 /* Make a different thread execute for next step */
140 Node *node = nextnode->get_parent();
141 tid = node->get_next_backtrack();
142 node_stack->pop_restofstack(1);
144 DEBUG("*** Divergence point ***\n");
147 tid = next->get_tid();
149 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
154 * Queries the model-checker for more executions to explore and, if one
155 * exists, resets the model-checker state to execute a new execution.
157 * @return If there are more executions to explore, return true. Otherwise,
160 bool ModelChecker::next_execution()
166 if (isfeasible() || DBG_ENABLED())
169 if ((diverge = model->get_next_backtrack()) == NULL)
173 printf("Next execution will diverge at:\n");
177 model->reset_to_initial_state();
181 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
183 action_type type = act->get_type();
193 /* linear search: from most recent to oldest */
194 action_list_t *list = &(*obj_map)[act->get_location()];
195 action_list_t::reverse_iterator rit;
196 for (rit = list->rbegin(); rit != list->rend(); rit++) {
197 ModelAction *prev = *rit;
198 if (act->is_synchronizing(prev))
204 void ModelChecker::set_backtracking(ModelAction *act)
208 Thread *t = get_thread(act->get_tid());
210 prev = get_last_conflict(act);
214 node = prev->get_node()->get_parent();
216 while (!node->is_enabled(t))
219 /* Check if this has been explored already */
220 if (node->has_been_explored(t->get_id()))
223 /* Cache the latest backtracking point */
224 if (!next_backtrack || *prev > *next_backtrack)
225 next_backtrack = prev;
227 /* If this is a new backtracking point, mark the tree */
228 if (!node->set_backtrack(t->get_id()))
230 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
231 prev->get_tid(), t->get_id());
239 * Returns last backtracking point. The model checker will explore a different
240 * path for this point in the next execution.
241 * @return The ModelAction at which the next execution should diverge.
243 ModelAction * ModelChecker::get_next_backtrack()
245 ModelAction *next = next_backtrack;
246 next_backtrack = NULL;
250 void ModelChecker::check_current_action(void)
252 ModelAction *curr = this->current_action;
254 current_action = NULL;
256 DEBUG("trying to push NULL action...\n");
260 if (curr->is_rmw()) {
261 //We have a RMW action
263 //Force the current thread to continue since the RMW should be atomic
264 nextThread = thread_current()->get_id();
269 tmp = node_stack->explore_action(curr);
271 /* Discard duplicate ModelAction; use action from NodeStack */
276 * Perform one-time actions when pushing new ModelAction onto
279 curr->create_cv(get_parent_action(curr->get_tid()));
280 /* Build may_read_from set */
282 build_reads_from_past(curr);
285 /* Assign 'creation' parent */
286 if (curr->get_type() == THREAD_CREATE) {
287 Thread *th = (Thread *)curr->get_location();
288 th->set_creation(curr);
291 /* Is there a better interface for setting the next thread rather
292 than this field/convoluted approach? Perhaps like just returning
295 nextThread = get_next_replay_thread();
297 Node *currnode = curr->get_node();
298 Node *parnode = currnode->get_parent();
300 if (!parnode->backtrack_empty()||!currnode->readsfrom_empty())
301 if (!next_backtrack || *curr > *next_backtrack)
302 next_backtrack = curr;
304 set_backtracking(curr);
306 /* Assign reads_from values */
307 Thread *th = get_thread(curr->get_tid());
308 uint64_t value = VALUE_NONE;
309 if (curr->is_read()) {
310 const ModelAction *reads_from = curr->get_node()->get_read_from();
311 value = reads_from->get_value();
312 /* Assign reads_from, perform release/acquire synchronization */
313 curr->read_from(reads_from);
314 r_modification_order(curr,reads_from);
315 } else if (curr->is_write()) {
316 w_modification_order(curr);
319 th->set_return_value(value);
321 /* Add action to list last. */
322 add_action_to_lists(curr);
325 /** @returns whether the current trace is feasible. */
326 bool ModelChecker::isfeasible() {
327 return !cyclegraph->checkForCycles();
330 /** Process a RMW by converting previous read into a RMW. */
331 void ModelChecker::process_rmw(ModelAction * act) {
332 int tid = id_to_int(act->get_tid());
333 ModelAction *lastread=get_last_action(tid);
334 lastread->upgrade_rmw(act);
335 cyclegraph->addRMWEdge(lastread->get_reads_from(),lastread);
339 * Updates the cyclegraph with the constraints imposed from the current read.
340 * @param curr The current action. Must be a read.
341 * @param rf The action that curr reads from. Must be a write.
343 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
344 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
346 ASSERT(curr->is_read());
348 /* Iterate over all threads */
349 for (i = 0; i < thrd_lists->size(); i++) {
350 /* Iterate over actions in thread, starting from most recent */
351 action_list_t *list = &(*thrd_lists)[i];
352 action_list_t::reverse_iterator rit;
353 for (rit = list->rbegin(); rit != list->rend(); rit++) {
354 ModelAction *act = *rit;
356 /* Include at most one act per-thread that "happens before" curr */
357 if (act->happens_before(curr)) {
358 if (act->is_read()) {
359 const ModelAction * prevreadfrom=act->get_reads_from();
360 if (rf!=prevreadfrom)
361 cyclegraph->addEdge(rf, prevreadfrom);
362 } else if (rf!=act) {
363 cyclegraph->addEdge(rf, act);
372 * Updates the cyclegraph with the constraints imposed from the current write.
373 * @param curr The current action. Must be a write.
375 void ModelChecker::w_modification_order(ModelAction * curr) {
376 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
378 ASSERT(curr->is_write());
380 if (curr->is_seqcst()) {
381 /* We have to at least see the last sequentially consistent write,
382 so we are initialized. */
383 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
384 if (last_seq_cst!=NULL)
385 cyclegraph->addEdge(curr, last_seq_cst);
388 /* Iterate over all threads */
389 for (i = 0; i < thrd_lists->size(); i++) {
390 /* Iterate over actions in thread, starting from most recent */
391 action_list_t *list = &(*thrd_lists)[i];
392 action_list_t::reverse_iterator rit;
393 for (rit = list->rbegin(); rit != list->rend(); rit++) {
394 ModelAction *act = *rit;
396 /* Include at most one act per-thread that "happens before" curr */
397 if (act->happens_before(curr)) {
398 if (act->is_read()) {
399 cyclegraph->addEdge(curr, act->get_reads_from());
401 cyclegraph->addEdge(curr, act);
409 * Performs various bookkeeping operations for the current ModelAction. For
410 * instance, adds action to the per-object, per-thread action vector and to the
411 * action trace list of all thread actions.
413 * @param act is the ModelAction to add.
415 void ModelChecker::add_action_to_lists(ModelAction *act)
417 int tid = id_to_int(act->get_tid());
418 action_trace->push_back(act);
420 (*obj_map)[act->get_location()].push_back(act);
422 std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
423 if (tid >= (int)vec->size())
424 vec->resize(next_thread_id);
425 (*vec)[tid].push_back(act);
427 if ((int)thrd_last_action->size() <= tid)
428 thrd_last_action->resize(get_num_threads());
429 (*thrd_last_action)[tid] = act;
432 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
434 int nthreads = get_num_threads();
435 if ((int)thrd_last_action->size() < nthreads)
436 thrd_last_action->resize(nthreads);
437 return (*thrd_last_action)[id_to_int(tid)];
441 * Gets the last memory_order_seq_cst action (in the total global sequence)
442 * performed on a particular object (i.e., memory location).
443 * @param location The object location to check
444 * @return The last seq_cst action performed
446 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
448 action_list_t *list = &(*obj_map)[location];
449 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
450 action_list_t::reverse_iterator rit;
451 for (rit = list->rbegin(); rit != list->rend(); rit++)
452 if ((*rit)->is_write() && (*rit)->is_seqcst())
457 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
459 ModelAction *parent = get_last_action(tid);
461 parent = get_thread(tid)->get_creation();
466 * Returns the clock vector for a given thread.
467 * @param tid The thread whose clock vector we want
468 * @return Desired clock vector
470 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
471 return get_parent_action(tid)->get_cv();
475 * Build up an initial set of all past writes that this 'read' action may read
476 * from. This set is determined by the clock vector's "happens before"
478 * @param curr is the current ModelAction that we are exploring; it must be a
481 void ModelChecker::build_reads_from_past(ModelAction *curr)
483 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
485 ASSERT(curr->is_read());
487 ModelAction *last_seq_cst = NULL;
489 /* Track whether this object has been initialized */
490 bool initialized = false;
492 if (curr->is_seqcst()) {
493 last_seq_cst = get_last_seq_cst(curr->get_location());
494 /* We have to at least see the last sequentially consistent write,
495 so we are initialized. */
496 if (last_seq_cst != NULL)
500 /* Iterate over all threads */
501 for (i = 0; i < thrd_lists->size(); i++) {
502 /* Iterate over actions in thread, starting from most recent */
503 action_list_t *list = &(*thrd_lists)[i];
504 action_list_t::reverse_iterator rit;
505 for (rit = list->rbegin(); rit != list->rend(); rit++) {
506 ModelAction *act = *rit;
508 /* Only consider 'write' actions */
509 if (!act->is_write())
512 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
513 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
514 DEBUG("Adding action to may_read_from:\n");
519 curr->get_node()->add_read_from(act);
522 /* Include at most one act per-thread that "happens before" curr */
523 if (act->happens_before(curr)) {
531 /* TODO: need a more informative way of reporting errors */
532 printf("ERROR: may read from uninitialized atomic\n");
535 if (DBG_ENABLED() || !initialized) {
536 printf("Reached read action:\n");
538 printf("Printing may_read_from\n");
539 curr->get_node()->print_may_read_from();
540 printf("End printing may_read_from\n");
546 static void print_list(action_list_t *list)
548 action_list_t::iterator it;
550 printf("---------------------------------------------------------------------\n");
553 for (it = list->begin(); it != list->end(); it++) {
556 printf("---------------------------------------------------------------------\n");
559 void ModelChecker::print_summary(void)
562 printf("Number of executions: %d\n", num_executions);
563 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
568 printf("INFEASIBLE EXECUTION!\n");
569 print_list(action_trace);
573 int ModelChecker::add_thread(Thread *t)
575 (*thread_map)[id_to_int(t->get_id())] = t;
576 scheduler->add_thread(t);
580 void ModelChecker::remove_thread(Thread *t)
582 scheduler->remove_thread(t);
586 * Switch from a user-context to the "master thread" context (a.k.a. system
587 * context). This switch is made with the intention of exploring a particular
588 * model-checking action (described by a ModelAction object). Must be called
589 * from a user-thread context.
590 * @param act The current action that will be explored. May be NULL, although
591 * there is little reason to switch to the model-checker without an action to
592 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
593 * yield control without performing any progress; see thrd_join()).
594 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
596 int ModelChecker::switch_to_master(ModelAction *act)
599 Thread * old = thread_current();
600 set_current_action(act);
601 old->set_state(THREAD_READY);
602 return Thread::swap(old, get_system_context());