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()
123 /* Have we completed exploring the preselected path? */
125 return THREAD_ID_T_NONE;
127 /* Else, we are trying to replay an execution */
128 ModelAction * next = node_stack->get_next()->get_action();
130 if (next == diverge) {
131 Node *nextnode = next->get_node();
132 /* Reached divergence point */
133 if (nextnode->increment_read_from()) {
134 /* The next node will read from a different value */
135 tid = next->get_tid();
136 node_stack->pop_restofstack(2);
138 /* Make a different thread execute for next step */
139 Node *node = nextnode->get_parent();
140 tid = node->get_next_backtrack();
141 node_stack->pop_restofstack(1);
143 DEBUG("*** Divergence point ***\n");
146 tid = next->get_tid();
148 DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
153 * Queries the model-checker for more executions to explore and, if one
154 * exists, resets the model-checker state to execute a new execution.
156 * @return If there are more executions to explore, return true. Otherwise,
159 bool ModelChecker::next_execution()
165 if (isfeasible() || DBG_ENABLED())
168 if ((diverge = model->get_next_backtrack()) == NULL)
172 printf("Next execution will diverge at:\n");
176 model->reset_to_initial_state();
180 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
182 action_type type = act->get_type();
192 /* linear search: from most recent to oldest */
193 action_list_t *list = &(*obj_map)[act->get_location()];
194 action_list_t::reverse_iterator rit;
195 for (rit = list->rbegin(); rit != list->rend(); rit++) {
196 ModelAction *prev = *rit;
197 if (act->is_synchronizing(prev))
203 void ModelChecker::set_backtracking(ModelAction *act)
207 Thread *t = get_thread(act->get_tid());
209 prev = get_last_conflict(act);
213 node = prev->get_node()->get_parent();
215 while (!node->is_enabled(t))
218 /* Check if this has been explored already */
219 if (node->has_been_explored(t->get_id()))
222 /* Cache the latest backtracking point */
223 if (!next_backtrack || *prev > *next_backtrack)
224 next_backtrack = prev;
226 /* If this is a new backtracking point, mark the tree */
227 if (!node->set_backtrack(t->get_id()))
229 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
230 prev->get_tid(), t->get_id());
238 * Returns last backtracking point. The model checker will explore a different
239 * path for this point in the next execution.
240 * @return The ModelAction at which the next execution should diverge.
242 ModelAction * ModelChecker::get_next_backtrack()
244 ModelAction *next = next_backtrack;
245 next_backtrack = NULL;
249 void ModelChecker::check_current_action(void)
251 ModelAction *curr = this->current_action;
252 bool already_added = false;
253 this->current_action = NULL;
255 DEBUG("trying to push NULL action...\n");
259 if (curr->is_rmwc()||curr->is_rmw()) {
260 ModelAction *tmp=process_rmw(curr);
261 already_added = true;
265 ModelAction * tmp = node_stack->explore_action(curr);
267 /* Discard duplicate ModelAction; use action from NodeStack */
268 /* First restore type and order in case of RMW operation */
270 tmp->copy_typeandorder(curr);
275 * Perform one-time actions when pushing new ModelAction onto
278 curr->create_cv(get_parent_action(curr->get_tid()));
279 /* Build may_read_from set */
281 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 /* Assign reads_from values */
292 Thread *th = get_thread(curr->get_tid());
293 uint64_t value = VALUE_NONE;
294 if (curr->is_read()) {
295 const ModelAction *reads_from = curr->get_node()->get_read_from();
296 value = reads_from->get_value();
297 /* Assign reads_from, perform release/acquire synchronization */
298 curr->read_from(reads_from);
299 r_modification_order(curr,reads_from);
300 } else if (curr->is_write()) {
301 w_modification_order(curr);
304 th->set_return_value(value);
306 /* Add action to list. */
308 add_action_to_lists(curr);
310 /* Is there a better interface for setting the next thread rather
311 than this field/convoluted approach? Perhaps like just returning
314 /* Do not split atomic actions. */
315 if (curr->is_rmwr()) {
316 nextThread = thread_current()->get_id();
318 nextThread = get_next_replay_thread();
321 Node *currnode = curr->get_node();
322 Node *parnode = currnode->get_parent();
324 if (!parnode->backtrack_empty()||!currnode->readsfrom_empty())
325 if (!next_backtrack || *curr > *next_backtrack)
326 next_backtrack = curr;
328 set_backtracking(curr);
331 /** @returns whether the current trace is feasible. */
332 bool ModelChecker::isfeasible() {
333 return !cyclegraph->checkForCycles();
336 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
337 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
338 int tid = id_to_int(act->get_tid());
339 ModelAction *lastread=get_last_action(tid);
340 lastread->process_rmw(act);
342 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
347 * Updates the cyclegraph with the constraints imposed from the current read.
348 * @param curr The current action. Must be a read.
349 * @param rf The action that curr reads from. Must be a write.
351 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
352 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
354 ASSERT(curr->is_read());
356 /* Iterate over all threads */
357 for (i = 0; i < thrd_lists->size(); i++) {
358 /* Iterate over actions in thread, starting from most recent */
359 action_list_t *list = &(*thrd_lists)[i];
360 action_list_t::reverse_iterator rit;
361 for (rit = list->rbegin(); rit != list->rend(); rit++) {
362 ModelAction *act = *rit;
364 /* Include at most one act per-thread that "happens before" curr */
365 if (act->happens_before(curr)) {
366 if (act->is_read()) {
367 const ModelAction * prevreadfrom=act->get_reads_from();
368 if (rf!=prevreadfrom)
369 cyclegraph->addEdge(rf, prevreadfrom);
370 } else if (rf!=act) {
371 cyclegraph->addEdge(rf, act);
380 * Updates the cyclegraph with the constraints imposed from the current write.
381 * @param curr The current action. Must be a write.
383 void ModelChecker::w_modification_order(ModelAction * curr) {
384 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
386 ASSERT(curr->is_write());
388 if (curr->is_seqcst()) {
389 /* We have to at least see the last sequentially consistent write,
390 so we are initialized. */
391 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
392 if (last_seq_cst!=NULL)
393 cyclegraph->addEdge(curr, last_seq_cst);
396 /* Iterate over all threads */
397 for (i = 0; i < thrd_lists->size(); i++) {
398 /* Iterate over actions in thread, starting from most recent */
399 action_list_t *list = &(*thrd_lists)[i];
400 action_list_t::reverse_iterator rit;
401 for (rit = list->rbegin(); rit != list->rend(); rit++) {
402 ModelAction *act = *rit;
404 /* Include at most one act per-thread that "happens before" curr */
405 if (act->happens_before(curr)) {
406 if (act->is_read()) {
407 cyclegraph->addEdge(curr, act->get_reads_from());
409 cyclegraph->addEdge(curr, act);
417 * Performs various bookkeeping operations for the current ModelAction. For
418 * instance, adds action to the per-object, per-thread action vector and to the
419 * action trace list of all thread actions.
421 * @param act is the ModelAction to add.
423 void ModelChecker::add_action_to_lists(ModelAction *act)
425 int tid = id_to_int(act->get_tid());
426 action_trace->push_back(act);
428 (*obj_map)[act->get_location()].push_back(act);
430 std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
431 if (tid >= (int)vec->size())
432 vec->resize(next_thread_id);
433 (*vec)[tid].push_back(act);
435 if ((int)thrd_last_action->size() <= tid)
436 thrd_last_action->resize(get_num_threads());
437 (*thrd_last_action)[tid] = act;
440 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
442 int nthreads = get_num_threads();
443 if ((int)thrd_last_action->size() < nthreads)
444 thrd_last_action->resize(nthreads);
445 return (*thrd_last_action)[id_to_int(tid)];
449 * Gets the last memory_order_seq_cst action (in the total global sequence)
450 * performed on a particular object (i.e., memory location).
451 * @param location The object location to check
452 * @return The last seq_cst action performed
454 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
456 action_list_t *list = &(*obj_map)[location];
457 /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
458 action_list_t::reverse_iterator rit;
459 for (rit = list->rbegin(); rit != list->rend(); rit++)
460 if ((*rit)->is_write() && (*rit)->is_seqcst())
465 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
467 ModelAction *parent = get_last_action(tid);
469 parent = get_thread(tid)->get_creation();
474 * Returns the clock vector for a given thread.
475 * @param tid The thread whose clock vector we want
476 * @return Desired clock vector
478 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
479 return get_parent_action(tid)->get_cv();
483 * Build up an initial set of all past writes that this 'read' action may read
484 * from. This set is determined by the clock vector's "happens before"
486 * @param curr is the current ModelAction that we are exploring; it must be a
489 void ModelChecker::build_reads_from_past(ModelAction *curr)
491 std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
493 ASSERT(curr->is_read());
495 ModelAction *last_seq_cst = NULL;
497 /* Track whether this object has been initialized */
498 bool initialized = false;
500 if (curr->is_seqcst()) {
501 last_seq_cst = get_last_seq_cst(curr->get_location());
502 /* We have to at least see the last sequentially consistent write,
503 so we are initialized. */
504 if (last_seq_cst != NULL)
508 /* Iterate over all threads */
509 for (i = 0; i < thrd_lists->size(); i++) {
510 /* Iterate over actions in thread, starting from most recent */
511 action_list_t *list = &(*thrd_lists)[i];
512 action_list_t::reverse_iterator rit;
513 for (rit = list->rbegin(); rit != list->rend(); rit++) {
514 ModelAction *act = *rit;
516 /* Only consider 'write' actions */
517 if (!act->is_write())
520 /* Don't consider more than one seq_cst write if we are a seq_cst read. */
521 if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
522 DEBUG("Adding action to may_read_from:\n");
527 curr->get_node()->add_read_from(act);
530 /* Include at most one act per-thread that "happens before" curr */
531 if (act->happens_before(curr)) {
539 /* TODO: need a more informative way of reporting errors */
540 printf("ERROR: may read from uninitialized atomic\n");
543 if (DBG_ENABLED() || !initialized) {
544 printf("Reached read action:\n");
546 printf("Printing may_read_from\n");
547 curr->get_node()->print_may_read_from();
548 printf("End printing may_read_from\n");
554 static void print_list(action_list_t *list)
556 action_list_t::iterator it;
558 printf("---------------------------------------------------------------------\n");
561 for (it = list->begin(); it != list->end(); it++) {
564 printf("---------------------------------------------------------------------\n");
567 void ModelChecker::print_summary(void)
570 printf("Number of executions: %d\n", num_executions);
571 printf("Total nodes created: %d\n", node_stack->get_total_nodes());
576 printf("INFEASIBLE EXECUTION!\n");
577 print_list(action_trace);
581 int ModelChecker::add_thread(Thread *t)
583 (*thread_map)[id_to_int(t->get_id())] = t;
584 scheduler->add_thread(t);
588 void ModelChecker::remove_thread(Thread *t)
590 scheduler->remove_thread(t);
594 * Switch from a user-context to the "master thread" context (a.k.a. system
595 * context). This switch is made with the intention of exploring a particular
596 * model-checking action (described by a ModelAction object). Must be called
597 * from a user-thread context.
598 * @param act The current action that will be explored. May be NULL, although
599 * there is little reason to switch to the model-checker without an action to
600 * explore (note: act == NULL is sometimes used as a hack to allow a thread to
601 * yield control without performing any progress; see thrd_join()).
602 * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
604 int ModelChecker::switch_to_master(ModelAction *act)
607 Thread * old = thread_current();
608 set_current_action(act);
609 old->set_state(THREAD_READY);
610 return Thread::swap(old, get_system_context());