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