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