d2e4d9b1f70a092cfd2700faa1ab1d99f3d5c1a9
[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  * Performs various bookkeeping operations for the current ModelAction. For
652  * instance, adds action to the per-object, per-thread action vector and to the
653  * action trace list of all thread actions.
654  *
655  * @param act is the ModelAction to add.
656  */
657 void ModelChecker::add_action_to_lists(ModelAction *act)
658 {
659         int tid = id_to_int(act->get_tid());
660         action_trace->push_back(act);
661
662         obj_map->get_safe_ptr(act->get_location())->push_back(act);
663
664         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
665         if (tid >= (int)vec->size())
666                 vec->resize(next_thread_id);
667         (*vec)[tid].push_back(act);
668
669         if ((int)thrd_last_action->size() <= tid)
670                 thrd_last_action->resize(get_num_threads());
671         (*thrd_last_action)[tid] = act;
672 }
673
674 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
675 {
676         int nthreads = get_num_threads();
677         if ((int)thrd_last_action->size() < nthreads)
678                 thrd_last_action->resize(nthreads);
679         return (*thrd_last_action)[id_to_int(tid)];
680 }
681
682 /**
683  * Gets the last memory_order_seq_cst action (in the total global sequence)
684  * performed on a particular object (i.e., memory location).
685  * @param location The object location to check
686  * @return The last seq_cst action performed
687  */
688 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
689 {
690         action_list_t *list = obj_map->get_safe_ptr(location);
691         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
692         action_list_t::reverse_iterator rit;
693         for (rit = list->rbegin(); rit != list->rend(); rit++)
694                 if ((*rit)->is_write() && (*rit)->is_seqcst())
695                         return *rit;
696         return NULL;
697 }
698
699 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
700 {
701         ModelAction *parent = get_last_action(tid);
702         if (!parent)
703                 parent = get_thread(tid)->get_creation();
704         return parent;
705 }
706
707 /**
708  * Returns the clock vector for a given thread.
709  * @param tid The thread whose clock vector we want
710  * @return Desired clock vector
711  */
712 ClockVector * ModelChecker::get_cv(thread_id_t tid)
713 {
714         return get_parent_action(tid)->get_cv();
715 }
716
717 /**
718  * Resolve a set of Promises with a current write. The set is provided in the
719  * Node corresponding to @a write.
720  * @param write The ModelAction that is fulfilling Promises
721  * @return True if promises were resolved; false otherwise
722  */
723 bool ModelChecker::resolve_promises(ModelAction *write)
724 {
725         bool resolved = false;
726         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
727                 Promise *promise = (*promises)[promise_index];
728                 if (write->get_node()->get_promise(i)) {
729                         ModelAction *read = promise->get_action();
730                         read->read_from(write);
731                         r_modification_order(read, write);
732                         post_r_modification_order(read, write);
733                         promises->erase(promises->begin() + promise_index);
734                         resolved = true;
735                 } else
736                         promise_index++;
737         }
738         return resolved;
739 }
740
741 /**
742  * Compute the set of promises that could potentially be satisfied by this
743  * action. Note that the set computation actually appears in the Node, not in
744  * ModelChecker.
745  * @param curr The ModelAction that may satisfy promises
746  */
747 void ModelChecker::compute_promises(ModelAction *curr)
748 {
749         for (unsigned int i = 0; i < promises->size(); i++) {
750                 Promise *promise = (*promises)[i];
751                 const ModelAction *act = promise->get_action();
752                 if (!act->happens_before(curr) &&
753                                 act->is_read() &&
754                                 !act->is_synchronizing(curr) &&
755                                 !act->same_thread(curr) &&
756                                 promise->get_value() == curr->get_value()) {
757                         curr->get_node()->set_promise(i);
758                 }
759         }
760 }
761
762 /** Checks promises in response to change in ClockVector Threads. */
763 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
764 {
765         for (unsigned int i = 0; i < promises->size(); i++) {
766                 Promise *promise = (*promises)[i];
767                 const ModelAction *act = promise->get_action();
768                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
769                                 merge_cv->synchronized_since(act)) {
770                         //This thread is no longer able to send values back to satisfy the promise
771                         int num_synchronized_threads = promise->increment_threads();
772                         if (num_synchronized_threads == model->get_num_threads()) {
773                                 //Promise has failed
774                                 failed_promise = true;
775                                 return;
776                         }
777                 }
778         }
779 }
780
781 /**
782  * Build up an initial set of all past writes that this 'read' action may read
783  * from. This set is determined by the clock vector's "happens before"
784  * relationship.
785  * @param curr is the current ModelAction that we are exploring; it must be a
786  * 'read' operation.
787  */
788 void ModelChecker::build_reads_from_past(ModelAction *curr)
789 {
790         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
791         unsigned int i;
792         ASSERT(curr->is_read());
793
794         ModelAction *last_seq_cst = NULL;
795
796         /* Track whether this object has been initialized */
797         bool initialized = false;
798
799         if (curr->is_seqcst()) {
800                 last_seq_cst = get_last_seq_cst(curr->get_location());
801                 /* We have to at least see the last sequentially consistent write,
802                          so we are initialized. */
803                 if (last_seq_cst != NULL)
804                         initialized = true;
805         }
806
807         /* Iterate over all threads */
808         for (i = 0; i < thrd_lists->size(); i++) {
809                 /* Iterate over actions in thread, starting from most recent */
810                 action_list_t *list = &(*thrd_lists)[i];
811                 action_list_t::reverse_iterator rit;
812                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
813                         ModelAction *act = *rit;
814
815                         /* Only consider 'write' actions */
816                         if (!act->is_write())
817                                 continue;
818
819                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
820                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
821                                 DEBUG("Adding action to may_read_from:\n");
822                                 if (DBG_ENABLED()) {
823                                         act->print();
824                                         curr->print();
825                                 }
826                                 curr->get_node()->add_read_from(act);
827                         }
828
829                         /* Include at most one act per-thread that "happens before" curr */
830                         if (act->happens_before(curr)) {
831                                 initialized = true;
832                                 break;
833                         }
834                 }
835         }
836
837         if (!initialized) {
838                 /** @todo Need a more informative way of reporting errors. */
839                 printf("ERROR: may read from uninitialized atomic\n");
840         }
841
842         if (DBG_ENABLED() || !initialized) {
843                 printf("Reached read action:\n");
844                 curr->print();
845                 printf("Printing may_read_from\n");
846                 curr->get_node()->print_may_read_from();
847                 printf("End printing may_read_from\n");
848         }
849
850         ASSERT(initialized);
851 }
852
853 static void print_list(action_list_t *list)
854 {
855         action_list_t::iterator it;
856
857         printf("---------------------------------------------------------------------\n");
858         printf("Trace:\n");
859
860         for (it = list->begin(); it != list->end(); it++) {
861                 (*it)->print();
862         }
863         printf("---------------------------------------------------------------------\n");
864 }
865
866 void ModelChecker::print_summary()
867 {
868         printf("\n");
869         printf("Number of executions: %d\n", num_executions);
870         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
871
872         scheduler->print();
873
874         if (!isfinalfeasible())
875                 printf("INFEASIBLE EXECUTION!\n");
876         print_list(action_trace);
877         printf("\n");
878 }
879
880 /**
881  * Add a Thread to the system for the first time. Should only be called once
882  * per thread.
883  * @param t The Thread to add
884  */
885 void ModelChecker::add_thread(Thread *t)
886 {
887         thread_map->put(id_to_int(t->get_id()), t);
888         scheduler->add_thread(t);
889 }
890
891 void ModelChecker::remove_thread(Thread *t)
892 {
893         scheduler->remove_thread(t);
894 }
895
896 /**
897  * Switch from a user-context to the "master thread" context (a.k.a. system
898  * context). This switch is made with the intention of exploring a particular
899  * model-checking action (described by a ModelAction object). Must be called
900  * from a user-thread context.
901  * @param act The current action that will be explored. May be NULL, although
902  * there is little reason to switch to the model-checker without an action to
903  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
904  * yield control without performing any progress; see thrd_join()).
905  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
906  */
907 int ModelChecker::switch_to_master(ModelAction *act)
908 {
909         DBG();
910         Thread *old = thread_current();
911         set_current_action(act);
912         old->set_state(THREAD_READY);
913         return Thread::swap(old, &system_context);
914 }
915
916 /**
917  * Takes the next step in the execution, if possible.
918  * @return Returns true (success) if a step was taken and false otherwise.
919  */
920 bool ModelChecker::take_step() {
921         Thread *curr, *next;
922
923         curr = thread_current();
924         if (curr) {
925                 if (curr->get_state() == THREAD_READY) {
926                         check_current_action();
927                         scheduler->add_thread(curr);
928                 } else if (curr->get_state() == THREAD_RUNNING) {
929                         /* Stopped while running; i.e., completed */
930                         curr->complete();
931                 } else {
932                         ASSERT(false);
933                 }
934         }
935         next = scheduler->next_thread();
936
937         /* Infeasible -> don't take any more steps */
938         if (!isfeasible())
939                 return false;
940
941         if (next)
942                 next->set_state(THREAD_RUNNING);
943         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
944
945         /* next == NULL -> don't take any more steps */
946         if (!next)
947                 return false;
948         /* Return false only if swap fails with an error */
949         return (Thread::swap(&system_context, next) == 0);
950 }
951
952 /** Runs the current execution until threre are no more steps to take. */
953 void ModelChecker::finish_execution() {
954         DBG();
955
956         while (take_step());
957 }