merge stuff
[c11tester.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 #include "mutex.h"
15
16 #define INITIAL_THREAD_ID       0
17
18 ModelChecker *model;
19
20 /** @brief Constructor */
21 ModelChecker::ModelChecker(struct model_params params) :
22         /* Initialize default scheduler */
23         scheduler(new Scheduler()),
24         num_executions(0),
25         num_feasible_executions(0),
26         params(params),
27         diverge(NULL),
28         action_trace(new action_list_t()),
29         thread_map(new HashTable<int, Thread *, int>()),
30         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
31         lock_waiters_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         futurevalues(new std::vector<struct PendingFutureValue>()),
35         lazy_sync_with_release(new HashTable<void *, action_list_t, uintptr_t, 4>()),
36         thrd_last_action(new std::vector<ModelAction *>(1)),
37         node_stack(new NodeStack()),
38         mo_graph(new CycleGraph()),
39         failed_promise(false),
40         too_many_reads(false),
41         asserted(false)
42 {
43         /* Allocate this "size" on the snapshotting heap */
44         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
45         /* First thread created will have id INITIAL_THREAD_ID */
46         priv->next_thread_id = INITIAL_THREAD_ID;
47
48         lazy_sync_size = &priv->lazy_sync_size;
49 }
50
51 /** @brief Destructor */
52 ModelChecker::~ModelChecker()
53 {
54         for (int i = 0; i < get_num_threads(); i++)
55                 delete thread_map->get(i);
56         delete thread_map;
57
58         delete obj_thrd_map;
59         delete obj_map;
60         delete lock_waiters_map;
61         delete action_trace;
62
63         for (unsigned int i = 0; i < promises->size(); i++)
64                 delete (*promises)[i];
65         delete promises;
66
67         delete lazy_sync_with_release;
68
69         delete thrd_last_action;
70         delete node_stack;
71         delete scheduler;
72         delete mo_graph;
73 }
74
75 /**
76  * Restores user program to initial state and resets all model-checker data
77  * structures.
78  */
79 void ModelChecker::reset_to_initial_state()
80 {
81         DEBUG("+++ Resetting to initial state +++\n");
82         node_stack->reset_execution();
83         failed_promise = false;
84         too_many_reads = false;
85         reset_asserted();
86         snapshotObject->backTrackBeforeStep(0);
87 }
88
89 /** @returns a thread ID for a new Thread */
90 thread_id_t ModelChecker::get_next_id()
91 {
92         return priv->next_thread_id++;
93 }
94
95 /** @returns the number of user threads created during this execution */
96 int ModelChecker::get_num_threads()
97 {
98         return priv->next_thread_id;
99 }
100
101 /** @returns a sequence number for a new ModelAction */
102 modelclock_t ModelChecker::get_next_seq_num()
103 {
104         return ++priv->used_sequence_numbers;
105 }
106
107 /**
108  * @brief Choose the next thread to execute.
109  *
110  * This function chooses the next thread that should execute. It can force the
111  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
112  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
113  * The model-checker may have no preference regarding the next thread (i.e.,
114  * when exploring a new execution ordering), in which case this will return
115  * NULL.
116  * @param curr The current ModelAction. This action might guide the choice of
117  * next thread.
118  * @return The next thread to run. If the model-checker has no preference, NULL.
119  */
120 Thread * ModelChecker::get_next_thread(ModelAction *curr)
121 {
122         thread_id_t tid;
123
124         if (curr!=NULL) {
125                 /* Do not split atomic actions. */
126                 if (curr->is_rmwr())
127                         return thread_current();
128                 /* The THREAD_CREATE action points to the created Thread */
129                 else if (curr->get_type() == THREAD_CREATE)
130                         return (Thread *)curr->get_location();
131         }
132
133         /* Have we completed exploring the preselected path? */
134         if (diverge == NULL)
135                 return NULL;
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         ASSERT(tid != THREAD_ID_T_NONE);
168         return thread_map->get(id_to_int(tid));
169 }
170
171 /**
172  * Queries the model-checker for more executions to explore and, if one
173  * exists, resets the model-checker state to execute a new execution.
174  *
175  * @return If there are more executions to explore, return true. Otherwise,
176  * return false.
177  */
178 bool ModelChecker::next_execution()
179 {
180         DBG();
181
182         num_executions++;
183         if (isfinalfeasible())
184                 num_feasible_executions++;
185
186         if (isfinalfeasible() || DBG_ENABLED())
187                 print_summary();
188
189         if ((diverge = get_next_backtrack()) == NULL)
190                 return false;
191
192         if (DBG_ENABLED()) {
193                 printf("Next execution will diverge at:\n");
194                 diverge->print();
195         }
196
197         reset_to_initial_state();
198         return true;
199 }
200
201 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
202 {
203         action_type type = act->get_type();
204
205         if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
206                 /* linear search: from most recent to oldest */
207                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
208                 action_list_t::reverse_iterator rit;
209                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
210                         ModelAction *prev = *rit;
211                         if (act->is_synchronizing(prev))
212                                 return prev;
213                 }
214         } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
215                 /* linear search: from most recent to oldest */
216                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
217                 action_list_t::reverse_iterator rit;
218                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
219                         ModelAction *prev = *rit;
220                         if (prev->is_success_lock())
221                                 return prev;
222                 }
223         } else if (type==ATOMIC_UNLOCK) {
224                 /* linear search: from most recent to oldest */
225                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
226                 action_list_t::reverse_iterator rit;
227                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
228                         ModelAction *prev = *rit;
229                         if (prev->is_failed_trylock())
230                                 return prev;
231                 }
232         }
233         return NULL;
234 }
235
236 void ModelChecker::set_backtracking(ModelAction *act)
237 {
238         ModelAction *prev;
239         Node *node;
240         Thread *t = get_thread(act);
241
242         prev = get_last_conflict(act);
243         if (prev == NULL)
244                 return;
245
246         node = prev->get_node()->get_parent();
247
248         while (!node->is_enabled(t))
249                 t = t->get_parent();
250
251         /* Check if this has been explored already */
252         if (node->has_been_explored(t->get_id()))
253                 return;
254
255         /* Cache the latest backtracking point */
256         if (!priv->next_backtrack || *prev > *priv->next_backtrack)
257                 priv->next_backtrack = prev;
258
259         /* If this is a new backtracking point, mark the tree */
260         if (!node->set_backtrack(t->get_id()))
261                 return;
262         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
263                         prev->get_tid(), t->get_id());
264         if (DBG_ENABLED()) {
265                 prev->print();
266                 act->print();
267         }
268 }
269
270 /**
271  * Returns last backtracking point. The model checker will explore a different
272  * path for this point in the next execution.
273  * @return The ModelAction at which the next execution should diverge.
274  */
275 ModelAction * ModelChecker::get_next_backtrack()
276 {
277         ModelAction *next = priv->next_backtrack;
278         priv->next_backtrack = NULL;
279         return next;
280 }
281
282 /**
283  * Processes a read or rmw model action.
284  * @param curr is the read model action to process.
285  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
286  * @return True if processing this read updates the mo_graph.
287  */
288 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
289 {
290         uint64_t value;
291         bool updated = false;
292         while (true) {
293                 const ModelAction *reads_from = curr->get_node()->get_read_from();
294                 if (reads_from != NULL) {
295                         mo_graph->startChanges();
296
297                         value = reads_from->get_value();
298                         bool r_status = false;
299
300                         if (!second_part_of_rmw) {
301                                 check_recency(curr);
302                                 r_status = r_modification_order(curr, reads_from);
303                         }
304
305
306                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
307                                 mo_graph->rollbackChanges();
308                                 too_many_reads = false;
309                                 continue;
310                         }
311
312                         curr->read_from(reads_from);
313                         mo_graph->commitChanges();
314                         updated |= r_status;
315                 } else if (!second_part_of_rmw) {
316                         /* Read from future value */
317                         value = curr->get_node()->get_future_value();
318                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
319                         curr->read_from(NULL);
320                         Promise *valuepromise = new Promise(curr, value, expiration);
321                         promises->push_back(valuepromise);
322                 }
323                 get_thread(curr)->set_return_value(value);
324                 return updated;
325         }
326 }
327
328 void ModelChecker::process_mutex(ModelAction *curr) {
329         std::mutex * mutex=(std::mutex *) curr->get_location();
330         struct std::mutex_state * state=mutex->get_state();
331         switch(curr->get_type()) {
332         case ATOMIC_TRYLOCK: {
333                 bool success=!state->islocked;
334                 curr->set_try_lock(success);
335                 if (!success)
336                         break;
337         }
338                 //otherwise fall into the lock case
339         case ATOMIC_LOCK: {
340                 if (curr->get_cv()->getClock(state->alloc_tid)<=state->alloc_clock) {
341                         printf("Lock access before initialization\n");
342                         set_assert();
343                 }
344                 state->islocked=true;
345                 ModelAction *unlock=get_last_unlock(curr);
346                 //synchronize with the previous unlock statement
347                 curr->synchronize_with(unlock);
348                 break;
349         }
350         case ATOMIC_UNLOCK: {
351                 //unlock the lock
352                 state->islocked=false;
353                 //wake up the other threads
354                 action_list_t * waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
355                 //activate all the waiting threads
356                 for(action_list_t::iterator rit = waiters->begin(); rit!=waiters->end(); rit++) {
357                         add_thread(get_thread((*rit)->get_tid()));
358                 }
359                 waiters->clear();
360                 break;
361         }
362         default:
363                 ASSERT(0);
364         }
365 }
366
367
368 /**
369  * Process a write ModelAction
370  * @param curr The ModelAction to process
371  * @return True if the mo_graph was updated or promises were resolved
372  */
373 bool ModelChecker::process_write(ModelAction *curr)
374 {
375         bool updated_mod_order = w_modification_order(curr);
376         bool updated_promises = resolve_promises(curr);
377
378         if (promises->size() == 0) {
379                 for (unsigned int i = 0; i<futurevalues->size(); i++) {
380                         struct PendingFutureValue pfv = (*futurevalues)[i];
381                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
382                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
383                                 priv->next_backtrack = pfv.act;
384                 }
385                 futurevalues->resize(0);
386         }
387
388         mo_graph->commitChanges();
389         get_thread(curr)->set_return_value(VALUE_NONE);
390         return updated_mod_order || updated_promises;
391 }
392
393 /**
394  * Initialize the current action by performing one or more of the following
395  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
396  * in the NodeStack, manipulating backtracking sets, allocating and
397  * initializing clock vectors, and computing the promises to fulfill.
398  *
399  * @param curr The current action, as passed from the user context; may be
400  * freed/invalidated after the execution of this function
401  * @return The current action, as processed by the ModelChecker. Is only the
402  * same as the parameter @a curr if this is a newly-explored action.
403  */
404 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
405 {
406         ModelAction *newcurr;
407
408         if (curr->is_rmwc() || curr->is_rmw()) {
409                 newcurr = process_rmw(curr);
410                 delete curr;
411                 compute_promises(newcurr);
412                 return newcurr;
413         }
414
415         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
416         if (newcurr) {
417                 /* First restore type and order in case of RMW operation */
418                 if (curr->is_rmwr())
419                         newcurr->copy_typeandorder(curr);
420
421                 ASSERT(curr->get_location()==newcurr->get_location());
422
423                 /* Discard duplicate ModelAction; use action from NodeStack */
424                 delete curr;
425
426                 /* If we have diverged, we need to reset the clock vector. */
427                 if (diverge == NULL)
428                         newcurr->create_cv(get_parent_action(newcurr->get_tid()));
429         } else {
430                 newcurr = curr;
431                 /*
432                  * Perform one-time actions when pushing new ModelAction onto
433                  * NodeStack
434                  */
435                 curr->create_cv(get_parent_action(curr->get_tid()));
436                 if (curr->is_write())
437                         compute_promises(curr);
438         }
439         return newcurr;
440 }
441
442 bool ModelChecker::check_action_enabled(ModelAction *curr) {
443         if (curr->is_lock()) {
444                 std::mutex * lock=(std::mutex *) curr->get_location();
445                 struct std::mutex_state * state = lock->get_state();
446                 if (state->islocked) {
447                         //Stick the action in the appropriate waiting queue
448                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
449                         return false;
450                 }
451         }
452
453         return true;
454 }
455
456 /**
457  * This is the heart of the model checker routine. It performs model-checking
458  * actions corresponding to a given "current action." Among other processes, it
459  * calculates reads-from relationships, updates synchronization clock vectors,
460  * forms a memory_order constraints graph, and handles replay/backtrack
461  * execution when running permutations of previously-observed executions.
462  *
463  * @param curr The current action to process
464  * @return The next Thread that must be executed. May be NULL if ModelChecker
465  * makes no choice (e.g., according to replay execution, combining RMW actions,
466  * etc.)
467  */
468 Thread * ModelChecker::check_current_action(ModelAction *curr)
469 {
470         ASSERT(curr);
471
472         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
473
474         if (!check_action_enabled(curr)) {
475                 //we'll make the execution look like we chose to run this action
476                 //much later...when a lock is actually available to relese
477                 remove_thread(get_current_thread());
478                 get_current_thread()->set_pending(curr);
479                 return get_next_thread(NULL);
480         }
481
482         ModelAction *newcurr = initialize_curr_action(curr);
483
484         /* Add the action to lists before any other model-checking tasks */
485         if (!second_part_of_rmw)
486                 add_action_to_lists(newcurr);
487
488         /* Build may_read_from set for newly-created actions */
489         if (curr == newcurr && curr->is_read())
490                 build_reads_from_past(curr);
491         curr = newcurr;
492
493         /* Add the action to lists before any other model-checking tasks */
494         if (!second_part_of_rmw)
495                 add_action_to_lists(newcurr);
496
497         /* Build may_read_from set for newly-created actions */
498         if (curr == newcurr && curr->is_read())
499                 build_reads_from_past(curr);
500         curr = newcurr;
501
502         /* Thread specific actions */
503         switch (curr->get_type()) {
504         case THREAD_CREATE: {
505                 Thread *th = (Thread *)curr->get_location();
506                 th->set_creation(curr);
507                 break;
508         }
509         case THREAD_JOIN: {
510                 Thread *waiting, *blocking;
511                 waiting = get_thread(curr);
512                 blocking = (Thread *)curr->get_location();
513                 if (!blocking->is_complete()) {
514                         blocking->push_wait_list(curr);
515                         scheduler->sleep(waiting);
516                 } else {
517                         do_complete_join(curr);
518                 }
519                 break;
520         }
521         case THREAD_FINISH: {
522                 Thread *th = get_thread(curr);
523                 while (!th->wait_list_empty()) {
524                         ModelAction *act = th->pop_wait_list();
525                         Thread *wake = get_thread(act);
526                         scheduler->wake(wake);
527                         do_complete_join(act);
528                 }
529                 th->complete();
530                 break;
531         }
532         case THREAD_START: {
533                 check_promises(NULL, curr->get_cv());
534                 break;
535         }
536         default:
537                 break;
538         }
539
540         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
541
542         while (!work_queue.empty()) {
543                 WorkQueueEntry work = work_queue.front();
544                 work_queue.pop_front();
545
546                 switch (work.type) {
547                 case WORK_CHECK_CURR_ACTION: {
548                         ModelAction *act = work.action;
549                         bool updated = false;
550                         if (act->is_read() && process_read(act, second_part_of_rmw))
551                                 updated = true;
552
553                         if (act->is_write() && process_write(act))
554                                 updated = true;
555
556                         if (act->is_mutex_op()) 
557                                 process_mutex(act);
558
559                         if (updated)
560                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
561                         break;
562                 }
563                 case WORK_CHECK_RELEASE_SEQ:
564                         resolve_release_sequences(work.location, &work_queue);
565                         break;
566                 case WORK_CHECK_MO_EDGES: {
567                         /** @todo Complete verification of work_queue */
568                         ModelAction *act = work.action;
569                         bool updated = false;
570
571                         if (act->is_read()) {
572                                 if (r_modification_order(act, act->get_reads_from()))
573                                         updated = true;
574                         }
575                         if (act->is_write()) {
576                                 if (w_modification_order(act))
577                                         updated = true;
578                         }
579
580                         if (updated)
581                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
582                         break;
583                 }
584                 default:
585                         ASSERT(false);
586                         break;
587                 }
588         }
589
590         check_curr_backtracking(curr);
591
592         set_backtracking(curr);
593
594         return get_next_thread(curr);
595 }
596
597 /**
598  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
599  * operation from the Thread it is joining with. Must be called after the
600  * completion of the Thread in question.
601  * @param join The THREAD_JOIN action
602  */
603 void ModelChecker::do_complete_join(ModelAction *join)
604 {
605         Thread *blocking = (Thread *)join->get_location();
606         ModelAction *act = get_last_action(blocking->get_id());
607         join->synchronize_with(act);
608 }
609
610 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
611         Node *currnode = curr->get_node();
612         Node *parnode = currnode->get_parent();
613
614         if ((!parnode->backtrack_empty() ||
615                          !currnode->read_from_empty() ||
616                          !currnode->future_value_empty() ||
617                          !currnode->promise_empty())
618                         && (!priv->next_backtrack ||
619                                         *curr > *priv->next_backtrack)) {
620                 priv->next_backtrack = curr;
621         }
622 }
623
624 bool ModelChecker::promises_expired() {
625         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
626                 Promise *promise = (*promises)[promise_index];
627                 if (promise->get_expiration()<priv->used_sequence_numbers) {
628                         return true;
629                 }
630         }
631         return false;
632 }
633
634 /** @returns whether the current partial trace must be a prefix of a
635  * feasible trace. */
636 bool ModelChecker::isfeasibleprefix() {
637         return promises->size() == 0 && *lazy_sync_size == 0;
638 }
639
640 /** @returns whether the current partial trace is feasible. */
641 bool ModelChecker::isfeasible() {
642         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
643 }
644
645 /** @returns whether the current partial trace is feasible other than
646  * multiple RMW reading from the same store. */
647 bool ModelChecker::isfeasibleotherthanRMW() {
648         if (DBG_ENABLED()) {
649                 if (mo_graph->checkForCycles())
650                         DEBUG("Infeasible: modification order cycles\n");
651                 if (failed_promise)
652                         DEBUG("Infeasible: failed promise\n");
653                 if (too_many_reads)
654                         DEBUG("Infeasible: too many reads\n");
655                 if (promises_expired())
656                         DEBUG("Infeasible: promises expired\n");
657         }
658         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
659 }
660
661 /** Returns whether the current completed trace is feasible. */
662 bool ModelChecker::isfinalfeasible() {
663         if (DBG_ENABLED() && promises->size() != 0)
664                 DEBUG("Infeasible: unrevolved promises\n");
665
666         return isfeasible() && promises->size() == 0;
667 }
668
669 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
670 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
671         int tid = id_to_int(act->get_tid());
672         ModelAction *lastread = get_last_action(tid);
673         lastread->process_rmw(act);
674         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
675                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
676                 mo_graph->commitChanges();
677         }
678         return lastread;
679 }
680
681 /**
682  * Checks whether a thread has read from the same write for too many times
683  * without seeing the effects of a later write.
684  *
685  * Basic idea:
686  * 1) there must a different write that we could read from that would satisfy the modification order,
687  * 2) we must have read from the same value in excess of maxreads times, and
688  * 3) that other write must have been in the reads_from set for maxreads times.
689  *
690  * If so, we decide that the execution is no longer feasible.
691  */
692 void ModelChecker::check_recency(ModelAction *curr) {
693         if (params.maxreads != 0) {
694                 if (curr->get_node()->get_read_from_size() <= 1)
695                         return;
696
697                 //Must make sure that execution is currently feasible...  We could
698                 //accidentally clear by rolling back
699                 if (!isfeasible())
700                         return;
701
702                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
703                 int tid = id_to_int(curr->get_tid());
704
705                 /* Skip checks */
706                 if ((int)thrd_lists->size() <= tid)
707                         return;
708
709                 action_list_t *list = &(*thrd_lists)[tid];
710
711                 action_list_t::reverse_iterator rit = list->rbegin();
712                 /* Skip past curr */
713                 for (; (*rit) != curr; rit++)
714                         ;
715                 /* go past curr now */
716                 rit++;
717
718                 action_list_t::reverse_iterator ritcopy = rit;
719                 //See if we have enough reads from the same value
720                 int count = 0;
721                 for (; count < params.maxreads; rit++,count++) {
722                         if (rit==list->rend())
723                                 return;
724                         ModelAction *act = *rit;
725                         if (!act->is_read())
726                                 return;
727                         if (act->get_reads_from() != curr->get_reads_from())
728                                 return;
729                         if (act->get_node()->get_read_from_size() <= 1)
730                                 return;
731                 }
732
733                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
734                         //Get write
735                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
736                         //Need a different write
737                         if (write==curr->get_reads_from())
738                                 continue;
739
740                         /* Test to see whether this is a feasible write to read from*/
741                         mo_graph->startChanges();
742                         r_modification_order(curr, write);
743                         bool feasiblereadfrom = isfeasible();
744                         mo_graph->rollbackChanges();
745
746                         if (!feasiblereadfrom)
747                                 continue;
748                         rit = ritcopy;
749
750                         bool feasiblewrite = true;
751                         //new we need to see if this write works for everyone
752
753                         for (int loop = count; loop>0; loop--,rit++) {
754                                 ModelAction *act=*rit;
755                                 bool foundvalue = false;
756                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
757                                         if (act->get_node()->get_read_from_at(i)==write) {
758                                                 foundvalue = true;
759                                                 break;
760                                         }
761                                 }
762                                 if (!foundvalue) {
763                                         feasiblewrite = false;
764                                         break;
765                                 }
766                         }
767                         if (feasiblewrite) {
768                                 too_many_reads = true;
769                                 return;
770                         }
771                 }
772         }
773 }
774
775 /**
776  * Updates the mo_graph with the constraints imposed from the current
777  * read.  
778  *
779  * Basic idea is the following: Go through each other thread and find
780  * the lastest action that happened before our read.  Two cases:
781  *
782  * (1) The action is a write => that write must either occur before
783  * the write we read from or be the write we read from.
784  *
785  * (2) The action is a read => the write that that action read from
786  * must occur before the write we read from or be the same write.
787  *
788  * @param curr The current action. Must be a read.
789  * @param rf The action that curr reads from. Must be a write.
790  * @return True if modification order edges were added; false otherwise
791  */
792 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
793 {
794         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
795         unsigned int i;
796         bool added = false;
797         ASSERT(curr->is_read());
798
799         /* Iterate over all threads */
800         for (i = 0; i < thrd_lists->size(); i++) {
801                 /* Iterate over actions in thread, starting from most recent */
802                 action_list_t *list = &(*thrd_lists)[i];
803                 action_list_t::reverse_iterator rit;
804                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
805                         ModelAction *act = *rit;
806
807                         /*
808                          * Include at most one act per-thread that "happens
809                          * before" curr. Don't consider reflexively.
810                          */
811                         if (act->happens_before(curr) && act != curr) {
812                                 if (act->is_write()) {
813                                         if (rf != act) {
814                                                 mo_graph->addEdge(act, rf);
815                                                 added = true;
816                                         }
817                                 } else {
818                                         const ModelAction *prevreadfrom = act->get_reads_from();
819                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
820                                                 mo_graph->addEdge(prevreadfrom, rf);
821                                                 added = true;
822                                         }
823                                 }
824                                 break;
825                         }
826                 }
827         }
828
829         return added;
830 }
831
832 /** This method fixes up the modification order when we resolve a
833  *  promises.  The basic problem is that actions that occur after the
834  *  read curr could not property add items to the modification order
835  *  for our read.
836  *  
837  *  So for each thread, we find the earliest item that happens after
838  *  the read curr.  This is the item we have to fix up with additional
839  *  constraints.  If that action is write, we add a MO edge between
840  *  the Action rf and that action.  If the action is a read, we add a
841  *  MO edge between the Action rf, and whatever the read accessed.
842  *
843  * @param curr is the read ModelAction that we are fixing up MO edges for.
844  * @param rf is the write ModelAction that curr reads from.
845  *
846  */
847
848 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
849 {
850         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
851         unsigned int i;
852         ASSERT(curr->is_read());
853
854         /* Iterate over all threads */
855         for (i = 0; i < thrd_lists->size(); i++) {
856                 /* Iterate over actions in thread, starting from most recent */
857                 action_list_t *list = &(*thrd_lists)[i];
858                 action_list_t::reverse_iterator rit;
859                 ModelAction *lastact = NULL;
860
861                 /* Find last action that happens after curr */
862                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
863                         ModelAction *act = *rit;
864                         if (curr->happens_before(act)) {
865                                 lastact = act;
866                         } else
867                                 break;
868                 }
869
870                         /* Include at most one act per-thread that "happens before" curr */
871                 if (lastact != NULL) {
872                         if (lastact->is_read()) {
873                                 const ModelAction *postreadfrom = lastact->get_reads_from();
874                                 if (postreadfrom != NULL&&rf != postreadfrom)
875                                         mo_graph->addEdge(rf, postreadfrom);
876                         } else if (rf != lastact) {
877                                 mo_graph->addEdge(rf, lastact);
878                         }
879                         break;
880                 }
881         }
882 }
883
884 /**
885  * Updates the mo_graph with the constraints imposed from the current write.
886  *
887  * Basic idea is the following: Go through each other thread and find
888  * the lastest action that happened before our write.  Two cases:
889  *
890  * (1) The action is a write => that write must occur before
891  * the current write
892  *
893  * (2) The action is a read => the write that that action read from
894  * must occur before the current write.
895  *
896  * This method also handles two other issues:
897  *
898  * (I) Sequential Consistency: Making sure that if the current write is
899  * seq_cst, that it occurs after the previous seq_cst write.
900  *
901  * (II) Sending the write back to non-synchronizing reads.
902  *
903  * @param curr The current action. Must be a write.
904  * @return True if modification order edges were added; false otherwise
905  */
906 bool ModelChecker::w_modification_order(ModelAction *curr)
907 {
908         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
909         unsigned int i;
910         bool added = false;
911         ASSERT(curr->is_write());
912
913         if (curr->is_seqcst()) {
914                 /* We have to at least see the last sequentially consistent write,
915                          so we are initialized. */
916                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
917                 if (last_seq_cst != NULL) {
918                         mo_graph->addEdge(last_seq_cst, curr);
919                         added = true;
920                 }
921         }
922
923         /* Iterate over all threads */
924         for (i = 0; i < thrd_lists->size(); i++) {
925                 /* Iterate over actions in thread, starting from most recent */
926                 action_list_t *list = &(*thrd_lists)[i];
927                 action_list_t::reverse_iterator rit;
928                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
929                         ModelAction *act = *rit;
930                         if (act == curr) {
931                                 /*
932                                  * If RMW, we already have all relevant edges,
933                                  * so just skip to next thread.
934                                  * If normal write, we need to look at earlier
935                                  * actions, so continue processing list.
936                                  */
937                                 if (curr->is_rmw())
938                                         break;
939                                 else
940                                         continue;
941                         }
942
943                         /*
944                          * Include at most one act per-thread that "happens
945                          * before" curr
946                          */
947                         if (act->happens_before(curr)) {
948                                 /*
949                                  * Note: if act is RMW, just add edge:
950                                  *   act --mo--> curr
951                                  * The following edge should be handled elsewhere:
952                                  *   readfrom(act) --mo--> act
953                                  */
954                                 if (act->is_write())
955                                         mo_graph->addEdge(act, curr);
956                                 else if (act->is_read() && act->get_reads_from() != NULL)
957                                         mo_graph->addEdge(act->get_reads_from(), curr);
958                                 added = true;
959                                 break;
960                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
961                                                      !act->same_thread(curr)) {
962                                 /* We have an action that:
963                                    (1) did not happen before us
964                                    (2) is a read and we are a write
965                                    (3) cannot synchronize with us
966                                    (4) is in a different thread
967                                    =>
968                                    that read could potentially read from our write.
969                                  */
970                                 if (thin_air_constraint_may_allow(curr, act)) {
971                                         if (isfeasible() ||
972                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
973                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
974                                                 futurevalues->push_back(pfv);
975                                         }
976                                 }
977                         }
978                 }
979         }
980
981         return added;
982 }
983
984 /** Arbitrary reads from the future are not allowed.  Section 29.3
985  * part 9 places some constraints.  This method checks one result of constraint
986  * constraint.  Others require compiler support. */
987
988 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
989         if (!writer->is_rmw())
990                 return true;
991
992         if (!reader->is_rmw())
993                 return true;
994
995         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
996                 if (search==reader)
997                         return false;
998                 if (search->get_tid() == reader->get_tid() &&
999                                 search->happens_before(reader))
1000                         break;
1001         }
1002
1003         return true;
1004 }
1005
1006 /**
1007  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1008  * The ModelAction under consideration is expected to be taking part in
1009  * release/acquire synchronization as an object of the "reads from" relation.
1010  * Note that this can only provide release sequence support for RMW chains
1011  * which do not read from the future, as those actions cannot be traced until
1012  * their "promise" is fulfilled. Similarly, we may not even establish the
1013  * presence of a release sequence with certainty, as some modification order
1014  * constraints may be decided further in the future. Thus, this function
1015  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1016  * and a boolean representing certainty.
1017  *
1018  * @todo Finish lazy updating, when promises are fulfilled in the future
1019  * @param rf The action that might be part of a release sequence. Must be a
1020  * write.
1021  * @param release_heads A pass-by-reference style return parameter.  After
1022  * execution of this function, release_heads will contain the heads of all the
1023  * relevant release sequences, if any exists
1024  * @return true, if the ModelChecker is certain that release_heads is complete;
1025  * false otherwise
1026  */
1027 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1028 {
1029         if (!rf) {
1030                 /* read from future: need to settle this later */
1031                 return false; /* incomplete */
1032         }
1033
1034         ASSERT(rf->is_write());
1035
1036         if (rf->is_release())
1037                 release_heads->push_back(rf);
1038         if (rf->is_rmw()) {
1039                 /* We need a RMW action that is both an acquire and release to stop */
1040                 /** @todo Need to be smarter here...  In the linux lock
1041                  * example, this will run to the beginning of the program for
1042                  * every acquire. */
1043                 if (rf->is_acquire() && rf->is_release())
1044                         return true; /* complete */
1045                 return release_seq_head(rf->get_reads_from(), release_heads);
1046         }
1047         if (rf->is_release())
1048                 return true; /* complete */
1049
1050         /* else relaxed write; check modification order for contiguous subsequence
1051          * -> rf must be same thread as release */
1052         int tid = id_to_int(rf->get_tid());
1053         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1054         action_list_t *list = &(*thrd_lists)[tid];
1055         action_list_t::const_reverse_iterator rit;
1056
1057         /* Find rf in the thread list */
1058         rit = std::find(list->rbegin(), list->rend(), rf);
1059         ASSERT(rit != list->rend());
1060
1061         /* Find the last write/release */
1062         for (; rit != list->rend(); rit++)
1063                 if ((*rit)->is_release())
1064                         break;
1065         if (rit == list->rend()) {
1066                 /* No write-release in this thread */
1067                 return true; /* complete */
1068         }
1069         ModelAction *release = *rit;
1070
1071         ASSERT(rf->same_thread(release));
1072
1073         bool certain = true;
1074         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1075                 if (id_to_int(rf->get_tid()) == (int)i)
1076                         continue;
1077                 list = &(*thrd_lists)[i];
1078
1079                 /* Can we ensure no future writes from this thread may break
1080                  * the release seq? */
1081                 bool future_ordered = false;
1082
1083                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1084                         const ModelAction *act = *rit;
1085                         if (!act->is_write())
1086                                 continue;
1087                         /* Reach synchronization -> this thread is complete */
1088                         if (act->happens_before(release))
1089                                 break;
1090                         if (rf->happens_before(act)) {
1091                                 future_ordered = true;
1092                                 continue;
1093                         }
1094
1095                         /* Check modification order */
1096                         if (mo_graph->checkReachable(rf, act)) {
1097                                 /* rf --mo--> act */
1098                                 future_ordered = true;
1099                                 continue;
1100                         }
1101                         if (mo_graph->checkReachable(act, release))
1102                                 /* act --mo--> release */
1103                                 break;
1104                         if (mo_graph->checkReachable(release, act) &&
1105                                       mo_graph->checkReachable(act, rf)) {
1106                                 /* release --mo-> act --mo--> rf */
1107                                 return true; /* complete */
1108                         }
1109                         certain = false;
1110                 }
1111                 if (!future_ordered)
1112                         return false; /* This thread is uncertain */
1113         }
1114
1115         if (certain)
1116                 release_heads->push_back(release);
1117         return certain;
1118 }
1119
1120 /**
1121  * A public interface for getting the release sequence head(s) with which a
1122  * given ModelAction must synchronize. This function only returns a non-empty
1123  * result when it can locate a release sequence head with certainty. Otherwise,
1124  * it may mark the internal state of the ModelChecker so that it will handle
1125  * the release sequence at a later time, causing @a act to update its
1126  * synchronization at some later point in execution.
1127  * @param act The 'acquire' action that may read from a release sequence
1128  * @param release_heads A pass-by-reference return parameter. Will be filled
1129  * with the head(s) of the release sequence(s), if they exists with certainty.
1130  * @see ModelChecker::release_seq_head
1131  */
1132 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1133 {
1134         const ModelAction *rf = act->get_reads_from();
1135         bool complete;
1136         complete = release_seq_head(rf, release_heads);
1137         if (!complete) {
1138                 /* add act to 'lazy checking' list */
1139                 action_list_t *list;
1140                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1141                 list->push_back(act);
1142                 (*lazy_sync_size)++;
1143         }
1144 }
1145
1146 /**
1147  * Attempt to resolve all stashed operations that might synchronize with a
1148  * release sequence for a given location. This implements the "lazy" portion of
1149  * determining whether or not a release sequence was contiguous, since not all
1150  * modification order information is present at the time an action occurs.
1151  *
1152  * @param location The location/object that should be checked for release
1153  * sequence resolutions
1154  * @param work_queue The work queue to which to add work items as they are
1155  * generated
1156  * @return True if any updates occurred (new synchronization, new mo_graph
1157  * edges)
1158  */
1159 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1160 {
1161         action_list_t *list;
1162         list = lazy_sync_with_release->getptr(location);
1163         if (!list)
1164                 return false;
1165
1166         bool updated = false;
1167         action_list_t::iterator it = list->begin();
1168         while (it != list->end()) {
1169                 ModelAction *act = *it;
1170                 const ModelAction *rf = act->get_reads_from();
1171                 rel_heads_list_t release_heads;
1172                 bool complete;
1173                 complete = release_seq_head(rf, &release_heads);
1174                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1175                         if (!act->has_synchronized_with(release_heads[i])) {
1176                                 updated = true;
1177                                 act->synchronize_with(release_heads[i]);
1178                         }
1179                 }
1180
1181                 if (updated) {
1182                         /* Re-check act for mo_graph edges */
1183                         work_queue->push_back(MOEdgeWorkEntry(act));
1184
1185                         /* propagate synchronization to later actions */
1186                         action_list_t::reverse_iterator it = action_trace->rbegin();
1187                         while ((*it) != act) {
1188                                 ModelAction *propagate = *it;
1189                                 if (act->happens_before(propagate)) {
1190                                         propagate->synchronize_with(act);
1191                                         /* Re-check 'propagate' for mo_graph edges */
1192                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1193                                 }
1194                         }
1195                 }
1196                 if (complete) {
1197                         it = list->erase(it);
1198                         (*lazy_sync_size)--;
1199                 } else
1200                         it++;
1201         }
1202
1203         // If we resolved promises or data races, see if we have realized a data race.
1204         if (checkDataRaces()) {
1205                 set_assert();
1206         }
1207
1208         return updated;
1209 }
1210
1211 /**
1212  * Performs various bookkeeping operations for the current ModelAction. For
1213  * instance, adds action to the per-object, per-thread action vector and to the
1214  * action trace list of all thread actions.
1215  *
1216  * @param act is the ModelAction to add.
1217  */
1218 void ModelChecker::add_action_to_lists(ModelAction *act)
1219 {
1220         int tid = id_to_int(act->get_tid());
1221         action_trace->push_back(act);
1222
1223         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1224
1225         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1226         if (tid >= (int)vec->size())
1227                 vec->resize(priv->next_thread_id);
1228         (*vec)[tid].push_back(act);
1229
1230         if ((int)thrd_last_action->size() <= tid)
1231                 thrd_last_action->resize(get_num_threads());
1232         (*thrd_last_action)[tid] = act;
1233 }
1234
1235 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1236 {
1237         int threadid=id_to_int(tid);
1238         if (threadid<(int)thrd_last_action->size())
1239                 return (*thrd_last_action)[id_to_int(tid)];
1240         else
1241                 return NULL;
1242 }
1243
1244 /**
1245  * Gets the last memory_order_seq_cst write (in the total global sequence)
1246  * performed on a particular object (i.e., memory location), not including the
1247  * current action.
1248  * @param curr The current ModelAction; also denotes the object location to
1249  * check
1250  * @return The last seq_cst write
1251  */
1252 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1253 {
1254         void *location = curr->get_location();
1255         action_list_t *list = obj_map->get_safe_ptr(location);
1256         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1257         action_list_t::reverse_iterator rit;
1258         for (rit = list->rbegin(); rit != list->rend(); rit++)
1259                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1260                         return *rit;
1261         return NULL;
1262 }
1263
1264 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr)
1265 {
1266         void *location = curr->get_location();
1267         action_list_t *list = obj_map->get_safe_ptr(location);
1268         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1269         action_list_t::reverse_iterator rit;
1270         for (rit = list->rbegin(); rit != list->rend(); rit++)
1271                 if ((*rit)->is_unlock())
1272                         return *rit;
1273         return NULL;
1274 }
1275
1276 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1277 {
1278         ModelAction *parent = get_last_action(tid);
1279         if (!parent)
1280                 parent = get_thread(tid)->get_creation();
1281         return parent;
1282 }
1283
1284 /**
1285  * Returns the clock vector for a given thread.
1286  * @param tid The thread whose clock vector we want
1287  * @return Desired clock vector
1288  */
1289 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1290 {
1291         return get_parent_action(tid)->get_cv();
1292 }
1293
1294 /**
1295  * Resolve a set of Promises with a current write. The set is provided in the
1296  * Node corresponding to @a write.
1297  * @param write The ModelAction that is fulfilling Promises
1298  * @return True if promises were resolved; false otherwise
1299  */
1300 bool ModelChecker::resolve_promises(ModelAction *write)
1301 {
1302         bool resolved = false;
1303
1304         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1305                 Promise *promise = (*promises)[promise_index];
1306                 if (write->get_node()->get_promise(i)) {
1307                         ModelAction *read = promise->get_action();
1308                         read->read_from(write);
1309                         if (read->is_rmw()) {
1310                                 mo_graph->addRMWEdge(write, read);
1311                         }
1312                         //First fix up the modification order for actions that happened
1313                         //before the read
1314                         r_modification_order(read, write);
1315                         //Next fix up the modification order for actions that happened
1316                         //after the read.
1317                         post_r_modification_order(read, write);
1318                         promises->erase(promises->begin() + promise_index);
1319                         resolved = true;
1320                 } else
1321                         promise_index++;
1322         }
1323         return resolved;
1324 }
1325
1326 /**
1327  * Compute the set of promises that could potentially be satisfied by this
1328  * action. Note that the set computation actually appears in the Node, not in
1329  * ModelChecker.
1330  * @param curr The ModelAction that may satisfy promises
1331  */
1332 void ModelChecker::compute_promises(ModelAction *curr)
1333 {
1334         for (unsigned int i = 0; i < promises->size(); i++) {
1335                 Promise *promise = (*promises)[i];
1336                 const ModelAction *act = promise->get_action();
1337                 if (!act->happens_before(curr) &&
1338                                 act->is_read() &&
1339                                 !act->is_synchronizing(curr) &&
1340                                 !act->same_thread(curr) &&
1341                                 promise->get_value() == curr->get_value()) {
1342                         curr->get_node()->set_promise(i);
1343                 }
1344         }
1345 }
1346
1347 /** Checks promises in response to change in ClockVector Threads. */
1348 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1349 {
1350         for (unsigned int i = 0; i < promises->size(); i++) {
1351                 Promise *promise = (*promises)[i];
1352                 const ModelAction *act = promise->get_action();
1353                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1354                                 merge_cv->synchronized_since(act)) {
1355                         //This thread is no longer able to send values back to satisfy the promise
1356                         int num_synchronized_threads = promise->increment_threads();
1357                         if (num_synchronized_threads == get_num_threads()) {
1358                                 //Promise has failed
1359                                 failed_promise = true;
1360                                 return;
1361                         }
1362                 }
1363         }
1364 }
1365
1366 /**
1367  * Build up an initial set of all past writes that this 'read' action may read
1368  * from. This set is determined by the clock vector's "happens before"
1369  * relationship.
1370  * @param curr is the current ModelAction that we are exploring; it must be a
1371  * 'read' operation.
1372  */
1373 void ModelChecker::build_reads_from_past(ModelAction *curr)
1374 {
1375         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1376         unsigned int i;
1377         ASSERT(curr->is_read());
1378
1379         ModelAction *last_seq_cst = NULL;
1380
1381         /* Track whether this object has been initialized */
1382         bool initialized = false;
1383
1384         if (curr->is_seqcst()) {
1385                 last_seq_cst = get_last_seq_cst(curr);
1386                 /* We have to at least see the last sequentially consistent write,
1387                          so we are initialized. */
1388                 if (last_seq_cst != NULL)
1389                         initialized = true;
1390         }
1391
1392         /* Iterate over all threads */
1393         for (i = 0; i < thrd_lists->size(); i++) {
1394                 /* Iterate over actions in thread, starting from most recent */
1395                 action_list_t *list = &(*thrd_lists)[i];
1396                 action_list_t::reverse_iterator rit;
1397                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1398                         ModelAction *act = *rit;
1399
1400                         /* Only consider 'write' actions */
1401                         if (!act->is_write() || act == curr)
1402                                 continue;
1403
1404                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1405                         if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1406                                 DEBUG("Adding action to may_read_from:\n");
1407                                 if (DBG_ENABLED()) {
1408                                         act->print();
1409                                         curr->print();
1410                                 }
1411                                 curr->get_node()->add_read_from(act);
1412                         }
1413
1414                         /* Include at most one act per-thread that "happens before" curr */
1415                         if (act->happens_before(curr)) {
1416                                 initialized = true;
1417                                 break;
1418                         }
1419                 }
1420         }
1421
1422         if (!initialized) {
1423                 /** @todo Need a more informative way of reporting errors. */
1424                 printf("ERROR: may read from uninitialized atomic\n");
1425         }
1426
1427         if (DBG_ENABLED() || !initialized) {
1428                 printf("Reached read action:\n");
1429                 curr->print();
1430                 printf("Printing may_read_from\n");
1431                 curr->get_node()->print_may_read_from();
1432                 printf("End printing may_read_from\n");
1433         }
1434
1435         ASSERT(initialized);
1436 }
1437
1438 static void print_list(action_list_t *list)
1439 {
1440         action_list_t::iterator it;
1441
1442         printf("---------------------------------------------------------------------\n");
1443         printf("Trace:\n");
1444
1445         for (it = list->begin(); it != list->end(); it++) {
1446                 (*it)->print();
1447         }
1448         printf("---------------------------------------------------------------------\n");
1449 }
1450
1451 void ModelChecker::print_summary()
1452 {
1453         printf("\n");
1454         printf("Number of executions: %d\n", num_executions);
1455         printf("Number of feasible executions: %d\n", num_feasible_executions);
1456         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1457
1458 #if SUPPORT_MOD_ORDER_DUMP
1459         scheduler->print();
1460         char buffername[100];
1461         sprintf(buffername, "exec%u",num_executions);
1462         mo_graph->dumpGraphToFile(buffername);
1463 #endif
1464
1465         if (!isfinalfeasible())
1466                 printf("INFEASIBLE EXECUTION!\n");
1467         print_list(action_trace);
1468         printf("\n");
1469 }
1470
1471 /**
1472  * Add a Thread to the system for the first time. Should only be called once
1473  * per thread.
1474  * @param t The Thread to add
1475  */
1476 void ModelChecker::add_thread(Thread *t)
1477 {
1478         thread_map->put(id_to_int(t->get_id()), t);
1479         scheduler->add_thread(t);
1480 }
1481
1482 void ModelChecker::remove_thread(Thread *t)
1483 {
1484         scheduler->remove_thread(t);
1485 }
1486
1487 /**
1488  * Switch from a user-context to the "master thread" context (a.k.a. system
1489  * context). This switch is made with the intention of exploring a particular
1490  * model-checking action (described by a ModelAction object). Must be called
1491  * from a user-thread context.
1492  * @param act The current action that will be explored. Must not be NULL.
1493  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1494  */
1495 int ModelChecker::switch_to_master(ModelAction *act)
1496 {
1497         DBG();
1498         Thread *old = thread_current();
1499         set_current_action(act);
1500         old->set_state(THREAD_READY);
1501         return Thread::swap(old, &system_context);
1502 }
1503
1504 /**
1505  * Takes the next step in the execution, if possible.
1506  * @return Returns true (success) if a step was taken and false otherwise.
1507  */
1508 bool ModelChecker::take_step() {
1509         if (has_asserted())
1510                 return false;
1511
1512         Thread * curr = thread_current();
1513         if (curr) {
1514                 if (curr->get_state() == THREAD_READY) {
1515                         ASSERT(priv->current_action);
1516
1517                         priv->nextThread = check_current_action(priv->current_action);
1518                         priv->current_action = NULL;
1519                         if (curr->is_blocked() || curr->is_complete())
1520                                 scheduler->remove_thread(curr);
1521                 } else {
1522                         ASSERT(false);
1523                 }
1524         }
1525         Thread * next = scheduler->next_thread(priv->nextThread);
1526
1527         /* Infeasible -> don't take any more steps */
1528         if (!isfeasible())
1529                 return false;
1530
1531         if (next)
1532                 next->set_state(THREAD_RUNNING);
1533         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1534
1535         /* next == NULL -> don't take any more steps */
1536         if (!next)
1537                 return false;
1538
1539         if ( next->get_pending() != NULL ) {
1540                 //restart a pending action
1541                 set_current_action(next->get_pending());
1542                 next->set_pending(NULL);
1543                 next->set_state(THREAD_READY);
1544                 return true;
1545         }
1546
1547         /* Return false only if swap fails with an error */
1548         return (Thread::swap(&system_context, next) == 0);
1549 }
1550
1551 /** Runs the current execution until threre are no more steps to take. */
1552 void ModelChecker::finish_execution() {
1553         DBG();
1554
1555         while (take_step());
1556 }