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