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