more mutex changes
[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 #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                 /* Discard duplicate ModelAction; use action from NodeStack */
423                 delete curr;
424
425                 /* If we have diverged, we need to reset the clock vector. */
426                 if (diverge == NULL)
427                         newcurr->create_cv(get_parent_action(newcurr->get_tid()));
428         } else {
429                 newcurr = curr;
430                 /*
431                  * Perform one-time actions when pushing new ModelAction onto
432                  * NodeStack
433                  */
434                 curr->create_cv(get_parent_action(curr->get_tid()));
435                 if (curr->is_write())
436                         compute_promises(curr);
437         }
438         return newcurr;
439 }
440
441 bool ModelChecker::check_action_enabled(ModelAction *curr) {
442         if (curr->is_lock()) {
443                 std::mutex * lock=(std::mutex *) curr->get_location();
444                 struct std::mutex_state * state = lock->get_state();
445                 if (state->islocked) {
446                         //Stick the action in the appropriate waiting queue
447                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
448                         return false;
449                 }
450         }
451
452         return true;
453 }
454
455 /**
456  * This is the heart of the model checker routine. It performs model-checking
457  * actions corresponding to a given "current action." Among other processes, it
458  * calculates reads-from relationships, updates synchronization clock vectors,
459  * forms a memory_order constraints graph, and handles replay/backtrack
460  * execution when running permutations of previously-observed executions.
461  *
462  * @param curr The current action to process
463  * @return The next Thread that must be executed. May be NULL if ModelChecker
464  * makes no choice (e.g., according to replay execution, combining RMW actions,
465  * etc.)
466  */
467 Thread * ModelChecker::check_current_action(ModelAction *curr)
468 {
469         ASSERT(curr);
470
471         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
472
473         if (!check_action_enabled(curr)) {
474                 //we'll make the execution look like we chose to run this action
475                 //much later...when a lock is actually available to relese
476                 remove_thread(get_current_thread());
477                 get_current_thread()->set_pending(curr);
478                 return get_next_thread(NULL);
479         }
480
481         ModelAction *newcurr = initialize_curr_action(curr);
482
483         /* Add the action to lists before any other model-checking tasks */
484         if (!second_part_of_rmw)
485                 add_action_to_lists(newcurr);
486
487         /* Build may_read_from set for newly-created actions */
488         if (curr == newcurr && curr->is_read())
489                 build_reads_from_past(curr);
490         curr = newcurr;
491
492         /* Thread specific actions */
493         switch (curr->get_type()) {
494         case THREAD_CREATE: {
495                 Thread *th = (Thread *)curr->get_location();
496                 th->set_creation(curr);
497                 break;
498         }
499         case THREAD_JOIN: {
500                 Thread *waiting, *blocking;
501                 waiting = get_thread(curr);
502                 blocking = (Thread *)curr->get_location();
503                 if (!blocking->is_complete()) {
504                         blocking->push_wait_list(curr);
505                         scheduler->sleep(waiting);
506                 } else {
507                         do_complete_join(curr);
508                 }
509                 break;
510         }
511         case THREAD_FINISH: {
512                 Thread *th = get_thread(curr);
513                 while (!th->wait_list_empty()) {
514                         ModelAction *act = th->pop_wait_list();
515                         Thread *wake = get_thread(act);
516                         scheduler->wake(wake);
517                         do_complete_join(act);
518                 }
519                 th->complete();
520                 break;
521         }
522         case THREAD_START: {
523                 check_promises(NULL, curr->get_cv());
524                 break;
525         }
526         default:
527                 break;
528         }
529
530         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
531
532         while (!work_queue.empty()) {
533                 WorkQueueEntry work = work_queue.front();
534                 work_queue.pop_front();
535
536                 switch (work.type) {
537                 case WORK_CHECK_CURR_ACTION: {
538                         ModelAction *act = work.action;
539                         bool updated = false;
540                         if (act->is_read() && process_read(act, second_part_of_rmw))
541                                 updated = true;
542
543                         if (act->is_write() && process_write(act))
544                                 updated = true;
545
546                         if (act->is_mutex_op()) 
547                                 process_mutex(act);
548
549                         if (updated)
550                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
551                         break;
552                 }
553                 case WORK_CHECK_RELEASE_SEQ:
554                         resolve_release_sequences(work.location, &work_queue);
555                         break;
556                 case WORK_CHECK_MO_EDGES: {
557                         /** @todo Complete verification of work_queue */
558                         ModelAction *act = work.action;
559                         bool updated = false;
560
561                         if (act->is_read()) {
562                                 if (r_modification_order(act, act->get_reads_from()))
563                                         updated = true;
564                         }
565                         if (act->is_write()) {
566                                 if (w_modification_order(act))
567                                         updated = true;
568                         }
569
570                         if (updated)
571                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
572                         break;
573                 }
574                 default:
575                         ASSERT(false);
576                         break;
577                 }
578         }
579
580         check_curr_backtracking(curr);
581
582         set_backtracking(curr);
583
584         return get_next_thread(curr);
585 }
586
587 /**
588  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
589  * operation from the Thread it is joining with. Must be called after the
590  * completion of the Thread in question.
591  * @param join The THREAD_JOIN action
592  */
593 void ModelChecker::do_complete_join(ModelAction *join)
594 {
595         Thread *blocking = (Thread *)join->get_location();
596         ModelAction *act = get_last_action(blocking->get_id());
597         join->synchronize_with(act);
598 }
599
600 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
601         Node *currnode = curr->get_node();
602         Node *parnode = currnode->get_parent();
603
604         if ((!parnode->backtrack_empty() ||
605                          !currnode->read_from_empty() ||
606                          !currnode->future_value_empty() ||
607                          !currnode->promise_empty())
608                         && (!priv->next_backtrack ||
609                                         *curr > *priv->next_backtrack)) {
610                 priv->next_backtrack = curr;
611         }
612 }
613
614 bool ModelChecker::promises_expired() {
615         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
616                 Promise *promise = (*promises)[promise_index];
617                 if (promise->get_expiration()<priv->used_sequence_numbers) {
618                         return true;
619                 }
620         }
621         return false;
622 }
623
624 /** @returns whether the current partial trace must be a prefix of a
625  * feasible trace. */
626 bool ModelChecker::isfeasibleprefix() {
627         return promises->size() == 0 && *lazy_sync_size == 0;
628 }
629
630 /** @returns whether the current partial trace is feasible. */
631 bool ModelChecker::isfeasible() {
632         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
633 }
634
635 /** @returns whether the current partial trace is feasible other than
636  * multiple RMW reading from the same store. */
637 bool ModelChecker::isfeasibleotherthanRMW() {
638         if (DBG_ENABLED()) {
639                 if (mo_graph->checkForCycles())
640                         DEBUG("Infeasible: modification order cycles\n");
641                 if (failed_promise)
642                         DEBUG("Infeasible: failed promise\n");
643                 if (too_many_reads)
644                         DEBUG("Infeasible: too many reads\n");
645                 if (promises_expired())
646                         DEBUG("Infeasible: promises expired\n");
647         }
648         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
649 }
650
651 /** Returns whether the current completed trace is feasible. */
652 bool ModelChecker::isfinalfeasible() {
653         if (DBG_ENABLED() && promises->size() != 0)
654                 DEBUG("Infeasible: unrevolved promises\n");
655
656         return isfeasible() && promises->size() == 0;
657 }
658
659 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
660 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
661         int tid = id_to_int(act->get_tid());
662         ModelAction *lastread = get_last_action(tid);
663         lastread->process_rmw(act);
664         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
665                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
666                 mo_graph->commitChanges();
667         }
668         return lastread;
669 }
670
671 /**
672  * Checks whether a thread has read from the same write for too many times
673  * without seeing the effects of a later write.
674  *
675  * Basic idea:
676  * 1) there must a different write that we could read from that would satisfy the modification order,
677  * 2) we must have read from the same value in excess of maxreads times, and
678  * 3) that other write must have been in the reads_from set for maxreads times.
679  *
680  * If so, we decide that the execution is no longer feasible.
681  */
682 void ModelChecker::check_recency(ModelAction *curr) {
683         if (params.maxreads != 0) {
684                 if (curr->get_node()->get_read_from_size() <= 1)
685                         return;
686
687                 //Must make sure that execution is currently feasible...  We could
688                 //accidentally clear by rolling back
689                 if (!isfeasible())
690                         return;
691
692                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
693                 int tid = id_to_int(curr->get_tid());
694
695                 /* Skip checks */
696                 if ((int)thrd_lists->size() <= tid)
697                         return;
698
699                 action_list_t *list = &(*thrd_lists)[tid];
700
701                 action_list_t::reverse_iterator rit = list->rbegin();
702                 /* Skip past curr */
703                 for (; (*rit) != curr; rit++)
704                         ;
705                 /* go past curr now */
706                 rit++;
707
708                 action_list_t::reverse_iterator ritcopy = rit;
709                 //See if we have enough reads from the same value
710                 int count = 0;
711                 for (; count < params.maxreads; rit++,count++) {
712                         if (rit==list->rend())
713                                 return;
714                         ModelAction *act = *rit;
715                         if (!act->is_read())
716                                 return;
717                         if (act->get_reads_from() != curr->get_reads_from())
718                                 return;
719                         if (act->get_node()->get_read_from_size() <= 1)
720                                 return;
721                 }
722
723                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
724                         //Get write
725                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
726                         //Need a different write
727                         if (write==curr->get_reads_from())
728                                 continue;
729
730                         /* Test to see whether this is a feasible write to read from*/
731                         mo_graph->startChanges();
732                         r_modification_order(curr, write);
733                         bool feasiblereadfrom = isfeasible();
734                         mo_graph->rollbackChanges();
735
736                         if (!feasiblereadfrom)
737                                 continue;
738                         rit = ritcopy;
739
740                         bool feasiblewrite = true;
741                         //new we need to see if this write works for everyone
742
743                         for (int loop = count; loop>0; loop--,rit++) {
744                                 ModelAction *act=*rit;
745                                 bool foundvalue = false;
746                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
747                                         if (act->get_node()->get_read_from_at(i)==write) {
748                                                 foundvalue = true;
749                                                 break;
750                                         }
751                                 }
752                                 if (!foundvalue) {
753                                         feasiblewrite = false;
754                                         break;
755                                 }
756                         }
757                         if (feasiblewrite) {
758                                 too_many_reads = true;
759                                 return;
760                         }
761                 }
762         }
763 }
764
765 /**
766  * Updates the mo_graph with the constraints imposed from the current
767  * read.  
768  *
769  * Basic idea is the following: Go through each other thread and find
770  * the lastest action that happened before our read.  Two cases:
771  *
772  * (1) The action is a write => that write must either occur before
773  * the write we read from or be the write we read from.
774  *
775  * (2) The action is a read => the write that that action read from
776  * must occur before the write we read from or be the same write.
777  *
778  * @param curr The current action. Must be a read.
779  * @param rf The action that curr reads from. Must be a write.
780  * @return True if modification order edges were added; false otherwise
781  */
782 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
783 {
784         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
785         unsigned int i;
786         bool added = false;
787         ASSERT(curr->is_read());
788
789         /* Iterate over all threads */
790         for (i = 0; i < thrd_lists->size(); i++) {
791                 /* Iterate over actions in thread, starting from most recent */
792                 action_list_t *list = &(*thrd_lists)[i];
793                 action_list_t::reverse_iterator rit;
794                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
795                         ModelAction *act = *rit;
796
797                         /*
798                          * Include at most one act per-thread that "happens
799                          * before" curr. Don't consider reflexively.
800                          */
801                         if (act->happens_before(curr) && act != curr) {
802                                 if (act->is_write()) {
803                                         if (rf != act) {
804                                                 mo_graph->addEdge(act, rf);
805                                                 added = true;
806                                         }
807                                 } else {
808                                         const ModelAction *prevreadfrom = act->get_reads_from();
809                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
810                                                 mo_graph->addEdge(prevreadfrom, rf);
811                                                 added = true;
812                                         }
813                                 }
814                                 break;
815                         }
816                 }
817         }
818
819         return added;
820 }
821
822 /** This method fixes up the modification order when we resolve a
823  *  promises.  The basic problem is that actions that occur after the
824  *  read curr could not property add items to the modification order
825  *  for our read.
826  *  
827  *  So for each thread, we find the earliest item that happens after
828  *  the read curr.  This is the item we have to fix up with additional
829  *  constraints.  If that action is write, we add a MO edge between
830  *  the Action rf and that action.  If the action is a read, we add a
831  *  MO edge between the Action rf, and whatever the read accessed.
832  *
833  * @param curr is the read ModelAction that we are fixing up MO edges for.
834  * @param rf is the write ModelAction that curr reads from.
835  *
836  */
837
838 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
839 {
840         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
841         unsigned int i;
842         ASSERT(curr->is_read());
843
844         /* Iterate over all threads */
845         for (i = 0; i < thrd_lists->size(); i++) {
846                 /* Iterate over actions in thread, starting from most recent */
847                 action_list_t *list = &(*thrd_lists)[i];
848                 action_list_t::reverse_iterator rit;
849                 ModelAction *lastact = NULL;
850
851                 /* Find last action that happens after curr */
852                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
853                         ModelAction *act = *rit;
854                         if (curr->happens_before(act)) {
855                                 lastact = act;
856                         } else
857                                 break;
858                 }
859
860                         /* Include at most one act per-thread that "happens before" curr */
861                 if (lastact != NULL) {
862                         if (lastact->is_read()) {
863                                 const ModelAction *postreadfrom = lastact->get_reads_from();
864                                 if (postreadfrom != NULL&&rf != postreadfrom)
865                                         mo_graph->addEdge(rf, postreadfrom);
866                         } else if (rf != lastact) {
867                                 mo_graph->addEdge(rf, lastact);
868                         }
869                         break;
870                 }
871         }
872 }
873
874 /**
875  * Updates the mo_graph with the constraints imposed from the current write.
876  *
877  * Basic idea is the following: Go through each other thread and find
878  * the lastest action that happened before our write.  Two cases:
879  *
880  * (1) The action is a write => that write must occur before
881  * the current write
882  *
883  * (2) The action is a read => the write that that action read from
884  * must occur before the current write.
885  *
886  * This method also handles two other issues:
887  *
888  * (I) Sequential Consistency: Making sure that if the current write is
889  * seq_cst, that it occurs after the previous seq_cst write.
890  *
891  * (II) Sending the write back to non-synchronizing reads.
892  *
893  * @param curr The current action. Must be a write.
894  * @return True if modification order edges were added; false otherwise
895  */
896 bool ModelChecker::w_modification_order(ModelAction *curr)
897 {
898         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
899         unsigned int i;
900         bool added = false;
901         ASSERT(curr->is_write());
902
903         if (curr->is_seqcst()) {
904                 /* We have to at least see the last sequentially consistent write,
905                          so we are initialized. */
906                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
907                 if (last_seq_cst != NULL) {
908                         mo_graph->addEdge(last_seq_cst, curr);
909                         added = true;
910                 }
911         }
912
913         /* Iterate over all threads */
914         for (i = 0; i < thrd_lists->size(); i++) {
915                 /* Iterate over actions in thread, starting from most recent */
916                 action_list_t *list = &(*thrd_lists)[i];
917                 action_list_t::reverse_iterator rit;
918                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
919                         ModelAction *act = *rit;
920                         if (act == curr) {
921                                 /*
922                                  * If RMW, we already have all relevant edges,
923                                  * so just skip to next thread.
924                                  * If normal write, we need to look at earlier
925                                  * actions, so continue processing list.
926                                  */
927                                 if (curr->is_rmw())
928                                         break;
929                                 else
930                                         continue;
931                         }
932
933                         /*
934                          * Include at most one act per-thread that "happens
935                          * before" curr
936                          */
937                         if (act->happens_before(curr)) {
938                                 /*
939                                  * Note: if act is RMW, just add edge:
940                                  *   act --mo--> curr
941                                  * The following edge should be handled elsewhere:
942                                  *   readfrom(act) --mo--> act
943                                  */
944                                 if (act->is_write())
945                                         mo_graph->addEdge(act, curr);
946                                 else if (act->is_read() && act->get_reads_from() != NULL)
947                                         mo_graph->addEdge(act->get_reads_from(), curr);
948                                 added = true;
949                                 break;
950                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
951                                                      !act->same_thread(curr)) {
952                                 /* We have an action that:
953                                    (1) did not happen before us
954                                    (2) is a read and we are a write
955                                    (3) cannot synchronize with us
956                                    (4) is in a different thread
957                                    =>
958                                    that read could potentially read from our write.
959                                  */
960                                 if (thin_air_constraint_may_allow(curr, act)) {
961                                         if (isfeasible() ||
962                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
963                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
964                                                 futurevalues->push_back(pfv);
965                                         }
966                                 }
967                         }
968                 }
969         }
970
971         return added;
972 }
973
974 /** Arbitrary reads from the future are not allowed.  Section 29.3
975  * part 9 places some constraints.  This method checks one result of constraint
976  * constraint.  Others require compiler support. */
977
978 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
979         if (!writer->is_rmw())
980                 return true;
981
982         if (!reader->is_rmw())
983                 return true;
984
985         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
986                 if (search==reader)
987                         return false;
988                 if (search->get_tid() == reader->get_tid() &&
989                                 search->happens_before(reader))
990                         break;
991         }
992
993         return true;
994 }
995
996 /**
997  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
998  * The ModelAction under consideration is expected to be taking part in
999  * release/acquire synchronization as an object of the "reads from" relation.
1000  * Note that this can only provide release sequence support for RMW chains
1001  * which do not read from the future, as those actions cannot be traced until
1002  * their "promise" is fulfilled. Similarly, we may not even establish the
1003  * presence of a release sequence with certainty, as some modification order
1004  * constraints may be decided further in the future. Thus, this function
1005  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1006  * and a boolean representing certainty.
1007  *
1008  * @todo Finish lazy updating, when promises are fulfilled in the future
1009  * @param rf The action that might be part of a release sequence. Must be a
1010  * write.
1011  * @param release_heads A pass-by-reference style return parameter.  After
1012  * execution of this function, release_heads will contain the heads of all the
1013  * relevant release sequences, if any exists
1014  * @return true, if the ModelChecker is certain that release_heads is complete;
1015  * false otherwise
1016  */
1017 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
1018 {
1019         if (!rf) {
1020                 /* read from future: need to settle this later */
1021                 return false; /* incomplete */
1022         }
1023
1024         ASSERT(rf->is_write());
1025
1026         if (rf->is_release())
1027                 release_heads->push_back(rf);
1028         if (rf->is_rmw()) {
1029                 /* We need a RMW action that is both an acquire and release to stop */
1030                 /** @todo Need to be smarter here...  In the linux lock
1031                  * example, this will run to the beginning of the program for
1032                  * every acquire. */
1033                 if (rf->is_acquire() && rf->is_release())
1034                         return true; /* complete */
1035                 return release_seq_head(rf->get_reads_from(), release_heads);
1036         }
1037         if (rf->is_release())
1038                 return true; /* complete */
1039
1040         /* else relaxed write; check modification order for contiguous subsequence
1041          * -> rf must be same thread as release */
1042         int tid = id_to_int(rf->get_tid());
1043         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1044         action_list_t *list = &(*thrd_lists)[tid];
1045         action_list_t::const_reverse_iterator rit;
1046
1047         /* Find rf in the thread list */
1048         rit = std::find(list->rbegin(), list->rend(), rf);
1049         ASSERT(rit != list->rend());
1050
1051         /* Find the last write/release */
1052         for (; rit != list->rend(); rit++)
1053                 if ((*rit)->is_release())
1054                         break;
1055         if (rit == list->rend()) {
1056                 /* No write-release in this thread */
1057                 return true; /* complete */
1058         }
1059         ModelAction *release = *rit;
1060
1061         ASSERT(rf->same_thread(release));
1062
1063         bool certain = true;
1064         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1065                 if (id_to_int(rf->get_tid()) == (int)i)
1066                         continue;
1067                 list = &(*thrd_lists)[i];
1068
1069                 /* Can we ensure no future writes from this thread may break
1070                  * the release seq? */
1071                 bool future_ordered = false;
1072
1073                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1074                         const ModelAction *act = *rit;
1075                         if (!act->is_write())
1076                                 continue;
1077                         /* Reach synchronization -> this thread is complete */
1078                         if (act->happens_before(release))
1079                                 break;
1080                         if (rf->happens_before(act)) {
1081                                 future_ordered = true;
1082                                 continue;
1083                         }
1084
1085                         /* Check modification order */
1086                         if (mo_graph->checkReachable(rf, act)) {
1087                                 /* rf --mo--> act */
1088                                 future_ordered = true;
1089                                 continue;
1090                         }
1091                         if (mo_graph->checkReachable(act, release))
1092                                 /* act --mo--> release */
1093                                 break;
1094                         if (mo_graph->checkReachable(release, act) &&
1095                                       mo_graph->checkReachable(act, rf)) {
1096                                 /* release --mo-> act --mo--> rf */
1097                                 return true; /* complete */
1098                         }
1099                         certain = false;
1100                 }
1101                 if (!future_ordered)
1102                         return false; /* This thread is uncertain */
1103         }
1104
1105         if (certain)
1106                 release_heads->push_back(release);
1107         return certain;
1108 }
1109
1110 /**
1111  * A public interface for getting the release sequence head(s) with which a
1112  * given ModelAction must synchronize. This function only returns a non-empty
1113  * result when it can locate a release sequence head with certainty. Otherwise,
1114  * it may mark the internal state of the ModelChecker so that it will handle
1115  * the release sequence at a later time, causing @a act to update its
1116  * synchronization at some later point in execution.
1117  * @param act The 'acquire' action that may read from a release sequence
1118  * @param release_heads A pass-by-reference return parameter. Will be filled
1119  * with the head(s) of the release sequence(s), if they exists with certainty.
1120  * @see ModelChecker::release_seq_head
1121  */
1122 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1123 {
1124         const ModelAction *rf = act->get_reads_from();
1125         bool complete;
1126         complete = release_seq_head(rf, release_heads);
1127         if (!complete) {
1128                 /* add act to 'lazy checking' list */
1129                 action_list_t *list;
1130                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1131                 list->push_back(act);
1132                 (*lazy_sync_size)++;
1133         }
1134 }
1135
1136 /**
1137  * Attempt to resolve all stashed operations that might synchronize with a
1138  * release sequence for a given location. This implements the "lazy" portion of
1139  * determining whether or not a release sequence was contiguous, since not all
1140  * modification order information is present at the time an action occurs.
1141  *
1142  * @param location The location/object that should be checked for release
1143  * sequence resolutions
1144  * @param work_queue The work queue to which to add work items as they are
1145  * generated
1146  * @return True if any updates occurred (new synchronization, new mo_graph
1147  * edges)
1148  */
1149 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1150 {
1151         action_list_t *list;
1152         list = lazy_sync_with_release->getptr(location);
1153         if (!list)
1154                 return false;
1155
1156         bool updated = false;
1157         action_list_t::iterator it = list->begin();
1158         while (it != list->end()) {
1159                 ModelAction *act = *it;
1160                 const ModelAction *rf = act->get_reads_from();
1161                 rel_heads_list_t release_heads;
1162                 bool complete;
1163                 complete = release_seq_head(rf, &release_heads);
1164                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1165                         if (!act->has_synchronized_with(release_heads[i])) {
1166                                 updated = true;
1167                                 act->synchronize_with(release_heads[i]);
1168                         }
1169                 }
1170
1171                 if (updated) {
1172                         /* Re-check act for mo_graph edges */
1173                         work_queue->push_back(MOEdgeWorkEntry(act));
1174
1175                         /* propagate synchronization to later actions */
1176                         action_list_t::reverse_iterator it = action_trace->rbegin();
1177                         while ((*it) != act) {
1178                                 ModelAction *propagate = *it;
1179                                 if (act->happens_before(propagate)) {
1180                                         propagate->synchronize_with(act);
1181                                         /* Re-check 'propagate' for mo_graph edges */
1182                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1183                                 }
1184                         }
1185                 }
1186                 if (complete) {
1187                         it = list->erase(it);
1188                         (*lazy_sync_size)--;
1189                 } else
1190                         it++;
1191         }
1192
1193         // If we resolved promises or data races, see if we have realized a data race.
1194         if (checkDataRaces()) {
1195                 set_assert();
1196         }
1197
1198         return updated;
1199 }
1200
1201 /**
1202  * Performs various bookkeeping operations for the current ModelAction. For
1203  * instance, adds action to the per-object, per-thread action vector and to the
1204  * action trace list of all thread actions.
1205  *
1206  * @param act is the ModelAction to add.
1207  */
1208 void ModelChecker::add_action_to_lists(ModelAction *act)
1209 {
1210         int tid = id_to_int(act->get_tid());
1211         action_trace->push_back(act);
1212
1213         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1214
1215         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1216         if (tid >= (int)vec->size())
1217                 vec->resize(priv->next_thread_id);
1218         (*vec)[tid].push_back(act);
1219
1220         if ((int)thrd_last_action->size() <= tid)
1221                 thrd_last_action->resize(get_num_threads());
1222         (*thrd_last_action)[tid] = act;
1223 }
1224
1225 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1226 {
1227         int threadid=id_to_int(tid);
1228         if (threadid<(int)thrd_last_action->size())
1229                 return (*thrd_last_action)[id_to_int(tid)];
1230         else
1231                 return NULL;
1232 }
1233
1234 /**
1235  * Gets the last memory_order_seq_cst write (in the total global sequence)
1236  * performed on a particular object (i.e., memory location), not including the
1237  * current action.
1238  * @param curr The current ModelAction; also denotes the object location to
1239  * check
1240  * @return The last seq_cst write
1241  */
1242 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1243 {
1244         void *location = curr->get_location();
1245         action_list_t *list = obj_map->get_safe_ptr(location);
1246         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1247         action_list_t::reverse_iterator rit;
1248         for (rit = list->rbegin(); rit != list->rend(); rit++)
1249                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1250                         return *rit;
1251         return NULL;
1252 }
1253
1254 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr)
1255 {
1256         void *location = curr->get_location();
1257         action_list_t *list = obj_map->get_safe_ptr(location);
1258         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1259         action_list_t::reverse_iterator rit;
1260         for (rit = list->rbegin(); rit != list->rend(); rit++)
1261                 if ((*rit)->is_unlock())
1262                         return *rit;
1263         return NULL;
1264 }
1265
1266 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1267 {
1268         ModelAction *parent = get_last_action(tid);
1269         if (!parent)
1270                 parent = get_thread(tid)->get_creation();
1271         return parent;
1272 }
1273
1274 /**
1275  * Returns the clock vector for a given thread.
1276  * @param tid The thread whose clock vector we want
1277  * @return Desired clock vector
1278  */
1279 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1280 {
1281         return get_parent_action(tid)->get_cv();
1282 }
1283
1284 /**
1285  * Resolve a set of Promises with a current write. The set is provided in the
1286  * Node corresponding to @a write.
1287  * @param write The ModelAction that is fulfilling Promises
1288  * @return True if promises were resolved; false otherwise
1289  */
1290 bool ModelChecker::resolve_promises(ModelAction *write)
1291 {
1292         bool resolved = false;
1293
1294         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1295                 Promise *promise = (*promises)[promise_index];
1296                 if (write->get_node()->get_promise(i)) {
1297                         ModelAction *read = promise->get_action();
1298                         read->read_from(write);
1299                         if (read->is_rmw()) {
1300                                 mo_graph->addRMWEdge(write, read);
1301                         }
1302                         //First fix up the modification order for actions that happened
1303                         //before the read
1304                         r_modification_order(read, write);
1305                         //Next fix up the modification order for actions that happened
1306                         //after the read.
1307                         post_r_modification_order(read, write);
1308                         promises->erase(promises->begin() + promise_index);
1309                         resolved = true;
1310                 } else
1311                         promise_index++;
1312         }
1313         return resolved;
1314 }
1315
1316 /**
1317  * Compute the set of promises that could potentially be satisfied by this
1318  * action. Note that the set computation actually appears in the Node, not in
1319  * ModelChecker.
1320  * @param curr The ModelAction that may satisfy promises
1321  */
1322 void ModelChecker::compute_promises(ModelAction *curr)
1323 {
1324         for (unsigned int i = 0; i < promises->size(); i++) {
1325                 Promise *promise = (*promises)[i];
1326                 const ModelAction *act = promise->get_action();
1327                 if (!act->happens_before(curr) &&
1328                                 act->is_read() &&
1329                                 !act->is_synchronizing(curr) &&
1330                                 !act->same_thread(curr) &&
1331                                 promise->get_value() == curr->get_value()) {
1332                         curr->get_node()->set_promise(i);
1333                 }
1334         }
1335 }
1336
1337 /** Checks promises in response to change in ClockVector Threads. */
1338 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1339 {
1340         for (unsigned int i = 0; i < promises->size(); i++) {
1341                 Promise *promise = (*promises)[i];
1342                 const ModelAction *act = promise->get_action();
1343                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1344                                 merge_cv->synchronized_since(act)) {
1345                         //This thread is no longer able to send values back to satisfy the promise
1346                         int num_synchronized_threads = promise->increment_threads();
1347                         if (num_synchronized_threads == get_num_threads()) {
1348                                 //Promise has failed
1349                                 failed_promise = true;
1350                                 return;
1351                         }
1352                 }
1353         }
1354 }
1355
1356 /**
1357  * Build up an initial set of all past writes that this 'read' action may read
1358  * from. This set is determined by the clock vector's "happens before"
1359  * relationship.
1360  * @param curr is the current ModelAction that we are exploring; it must be a
1361  * 'read' operation.
1362  */
1363 void ModelChecker::build_reads_from_past(ModelAction *curr)
1364 {
1365         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1366         unsigned int i;
1367         ASSERT(curr->is_read());
1368
1369         ModelAction *last_seq_cst = NULL;
1370
1371         /* Track whether this object has been initialized */
1372         bool initialized = false;
1373
1374         if (curr->is_seqcst()) {
1375                 last_seq_cst = get_last_seq_cst(curr);
1376                 /* We have to at least see the last sequentially consistent write,
1377                          so we are initialized. */
1378                 if (last_seq_cst != NULL)
1379                         initialized = true;
1380         }
1381
1382         /* Iterate over all threads */
1383         for (i = 0; i < thrd_lists->size(); i++) {
1384                 /* Iterate over actions in thread, starting from most recent */
1385                 action_list_t *list = &(*thrd_lists)[i];
1386                 action_list_t::reverse_iterator rit;
1387                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1388                         ModelAction *act = *rit;
1389
1390                         /* Only consider 'write' actions */
1391                         if (!act->is_write() || act == curr)
1392                                 continue;
1393
1394                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1395                         if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1396                                 DEBUG("Adding action to may_read_from:\n");
1397                                 if (DBG_ENABLED()) {
1398                                         act->print();
1399                                         curr->print();
1400                                 }
1401                                 curr->get_node()->add_read_from(act);
1402                         }
1403
1404                         /* Include at most one act per-thread that "happens before" curr */
1405                         if (act->happens_before(curr)) {
1406                                 initialized = true;
1407                                 break;
1408                         }
1409                 }
1410         }
1411
1412         if (!initialized) {
1413                 /** @todo Need a more informative way of reporting errors. */
1414                 printf("ERROR: may read from uninitialized atomic\n");
1415         }
1416
1417         if (DBG_ENABLED() || !initialized) {
1418                 printf("Reached read action:\n");
1419                 curr->print();
1420                 printf("Printing may_read_from\n");
1421                 curr->get_node()->print_may_read_from();
1422                 printf("End printing may_read_from\n");
1423         }
1424
1425         ASSERT(initialized);
1426 }
1427
1428 static void print_list(action_list_t *list)
1429 {
1430         action_list_t::iterator it;
1431
1432         printf("---------------------------------------------------------------------\n");
1433         printf("Trace:\n");
1434
1435         for (it = list->begin(); it != list->end(); it++) {
1436                 (*it)->print();
1437         }
1438         printf("---------------------------------------------------------------------\n");
1439 }
1440
1441 void ModelChecker::print_summary()
1442 {
1443         printf("\n");
1444         printf("Number of executions: %d\n", num_executions);
1445         printf("Number of feasible executions: %d\n", num_feasible_executions);
1446         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1447
1448 #if SUPPORT_MOD_ORDER_DUMP
1449         scheduler->print();
1450         char buffername[100];
1451         sprintf(buffername, "exec%u",num_executions);
1452         mo_graph->dumpGraphToFile(buffername);
1453 #endif
1454
1455         if (!isfinalfeasible())
1456                 printf("INFEASIBLE EXECUTION!\n");
1457         print_list(action_trace);
1458         printf("\n");
1459 }
1460
1461 /**
1462  * Add a Thread to the system for the first time. Should only be called once
1463  * per thread.
1464  * @param t The Thread to add
1465  */
1466 void ModelChecker::add_thread(Thread *t)
1467 {
1468         thread_map->put(id_to_int(t->get_id()), t);
1469         scheduler->add_thread(t);
1470 }
1471
1472 void ModelChecker::remove_thread(Thread *t)
1473 {
1474         scheduler->remove_thread(t);
1475 }
1476
1477 /**
1478  * Switch from a user-context to the "master thread" context (a.k.a. system
1479  * context). This switch is made with the intention of exploring a particular
1480  * model-checking action (described by a ModelAction object). Must be called
1481  * from a user-thread context.
1482  * @param act The current action that will be explored. Must not be NULL.
1483  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1484  */
1485 int ModelChecker::switch_to_master(ModelAction *act)
1486 {
1487         DBG();
1488         Thread *old = thread_current();
1489         set_current_action(act);
1490         old->set_state(THREAD_READY);
1491         return Thread::swap(old, &system_context);
1492 }
1493
1494 /**
1495  * Takes the next step in the execution, if possible.
1496  * @return Returns true (success) if a step was taken and false otherwise.
1497  */
1498 bool ModelChecker::take_step() {
1499         if (has_asserted())
1500                 return false;
1501
1502         Thread * curr = thread_current();
1503         if (curr) {
1504                 if (curr->get_state() == THREAD_READY) {
1505                         ASSERT(priv->current_action);
1506
1507                         priv->nextThread = check_current_action(priv->current_action);
1508                         priv->current_action = NULL;
1509                         if (curr->is_blocked() || curr->is_complete())
1510                                 scheduler->remove_thread(curr);
1511                 } else {
1512                         ASSERT(false);
1513                 }
1514         }
1515         Thread * next = scheduler->next_thread(priv->nextThread);
1516
1517         /* Infeasible -> don't take any more steps */
1518         if (!isfeasible())
1519                 return false;
1520
1521         if (next)
1522                 next->set_state(THREAD_RUNNING);
1523         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1524
1525         /* next == NULL -> don't take any more steps */
1526         if (!next)
1527                 return false;
1528
1529         if ( next->get_pending() != NULL ) {
1530                 //restart a pending action
1531                 set_current_action(next->get_pending());
1532                 next->set_pending(NULL);
1533                 next->set_state(THREAD_READY);
1534                 return true;
1535         }
1536
1537         /* Return false only if swap fails with an error */
1538         return (Thread::swap(&system_context, next) == 0);
1539 }
1540
1541 /** Runs the current execution until threre are no more steps to take. */
1542 void ModelChecker::finish_execution() {
1543         DBG();
1544
1545         while (take_step());
1546 }