69cffcdb2e7e7a0f8edccfabbe669ccc782e4f60
[model-checker.git] / model.cc
1 #include <stdio.h>
2
3 #include "model.h"
4 #include "action.h"
5 #include "nodestack.h"
6 #include "schedule.h"
7 #include "snapshot-interface.h"
8 #include "common.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
11 #include "promise.h"
12
13 #define INITIAL_THREAD_ID       0
14
15 ModelChecker *model;
16
17 /** @brief Constructor */
18 ModelChecker::ModelChecker(struct model_params params) :
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),
24         num_executions(0),
25         params(params),
26         current_action(NULL),
27         diverge(NULL),
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         lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
35         thrd_last_action(new std::vector<ModelAction *>(1)),
36         node_stack(new NodeStack()),
37         next_backtrack(NULL),
38         mo_graph(new CycleGraph()),
39         failed_promise(false)
40 {
41 }
42
43 /** @brief Destructor */
44 ModelChecker::~ModelChecker()
45 {
46         for (int i = 0; i < get_num_threads(); i++)
47                 delete thread_map->get(i);
48         delete thread_map;
49
50         delete obj_thrd_map;
51         delete obj_map;
52         delete action_trace;
53
54         for (unsigned int i = 0; i < promises->size(); i++)
55                 delete (*promises)[i];
56         delete promises;
57
58         delete lazy_sync_with_release;
59
60         delete thrd_last_action;
61         delete node_stack;
62         delete scheduler;
63         delete mo_graph;
64 }
65
66 /**
67  * Restores user program to initial state and resets all model-checker data
68  * structures.
69  */
70 void ModelChecker::reset_to_initial_state()
71 {
72         DEBUG("+++ Resetting to initial state +++\n");
73         node_stack->reset_execution();
74         current_action = NULL;
75         next_thread_id = INITIAL_THREAD_ID;
76         used_sequence_numbers = 0;
77         nextThread = 0;
78         next_backtrack = NULL;
79         failed_promise = false;
80         snapshotObject->backTrackBeforeStep(0);
81 }
82
83 /** @returns a thread ID for a new Thread */
84 thread_id_t ModelChecker::get_next_id()
85 {
86         return next_thread_id++;
87 }
88
89 /** @returns the number of user threads created during this execution */
90 int ModelChecker::get_num_threads()
91 {
92         return next_thread_id;
93 }
94
95 /** @returns a sequence number for a new ModelAction */
96 modelclock_t ModelChecker::get_next_seq_num()
97 {
98         return ++used_sequence_numbers;
99 }
100
101 /**
102  * Performs the "scheduling" for the model-checker. That is, it checks if the
103  * model-checker has selected a "next thread to run" and returns it, if
104  * available. This function should be called from the Scheduler routine, where
105  * the Scheduler falls back to a default scheduling routine if needed.
106  *
107  * @return The next thread chosen by the model-checker. If the model-checker
108  * makes no selection, retuns NULL.
109  */
110 Thread * ModelChecker::schedule_next_thread()
111 {
112         Thread *t;
113         if (nextThread == THREAD_ID_T_NONE)
114                 return NULL;
115         t = thread_map->get(id_to_int(nextThread));
116
117         ASSERT(t != NULL);
118
119         return t;
120 }
121
122 /**
123  * Choose the next thread in the replay sequence.
124  *
125  * If the replay sequence has reached the 'diverge' point, returns a thread
126  * from the backtracking set. Otherwise, simply returns the next thread in the
127  * sequence that is being replayed.
128  */
129 thread_id_t ModelChecker::get_next_replay_thread()
130 {
131         thread_id_t tid;
132
133         /* Have we completed exploring the preselected path? */
134         if (diverge == NULL)
135                 return THREAD_ID_T_NONE;
136
137         /* Else, we are trying to replay an execution */
138         ModelAction *next = node_stack->get_next()->get_action();
139
140         if (next == diverge) {
141                 Node *nextnode = next->get_node();
142                 /* Reached divergence point */
143                 if (nextnode->increment_promise()) {
144                         /* The next node will try to satisfy a different set of promises. */
145                         tid = next->get_tid();
146                         node_stack->pop_restofstack(2);
147                 } else if (nextnode->increment_read_from()) {
148                         /* The next node will read from a different value. */
149                         tid = next->get_tid();
150                         node_stack->pop_restofstack(2);
151                 } else if (nextnode->increment_future_value()) {
152                         /* The next node will try to read from a different future value. */
153                         tid = next->get_tid();
154                         node_stack->pop_restofstack(2);
155                 } else {
156                         /* Make a different thread execute for next step */
157                         Node *node = nextnode->get_parent();
158                         tid = node->get_next_backtrack();
159                         node_stack->pop_restofstack(1);
160                 }
161                 DEBUG("*** Divergence point ***\n");
162                 diverge = NULL;
163         } else {
164                 tid = next->get_tid();
165         }
166         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
167         return tid;
168 }
169
170 /**
171  * Queries the model-checker for more executions to explore and, if one
172  * exists, resets the model-checker state to execute a new execution.
173  *
174  * @return If there are more executions to explore, return true. Otherwise,
175  * return false.
176  */
177 bool ModelChecker::next_execution()
178 {
179         DBG();
180
181         num_executions++;
182
183         if (isfinalfeasible() || DBG_ENABLED())
184                 print_summary();
185
186         if ((diverge = model->get_next_backtrack()) == NULL)
187                 return false;
188
189         if (DBG_ENABLED()) {
190                 printf("Next execution will diverge at:\n");
191                 diverge->print();
192         }
193
194         model->reset_to_initial_state();
195         return true;
196 }
197
198 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
199 {
200         action_type type = act->get_type();
201
202         switch (type) {
203                 case ATOMIC_READ:
204                 case ATOMIC_WRITE:
205                 case ATOMIC_RMW:
206                         break;
207                 default:
208                         return NULL;
209         }
210         /* linear search: from most recent to oldest */
211         action_list_t *list = obj_map->get_safe_ptr(act->get_location());
212         action_list_t::reverse_iterator rit;
213         for (rit = list->rbegin(); rit != list->rend(); rit++) {
214                 ModelAction *prev = *rit;
215                 if (act->is_synchronizing(prev))
216                         return prev;
217         }
218         return NULL;
219 }
220
221 void ModelChecker::set_backtracking(ModelAction *act)
222 {
223         ModelAction *prev;
224         Node *node;
225         Thread *t = get_thread(act->get_tid());
226
227         prev = get_last_conflict(act);
228         if (prev == NULL)
229                 return;
230
231         node = prev->get_node()->get_parent();
232
233         while (!node->is_enabled(t))
234                 t = t->get_parent();
235
236         /* Check if this has been explored already */
237         if (node->has_been_explored(t->get_id()))
238                 return;
239
240         /* Cache the latest backtracking point */
241         if (!next_backtrack || *prev > *next_backtrack)
242                 next_backtrack = prev;
243
244         /* If this is a new backtracking point, mark the tree */
245         if (!node->set_backtrack(t->get_id()))
246                 return;
247         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
248                         prev->get_tid(), t->get_id());
249         if (DBG_ENABLED()) {
250                 prev->print();
251                 act->print();
252         }
253 }
254
255 /**
256  * Returns last backtracking point. The model checker will explore a different
257  * path for this point in the next execution.
258  * @return The ModelAction at which the next execution should diverge.
259  */
260 ModelAction * ModelChecker::get_next_backtrack()
261 {
262         ModelAction *next = next_backtrack;
263         next_backtrack = NULL;
264         return next;
265 }
266
267 void ModelChecker::check_current_action(void)
268 {
269         ModelAction *curr = this->current_action;
270         bool already_added = false;
271         this->current_action = NULL;
272         if (!curr) {
273                 DEBUG("trying to push NULL action...\n");
274                 return;
275         }
276
277         if (curr->is_rmwc() || curr->is_rmw()) {
278                 ModelAction *tmp = process_rmw(curr);
279                 already_added = true;
280                 delete curr;
281                 curr = tmp;
282         } else {
283                 ModelAction *tmp = node_stack->explore_action(curr);
284                 if (tmp) {
285                         /* Discard duplicate ModelAction; use action from NodeStack */
286                         /* First restore type and order in case of RMW operation */
287                         if (curr->is_rmwr())
288                                 tmp->copy_typeandorder(curr);
289
290                         /* If we have diverged, we need to reset the clock vector. */
291                         if (diverge == NULL)
292                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
293
294                         delete curr;
295                         curr = tmp;
296                 } else {
297                         /*
298                          * Perform one-time actions when pushing new ModelAction onto
299                          * NodeStack
300                          */
301                         curr->create_cv(get_parent_action(curr->get_tid()));
302                         /* Build may_read_from set */
303                         if (curr->is_read())
304                                 build_reads_from_past(curr);
305                         if (curr->is_write())
306                                 compute_promises(curr);
307                 }
308         }
309
310         /* Assign 'creation' parent */
311         if (curr->get_type() == THREAD_CREATE) {
312                 Thread *th = (Thread *)curr->get_location();
313                 th->set_creation(curr);
314         }
315
316         /* Deal with new thread */
317         if (curr->get_type() == THREAD_START)
318                 check_promises(NULL, curr->get_cv());
319
320         /* Assign reads_from values */
321         Thread *th = get_thread(curr->get_tid());
322         uint64_t value = VALUE_NONE;
323         if (curr->is_read()) {
324                 const ModelAction *reads_from = curr->get_node()->get_read_from();
325                 if (reads_from != NULL) {
326                         value = reads_from->get_value();
327                         /* Assign reads_from, perform release/acquire synchronization */
328                         curr->read_from(reads_from);
329                         r_modification_order(curr,reads_from);
330                 } else {
331                         /* Read from future value */
332                         value = curr->get_node()->get_future_value();
333                         curr->read_from(NULL);
334                         Promise *valuepromise = new Promise(curr, value);
335                         promises->push_back(valuepromise);
336                 }
337         } else if (curr->is_write()) {
338                 w_modification_order(curr);
339                 resolve_promises(curr);
340         }
341
342         th->set_return_value(value);
343
344         /* Add action to list.  */
345         if (!already_added)
346                 add_action_to_lists(curr);
347
348         /** @todo Is there a better interface for setting the next thread rather
349                  than this field/convoluted approach?  Perhaps like just returning
350                  it or something? */
351
352         /* Do not split atomic actions. */
353         if (curr->is_rmwr())
354                 nextThread = thread_current()->get_id();
355         else
356                 nextThread = get_next_replay_thread();
357
358         Node *currnode = curr->get_node();
359         Node *parnode = currnode->get_parent();
360
361         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
362                   !currnode->future_value_empty() || !currnode->promise_empty())
363                 if (!next_backtrack || *curr > *next_backtrack)
364                         next_backtrack = curr;
365
366         set_backtracking(curr);
367 }
368
369 /** @returns whether the current partial trace is feasible. */
370 bool ModelChecker::isfeasible() {
371         return !mo_graph->checkForCycles() && !failed_promise;
372 }
373
374 /** Returns whether the current completed trace is feasible. */
375 bool ModelChecker::isfinalfeasible() {
376         return isfeasible() && promises->size() == 0;
377 }
378
379 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
380 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
381         int tid = id_to_int(act->get_tid());
382         ModelAction *lastread = get_last_action(tid);
383         lastread->process_rmw(act);
384         if (act->is_rmw())
385                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
386         return lastread;
387 }
388
389 /**
390  * Updates the mo_graph with the constraints imposed from the current read.
391  * @param curr The current action. Must be a read.
392  * @param rf The action that curr reads from. Must be a write.
393  * @return True if modification order edges were added; false otherwise
394  */
395 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
396 {
397         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
398         unsigned int i;
399         bool added = false;
400         ASSERT(curr->is_read());
401
402         /* Iterate over all threads */
403         for (i = 0; i < thrd_lists->size(); i++) {
404                 /* Iterate over actions in thread, starting from most recent */
405                 action_list_t *list = &(*thrd_lists)[i];
406                 action_list_t::reverse_iterator rit;
407                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
408                         ModelAction *act = *rit;
409
410                         /* Include at most one act per-thread that "happens before" curr */
411                         if (act->happens_before(curr)) {
412                                 if (act->is_read()) {
413                                         const ModelAction *prevreadfrom = act->get_reads_from();
414                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
415                                                 mo_graph->addEdge(prevreadfrom, rf);
416                                                 added = true;
417                                         }
418                                 } else if (rf != act) {
419                                         mo_graph->addEdge(act, rf);
420                                         added = true;
421                                 }
422                                 break;
423                         }
424                 }
425         }
426
427         return added;
428 }
429
430 /** Updates the mo_graph with the constraints imposed from the current read. */
431 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
432 {
433         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
434         unsigned int i;
435         ASSERT(curr->is_read());
436
437         /* Iterate over all threads */
438         for (i = 0; i < thrd_lists->size(); i++) {
439                 /* Iterate over actions in thread, starting from most recent */
440                 action_list_t *list = &(*thrd_lists)[i];
441                 action_list_t::reverse_iterator rit;
442                 ModelAction *lastact = NULL;
443
444                 /* Find last action that happens after curr */
445                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
446                         ModelAction *act = *rit;
447                         if (curr->happens_before(act)) {
448                                 lastact = act;
449                         } else
450                                 break;
451                 }
452
453                         /* Include at most one act per-thread that "happens before" curr */
454                 if (lastact != NULL) {
455                         if (lastact->is_read()) {
456                                 const ModelAction *postreadfrom = lastact->get_reads_from();
457                                 if (postreadfrom != NULL&&rf != postreadfrom)
458                                         mo_graph->addEdge(rf, postreadfrom);
459                         } else if (rf != lastact) {
460                                 mo_graph->addEdge(rf, lastact);
461                         }
462                         break;
463                 }
464         }
465 }
466
467 /**
468  * Updates the mo_graph with the constraints imposed from the current write.
469  * @param curr The current action. Must be a write.
470  * @return True if modification order edges were added; false otherwise
471  */
472 bool ModelChecker::w_modification_order(ModelAction *curr)
473 {
474         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
475         unsigned int i;
476         bool added = false;
477         ASSERT(curr->is_write());
478
479         if (curr->is_seqcst()) {
480                 /* We have to at least see the last sequentially consistent write,
481                          so we are initialized. */
482                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
483                 if (last_seq_cst != NULL) {
484                         mo_graph->addEdge(last_seq_cst, curr);
485                         added = true;
486                 }
487         }
488
489         /* Iterate over all threads */
490         for (i = 0; i < thrd_lists->size(); i++) {
491                 /* Iterate over actions in thread, starting from most recent */
492                 action_list_t *list = &(*thrd_lists)[i];
493                 action_list_t::reverse_iterator rit;
494                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
495                         ModelAction *act = *rit;
496
497                         /* Include at most one act per-thread that "happens before" curr */
498                         if (act->happens_before(curr)) {
499                                 if (act->is_read())
500                                         mo_graph->addEdge(act->get_reads_from(), curr);
501                                 else
502                                         mo_graph->addEdge(act, curr);
503                                 added = true;
504                                 break;
505                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
506                                                      !act->same_thread(curr)) {
507                                 /* We have an action that:
508                                    (1) did not happen before us
509                                    (2) is a read and we are a write
510                                    (3) cannot synchronize with us
511                                    (4) is in a different thread
512                                    =>
513                                    that read could potentially read from our write.
514                                  */
515                                 if (act->get_node()->add_future_value(curr->get_value()) &&
516                                                 (!next_backtrack || *act > *next_backtrack))
517                                         next_backtrack = act;
518                         }
519                 }
520         }
521
522         return added;
523 }
524
525 /**
526  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
527  * The ModelAction under consideration is expected to be taking part in
528  * release/acquire synchronization as an object of the "reads from" relation.
529  * Note that this can only provide release sequence support for RMW chains
530  * which do not read from the future, as those actions cannot be traced until
531  * their "promise" is fulfilled. Similarly, we may not even establish the
532  * presence of a release sequence with certainty, as some modification order
533  * constraints may be decided further in the future. Thus, this function
534  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
535  * and a boolean representing certainty.
536  *
537  * @todo Finish lazy updating, when promises are fulfilled in the future
538  * @param rf The action that might be part of a release sequence. Must be a
539  * write.
540  * @param release_heads A pass-by-reference style return parameter.  After
541  * execution of this function, release_heads will contain the heads of all the
542  * relevant release sequences, if any exists
543  * @return true, if the ModelChecker is certain that release_heads is complete;
544  * false otherwise
545  */
546 bool ModelChecker::release_seq_head(const ModelAction *rf,
547                 std::vector<const ModelAction *> *release_heads) const
548 {
549         ASSERT(rf->is_write());
550         if (!rf) {
551                 /* read from future: need to settle this later */
552                 return false; /* incomplete */
553         }
554         if (rf->is_release())
555                 release_heads->push_back(rf);
556         if (rf->is_rmw()) {
557                 if (rf->is_acquire())
558                         return true; /* complete */
559                 return release_seq_head(rf->get_reads_from(), release_heads);
560         }
561         if (rf->is_release())
562                 return true; /* complete */
563
564         /* else relaxed write; check modification order for contiguous subsequence
565          * -> rf must be same thread as release */
566         int tid = id_to_int(rf->get_tid());
567         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
568         action_list_t *list = &(*thrd_lists)[tid];
569         action_list_t::const_reverse_iterator rit;
570
571         /* Find rf in the thread list */
572         for (rit = list->rbegin(); rit != list->rend(); rit++)
573                 if (*rit == rf)
574                         break;
575
576         /* Find the last write/release */
577         for (; rit != list->rend(); rit++)
578                 if ((*rit)->is_release())
579                         break;
580         if (rit == list->rend()) {
581                 /* No write-release in this thread */
582                 return true; /* complete */
583         }
584         ModelAction *release = *rit;
585
586         ASSERT(rf->same_thread(release));
587
588         bool certain = true;
589         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
590                 if (id_to_int(rf->get_tid()) == (int)i)
591                         continue;
592                 list = &(*thrd_lists)[i];
593                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
594                         const ModelAction *act = *rit;
595                         if (!act->is_write())
596                                 continue;
597                         /* Reach synchronization -> this thread is complete */
598                         if (act->happens_before(release))
599                                 break;
600                         if (rf->happens_before(act))
601                                 continue;
602
603                         /* Check modification order */
604                         if (mo_graph->checkReachable(rf, act))
605                                 /* rf --mo--> act */
606                                 continue;
607                         if (mo_graph->checkReachable(act, release))
608                                 /* act --mo--> release */
609                                 break;
610                         if (mo_graph->checkReachable(release, act) &&
611                                       mo_graph->checkReachable(act, rf)) {
612                                 /* release --mo-> act --mo--> rf */
613                                 return true; /* complete */
614                         }
615                         certain = false;
616                 }
617         }
618
619         if (certain)
620                 release_heads->push_back(release);
621         return certain;
622 }
623
624 /**
625  * A public interface for getting the release sequence head(s) with which a
626  * given ModelAction must synchronize. This function only returns a non-empty
627  * result when it can locate a release sequence head with certainty. Otherwise,
628  * it may mark the internal state of the ModelChecker so that it will handle
629  * the release sequence at a later time, causing @a act to update its
630  * synchronization at some later point in execution.
631  * @param act The 'acquire' action that may read from a release sequence
632  * @param release_heads A pass-by-reference return parameter. Will be filled
633  * with the head(s) of the release sequence(s), if they exists with certainty.
634  * @see ModelChecker::release_seq_head
635  */
636 void ModelChecker::get_release_seq_heads(ModelAction *act,
637                 std::vector<const ModelAction *> *release_heads)
638 {
639         const ModelAction *rf = act->get_reads_from();
640         bool complete;
641         complete = release_seq_head(rf, release_heads);
642         if (!complete) {
643                 /* add act to 'lazy checking' list */
644                 std::list<ModelAction *> *list;
645                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
646                 list->push_back(act);
647         }
648 }
649
650 /**
651  * Attempt to resolve all stashed operations that might synchronize with a
652  * release sequence for a given location. This implements the "lazy" portion of
653  * determining whether or not a release sequence was contiguous, since not all
654  * modification order information is present at the time an action occurs.
655  *
656  * @param location The location/object that should be checked for release
657  * sequence resolutions
658  * @return True if any updates occurred (new synchronization, new mo_graph edges)
659  */
660 bool ModelChecker::resolve_release_sequences(void *location)
661 {
662         std::list<ModelAction *> *list;
663         list = lazy_sync_with_release->getptr(location);
664         if (!list)
665                 return false;
666
667         bool updated = false;
668         std::list<ModelAction *>::iterator it = list->begin();
669         while (it != list->end()) {
670                 ModelAction *act = *it;
671                 const ModelAction *rf = act->get_reads_from();
672                 std::vector<const ModelAction *> release_heads;
673                 bool complete;
674                 complete = release_seq_head(rf, &release_heads);
675                 for (unsigned int i = 0; i < release_heads.size(); i++) {
676                         if (!act->has_synchronized_with(release_heads[i])) {
677                                 updated = true;
678                                 act->synchronize_with(release_heads[i]);
679                         }
680                 }
681
682                 if (updated) {
683                         /* propagate synchronization to later actions */
684                         action_list_t::reverse_iterator it = action_trace->rbegin();
685                         while ((*it) != act) {
686                                 ModelAction *propagate = *it;
687                                 if (act->happens_before(propagate))
688                                         /** @todo new mo_graph edges along with
689                                          * this synchronization? */
690                                         propagate->synchronize_with(act);
691                         }
692                 }
693                 if (complete)
694                         it = list->erase(it);
695                 else
696                         it++;
697         }
698
699         return updated;
700 }
701
702 /**
703  * Performs various bookkeeping operations for the current ModelAction. For
704  * instance, adds action to the per-object, per-thread action vector and to the
705  * action trace list of all thread actions.
706  *
707  * @param act is the ModelAction to add.
708  */
709 void ModelChecker::add_action_to_lists(ModelAction *act)
710 {
711         int tid = id_to_int(act->get_tid());
712         action_trace->push_back(act);
713
714         obj_map->get_safe_ptr(act->get_location())->push_back(act);
715
716         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
717         if (tid >= (int)vec->size())
718                 vec->resize(next_thread_id);
719         (*vec)[tid].push_back(act);
720
721         if ((int)thrd_last_action->size() <= tid)
722                 thrd_last_action->resize(get_num_threads());
723         (*thrd_last_action)[tid] = act;
724 }
725
726 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
727 {
728         int nthreads = get_num_threads();
729         if ((int)thrd_last_action->size() < nthreads)
730                 thrd_last_action->resize(nthreads);
731         return (*thrd_last_action)[id_to_int(tid)];
732 }
733
734 /**
735  * Gets the last memory_order_seq_cst action (in the total global sequence)
736  * performed on a particular object (i.e., memory location).
737  * @param location The object location to check
738  * @return The last seq_cst action performed
739  */
740 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
741 {
742         action_list_t *list = obj_map->get_safe_ptr(location);
743         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
744         action_list_t::reverse_iterator rit;
745         for (rit = list->rbegin(); rit != list->rend(); rit++)
746                 if ((*rit)->is_write() && (*rit)->is_seqcst())
747                         return *rit;
748         return NULL;
749 }
750
751 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
752 {
753         ModelAction *parent = get_last_action(tid);
754         if (!parent)
755                 parent = get_thread(tid)->get_creation();
756         return parent;
757 }
758
759 /**
760  * Returns the clock vector for a given thread.
761  * @param tid The thread whose clock vector we want
762  * @return Desired clock vector
763  */
764 ClockVector * ModelChecker::get_cv(thread_id_t tid)
765 {
766         return get_parent_action(tid)->get_cv();
767 }
768
769 /**
770  * Resolve a set of Promises with a current write. The set is provided in the
771  * Node corresponding to @a write.
772  * @param write The ModelAction that is fulfilling Promises
773  * @return True if promises were resolved; false otherwise
774  */
775 bool ModelChecker::resolve_promises(ModelAction *write)
776 {
777         bool resolved = false;
778         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
779                 Promise *promise = (*promises)[promise_index];
780                 if (write->get_node()->get_promise(i)) {
781                         ModelAction *read = promise->get_action();
782                         read->read_from(write);
783                         r_modification_order(read, write);
784                         post_r_modification_order(read, write);
785                         promises->erase(promises->begin() + promise_index);
786                         resolved = true;
787                 } else
788                         promise_index++;
789         }
790         return resolved;
791 }
792
793 /**
794  * Compute the set of promises that could potentially be satisfied by this
795  * action. Note that the set computation actually appears in the Node, not in
796  * ModelChecker.
797  * @param curr The ModelAction that may satisfy promises
798  */
799 void ModelChecker::compute_promises(ModelAction *curr)
800 {
801         for (unsigned int i = 0; i < promises->size(); i++) {
802                 Promise *promise = (*promises)[i];
803                 const ModelAction *act = promise->get_action();
804                 if (!act->happens_before(curr) &&
805                                 act->is_read() &&
806                                 !act->is_synchronizing(curr) &&
807                                 !act->same_thread(curr) &&
808                                 promise->get_value() == curr->get_value()) {
809                         curr->get_node()->set_promise(i);
810                 }
811         }
812 }
813
814 /** Checks promises in response to change in ClockVector Threads. */
815 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
816 {
817         for (unsigned int i = 0; i < promises->size(); i++) {
818                 Promise *promise = (*promises)[i];
819                 const ModelAction *act = promise->get_action();
820                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
821                                 merge_cv->synchronized_since(act)) {
822                         //This thread is no longer able to send values back to satisfy the promise
823                         int num_synchronized_threads = promise->increment_threads();
824                         if (num_synchronized_threads == model->get_num_threads()) {
825                                 //Promise has failed
826                                 failed_promise = true;
827                                 return;
828                         }
829                 }
830         }
831 }
832
833 /**
834  * Build up an initial set of all past writes that this 'read' action may read
835  * from. This set is determined by the clock vector's "happens before"
836  * relationship.
837  * @param curr is the current ModelAction that we are exploring; it must be a
838  * 'read' operation.
839  */
840 void ModelChecker::build_reads_from_past(ModelAction *curr)
841 {
842         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
843         unsigned int i;
844         ASSERT(curr->is_read());
845
846         ModelAction *last_seq_cst = NULL;
847
848         /* Track whether this object has been initialized */
849         bool initialized = false;
850
851         if (curr->is_seqcst()) {
852                 last_seq_cst = get_last_seq_cst(curr->get_location());
853                 /* We have to at least see the last sequentially consistent write,
854                          so we are initialized. */
855                 if (last_seq_cst != NULL)
856                         initialized = true;
857         }
858
859         /* Iterate over all threads */
860         for (i = 0; i < thrd_lists->size(); i++) {
861                 /* Iterate over actions in thread, starting from most recent */
862                 action_list_t *list = &(*thrd_lists)[i];
863                 action_list_t::reverse_iterator rit;
864                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
865                         ModelAction *act = *rit;
866
867                         /* Only consider 'write' actions */
868                         if (!act->is_write())
869                                 continue;
870
871                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
872                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
873                                 DEBUG("Adding action to may_read_from:\n");
874                                 if (DBG_ENABLED()) {
875                                         act->print();
876                                         curr->print();
877                                 }
878                                 curr->get_node()->add_read_from(act);
879                         }
880
881                         /* Include at most one act per-thread that "happens before" curr */
882                         if (act->happens_before(curr)) {
883                                 initialized = true;
884                                 break;
885                         }
886                 }
887         }
888
889         if (!initialized) {
890                 /** @todo Need a more informative way of reporting errors. */
891                 printf("ERROR: may read from uninitialized atomic\n");
892         }
893
894         if (DBG_ENABLED() || !initialized) {
895                 printf("Reached read action:\n");
896                 curr->print();
897                 printf("Printing may_read_from\n");
898                 curr->get_node()->print_may_read_from();
899                 printf("End printing may_read_from\n");
900         }
901
902         ASSERT(initialized);
903 }
904
905 static void print_list(action_list_t *list)
906 {
907         action_list_t::iterator it;
908
909         printf("---------------------------------------------------------------------\n");
910         printf("Trace:\n");
911
912         for (it = list->begin(); it != list->end(); it++) {
913                 (*it)->print();
914         }
915         printf("---------------------------------------------------------------------\n");
916 }
917
918 void ModelChecker::print_summary()
919 {
920         printf("\n");
921         printf("Number of executions: %d\n", num_executions);
922         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
923
924         scheduler->print();
925
926         if (!isfinalfeasible())
927                 printf("INFEASIBLE EXECUTION!\n");
928         print_list(action_trace);
929         printf("\n");
930 }
931
932 /**
933  * Add a Thread to the system for the first time. Should only be called once
934  * per thread.
935  * @param t The Thread to add
936  */
937 void ModelChecker::add_thread(Thread *t)
938 {
939         thread_map->put(id_to_int(t->get_id()), t);
940         scheduler->add_thread(t);
941 }
942
943 void ModelChecker::remove_thread(Thread *t)
944 {
945         scheduler->remove_thread(t);
946 }
947
948 /**
949  * Switch from a user-context to the "master thread" context (a.k.a. system
950  * context). This switch is made with the intention of exploring a particular
951  * model-checking action (described by a ModelAction object). Must be called
952  * from a user-thread context.
953  * @param act The current action that will be explored. May be NULL, although
954  * there is little reason to switch to the model-checker without an action to
955  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
956  * yield control without performing any progress; see thrd_join()).
957  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
958  */
959 int ModelChecker::switch_to_master(ModelAction *act)
960 {
961         DBG();
962         Thread *old = thread_current();
963         set_current_action(act);
964         old->set_state(THREAD_READY);
965         return Thread::swap(old, &system_context);
966 }
967
968 /**
969  * Takes the next step in the execution, if possible.
970  * @return Returns true (success) if a step was taken and false otherwise.
971  */
972 bool ModelChecker::take_step() {
973         Thread *curr, *next;
974
975         curr = thread_current();
976         if (curr) {
977                 if (curr->get_state() == THREAD_READY) {
978                         check_current_action();
979                         scheduler->add_thread(curr);
980                 } else if (curr->get_state() == THREAD_RUNNING) {
981                         /* Stopped while running; i.e., completed */
982                         curr->complete();
983                 } else {
984                         ASSERT(false);
985                 }
986         }
987         next = scheduler->next_thread();
988
989         /* Infeasible -> don't take any more steps */
990         if (!isfeasible())
991                 return false;
992
993         if (next)
994                 next->set_state(THREAD_RUNNING);
995         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
996
997         /* next == NULL -> don't take any more steps */
998         if (!next)
999                 return false;
1000         /* Return false only if swap fails with an error */
1001         return (Thread::swap(&system_context, next) == 0);
1002 }
1003
1004 /** Runs the current execution until threre are no more steps to take. */
1005 void ModelChecker::finish_execution() {
1006         DBG();
1007
1008         while (take_step());
1009 }