model: add special model-checker Thread to ModelChecker
[c11tester.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3
4 #include "model.h"
5 #include "action.h"
6 #include "nodestack.h"
7 #include "schedule.h"
8 #include "snapshot-interface.h"
9 #include "common.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
12 #include "promise.h"
13 #include "datarace.h"
14 #include "mutex.h"
15 #include "threads.h"
16
17 #define INITIAL_THREAD_ID       0
18
19 ModelChecker *model;
20
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23         /* Initialize default scheduler */
24         params(params),
25         scheduler(new Scheduler()),
26         num_executions(0),
27         num_feasible_executions(0),
28         diverge(NULL),
29         earliest_diverge(NULL),
30         action_trace(new action_list_t()),
31         thread_map(new HashTable<int, Thread *, int>()),
32         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33         lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
34         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
35         promises(new std::vector<Promise *>()),
36         futurevalues(new std::vector<struct PendingFutureValue>()),
37         pending_rel_seqs(new std::vector<struct release_seq *>()),
38         thrd_last_action(new std::vector<ModelAction *>(1)),
39         node_stack(new NodeStack()),
40         mo_graph(new CycleGraph()),
41         failed_promise(false),
42         too_many_reads(false),
43         asserted(false),
44         bad_synchronization(false)
45 {
46         /* Allocate this "size" on the snapshotting heap */
47         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
48         /* First thread created will have id INITIAL_THREAD_ID */
49         priv->next_thread_id = INITIAL_THREAD_ID;
50
51         /* Initialize a model-checker thread, for special ModelActions */
52         model_thread = new Thread(get_next_id());
53         thread_map->put(id_to_int(model_thread->get_id()), model_thread);
54 }
55
56 /** @brief Destructor */
57 ModelChecker::~ModelChecker()
58 {
59         for (unsigned int i = 0; i < get_num_threads(); i++)
60                 delete thread_map->get(i);
61         delete thread_map;
62
63         delete obj_thrd_map;
64         delete obj_map;
65         delete lock_waiters_map;
66         delete action_trace;
67
68         for (unsigned int i = 0; i < promises->size(); i++)
69                 delete (*promises)[i];
70         delete promises;
71
72         delete pending_rel_seqs;
73
74         delete thrd_last_action;
75         delete node_stack;
76         delete scheduler;
77         delete mo_graph;
78 }
79
80 /**
81  * Restores user program to initial state and resets all model-checker data
82  * structures.
83  */
84 void ModelChecker::reset_to_initial_state()
85 {
86         DEBUG("+++ Resetting to initial state +++\n");
87         node_stack->reset_execution();
88         failed_promise = false;
89         too_many_reads = false;
90         bad_synchronization = false;
91         reset_asserted();
92         snapshotObject->backTrackBeforeStep(0);
93 }
94
95 /** @return a thread ID for a new Thread */
96 thread_id_t ModelChecker::get_next_id()
97 {
98         return priv->next_thread_id++;
99 }
100
101 /** @return the number of user threads created during this execution */
102 unsigned int ModelChecker::get_num_threads()
103 {
104         return priv->next_thread_id;
105 }
106
107 /** @return The currently executing Thread. */
108 Thread * ModelChecker::get_current_thread()
109 {
110         return scheduler->get_current_thread();
111 }
112
113 /** @return a sequence number for a new ModelAction */
114 modelclock_t ModelChecker::get_next_seq_num()
115 {
116         return ++priv->used_sequence_numbers;
117 }
118
119 /**
120  * @brief Choose the next thread to execute.
121  *
122  * This function chooses the next thread that should execute. It can force the
123  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
124  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
125  * The model-checker may have no preference regarding the next thread (i.e.,
126  * when exploring a new execution ordering), in which case this will return
127  * NULL.
128  * @param curr The current ModelAction. This action might guide the choice of
129  * next thread.
130  * @return The next thread to run. If the model-checker has no preference, NULL.
131  */
132 Thread * ModelChecker::get_next_thread(ModelAction *curr)
133 {
134         thread_id_t tid;
135
136         if (curr!=NULL) {
137                 /* Do not split atomic actions. */
138                 if (curr->is_rmwr())
139                         return thread_current();
140                 /* The THREAD_CREATE action points to the created Thread */
141                 else if (curr->get_type() == THREAD_CREATE)
142                         return (Thread *)curr->get_location();
143         }
144
145         /* Have we completed exploring the preselected path? */
146         if (diverge == NULL)
147                 return NULL;
148
149         /* Else, we are trying to replay an execution */
150         ModelAction *next = node_stack->get_next()->get_action();
151
152         if (next == diverge) {
153                 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
154                         earliest_diverge=diverge;
155
156                 Node *nextnode = next->get_node();
157                 /* Reached divergence point */
158                 if (nextnode->increment_promise()) {
159                         /* The next node will try to satisfy a different set of promises. */
160                         tid = next->get_tid();
161                         node_stack->pop_restofstack(2);
162                 } else if (nextnode->increment_read_from()) {
163                         /* The next node will read from a different value. */
164                         tid = next->get_tid();
165                         node_stack->pop_restofstack(2);
166                 } else if (nextnode->increment_future_value()) {
167                         /* The next node will try to read from a different future value. */
168                         tid = next->get_tid();
169                         node_stack->pop_restofstack(2);
170                 } else if (nextnode->increment_relseq_break()) {
171                         /* The next node will try to resolve a release sequence differently */
172                         tid = next->get_tid();
173                         node_stack->pop_restofstack(2);
174                 } else {
175                         /* Make a different thread execute for next step */
176                         Node *node = nextnode->get_parent();
177                         tid = node->get_next_backtrack();
178                         node_stack->pop_restofstack(1);
179                         if (diverge==earliest_diverge) {
180                                 earliest_diverge=node->get_action();
181                         }
182                 }
183                 DEBUG("*** Divergence point ***\n");
184
185                 diverge = NULL;
186         } else {
187                 tid = next->get_tid();
188         }
189         DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
190         ASSERT(tid != THREAD_ID_T_NONE);
191         return thread_map->get(id_to_int(tid));
192 }
193
194 /**
195  * Queries the model-checker for more executions to explore and, if one
196  * exists, resets the model-checker state to execute a new execution.
197  *
198  * @return If there are more executions to explore, return true. Otherwise,
199  * return false.
200  */
201 bool ModelChecker::next_execution()
202 {
203         DBG();
204
205         num_executions++;
206
207         if (isfinalfeasible()) {
208                 printf("Earliest divergence point since last feasible execution:\n");
209                 if (earliest_diverge)
210                         earliest_diverge->print();
211                 else
212                         printf("(Not set)\n");
213
214                 earliest_diverge = NULL;
215                 num_feasible_executions++;
216         }
217
218         DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
219                         pending_rel_seqs->size());
220
221         if (isfinalfeasible() || DBG_ENABLED())
222                 print_summary();
223
224         if ((diverge = get_next_backtrack()) == NULL)
225                 return false;
226
227         if (DBG_ENABLED()) {
228                 printf("Next execution will diverge at:\n");
229                 diverge->print();
230         }
231
232         reset_to_initial_state();
233         return true;
234 }
235
236 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
237 {
238         switch (act->get_type()) {
239         case ATOMIC_READ:
240         case ATOMIC_WRITE:
241         case ATOMIC_RMW: {
242                 /* linear search: from most recent to oldest */
243                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
244                 action_list_t::reverse_iterator rit;
245                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
246                         ModelAction *prev = *rit;
247                         if (prev->could_synchronize_with(act))
248                                 return prev;
249                 }
250                 break;
251         }
252         case ATOMIC_LOCK:
253         case ATOMIC_TRYLOCK: {
254                 /* linear search: from most recent to oldest */
255                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
256                 action_list_t::reverse_iterator rit;
257                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
258                         ModelAction *prev = *rit;
259                         if (act->is_conflicting_lock(prev))
260                                 return prev;
261                 }
262                 break;
263         }
264         case ATOMIC_UNLOCK: {
265                 /* linear search: from most recent to oldest */
266                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
267                 action_list_t::reverse_iterator rit;
268                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
269                         ModelAction *prev = *rit;
270                         if (!act->same_thread(prev)&&prev->is_failed_trylock())
271                                 return prev;
272                 }
273                 break;
274         }
275         default:
276                 break;
277         }
278         return NULL;
279 }
280
281 /** This method find backtracking points where we should try to
282  * reorder the parameter ModelAction against.
283  *
284  * @param the ModelAction to find backtracking points for.
285  */
286 void ModelChecker::set_backtracking(ModelAction *act)
287 {
288         Thread *t = get_thread(act);
289         ModelAction * prev = get_last_conflict(act);
290         if (prev == NULL)
291                 return;
292
293         Node * node = prev->get_node()->get_parent();
294
295         int low_tid, high_tid;
296         if (node->is_enabled(t)) {
297                 low_tid = id_to_int(act->get_tid());
298                 high_tid = low_tid+1;
299         } else {
300                 low_tid = 0;
301                 high_tid = get_num_threads();
302         }
303
304         for(int i = low_tid; i < high_tid; i++) {
305                 thread_id_t tid = int_to_id(i);
306                 if (!node->is_enabled(tid))
307                         continue;
308
309                 /* Check if this has been explored already */
310                 if (node->has_been_explored(tid))
311                         continue;
312
313                 /* See if fairness allows */
314                 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
315                         bool unfair=false;
316                         for(int t=0;t<node->get_num_threads();t++) {
317                                 thread_id_t tother=int_to_id(t);
318                                 if (node->is_enabled(tother) && node->has_priority(tother)) {
319                                         unfair=true;
320                                         break;
321                                 }
322                         }
323                         if (unfair)
324                                 continue;
325                 }
326
327                 /* Cache the latest backtracking point */
328                 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
329                         priv->next_backtrack = prev;
330
331                 /* If this is a new backtracking point, mark the tree */
332                 if (!node->set_backtrack(tid))
333                         continue;
334                 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
335                                         id_to_int(prev->get_tid()),
336                                         id_to_int(t->get_id()));
337                 if (DBG_ENABLED()) {
338                         prev->print();
339                         act->print();
340                 }
341         }
342 }
343
344 /**
345  * Returns last backtracking point. The model checker will explore a different
346  * path for this point in the next execution.
347  * @return The ModelAction at which the next execution should diverge.
348  */
349 ModelAction * ModelChecker::get_next_backtrack()
350 {
351         ModelAction *next = priv->next_backtrack;
352         priv->next_backtrack = NULL;
353         return next;
354 }
355
356 /**
357  * Processes a read or rmw model action.
358  * @param curr is the read model action to process.
359  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
360  * @return True if processing this read updates the mo_graph.
361  */
362 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
363 {
364         uint64_t value;
365         bool updated = false;
366         while (true) {
367                 const ModelAction *reads_from = curr->get_node()->get_read_from();
368                 if (reads_from != NULL) {
369                         mo_graph->startChanges();
370
371                         value = reads_from->get_value();
372                         bool r_status = false;
373
374                         if (!second_part_of_rmw) {
375                                 check_recency(curr, reads_from);
376                                 r_status = r_modification_order(curr, reads_from);
377                         }
378
379
380                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
381                                 mo_graph->rollbackChanges();
382                                 too_many_reads = false;
383                                 continue;
384                         }
385
386                         curr->read_from(reads_from);
387                         mo_graph->commitChanges();
388                         mo_check_promises(curr->get_tid(), reads_from);
389
390                         updated |= r_status;
391                 } else if (!second_part_of_rmw) {
392                         /* Read from future value */
393                         value = curr->get_node()->get_future_value();
394                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
395                         curr->read_from(NULL);
396                         Promise *valuepromise = new Promise(curr, value, expiration);
397                         promises->push_back(valuepromise);
398                 }
399                 get_thread(curr)->set_return_value(value);
400                 return updated;
401         }
402 }
403
404 /**
405  * Processes a lock, trylock, or unlock model action.  @param curr is
406  * the read model action to process.
407  *
408  * The try lock operation checks whether the lock is taken.  If not,
409  * it falls to the normal lock operation case.  If so, it returns
410  * fail.
411  *
412  * The lock operation has already been checked that it is enabled, so
413  * it just grabs the lock and synchronizes with the previous unlock.
414  *
415  * The unlock operation has to re-enable all of the threads that are
416  * waiting on the lock.
417  *
418  * @return True if synchronization was updated; false otherwise
419  */
420 bool ModelChecker::process_mutex(ModelAction *curr) {
421         std::mutex *mutex = (std::mutex *)curr->get_location();
422         struct std::mutex_state *state = mutex->get_state();
423         switch (curr->get_type()) {
424         case ATOMIC_TRYLOCK: {
425                 bool success = !state->islocked;
426                 curr->set_try_lock(success);
427                 if (!success) {
428                         get_thread(curr)->set_return_value(0);
429                         break;
430                 }
431                 get_thread(curr)->set_return_value(1);
432         }
433                 //otherwise fall into the lock case
434         case ATOMIC_LOCK: {
435                 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
436                         printf("Lock access before initialization\n");
437                         set_assert();
438                 }
439                 state->islocked = true;
440                 ModelAction *unlock = get_last_unlock(curr);
441                 //synchronize with the previous unlock statement
442                 if (unlock != NULL) {
443                         curr->synchronize_with(unlock);
444                         return true;
445                 }
446                 break;
447         }
448         case ATOMIC_UNLOCK: {
449                 //unlock the lock
450                 state->islocked = false;
451                 //wake up the other threads
452                 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
453                 //activate all the waiting threads
454                 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
455                         scheduler->wake(get_thread(*rit));
456                 }
457                 waiters->clear();
458                 break;
459         }
460         default:
461                 ASSERT(0);
462         }
463         return false;
464 }
465
466 /**
467  * Process a write ModelAction
468  * @param curr The ModelAction to process
469  * @return True if the mo_graph was updated or promises were resolved
470  */
471 bool ModelChecker::process_write(ModelAction *curr)
472 {
473         bool updated_mod_order = w_modification_order(curr);
474         bool updated_promises = resolve_promises(curr);
475
476         if (promises->size() == 0) {
477                 for (unsigned int i = 0; i < futurevalues->size(); i++) {
478                         struct PendingFutureValue pfv = (*futurevalues)[i];
479                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
480                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
481                                 priv->next_backtrack = pfv.act;
482                 }
483                 futurevalues->resize(0);
484         }
485
486         mo_graph->commitChanges();
487         mo_check_promises(curr->get_tid(), curr);
488
489         get_thread(curr)->set_return_value(VALUE_NONE);
490         return updated_mod_order || updated_promises;
491 }
492
493 /**
494  * @brief Process the current action for thread-related activity
495  *
496  * Performs current-action processing for a THREAD_* ModelAction. Proccesses
497  * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
498  * synchronization, etc.  This function is a no-op for non-THREAD actions
499  * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
500  *
501  * @param curr The current action
502  * @return True if synchronization was updated or a thread completed
503  */
504 bool ModelChecker::process_thread_action(ModelAction *curr)
505 {
506         bool updated = false;
507
508         switch (curr->get_type()) {
509         case THREAD_CREATE: {
510                 Thread *th = (Thread *)curr->get_location();
511                 th->set_creation(curr);
512                 break;
513         }
514         case THREAD_JOIN: {
515                 Thread *waiting, *blocking;
516                 waiting = get_thread(curr);
517                 blocking = (Thread *)curr->get_location();
518                 if (!blocking->is_complete()) {
519                         blocking->push_wait_list(curr);
520                         scheduler->sleep(waiting);
521                 } else {
522                         do_complete_join(curr);
523                         updated = true; /* trigger rel-seq checks */
524                 }
525                 break;
526         }
527         case THREAD_FINISH: {
528                 Thread *th = get_thread(curr);
529                 while (!th->wait_list_empty()) {
530                         ModelAction *act = th->pop_wait_list();
531                         Thread *wake = get_thread(act);
532                         scheduler->wake(wake);
533                         do_complete_join(act);
534                         updated = true; /* trigger rel-seq checks */
535                 }
536                 th->complete();
537                 updated = true; /* trigger rel-seq checks */
538                 break;
539         }
540         case THREAD_START: {
541                 check_promises(curr->get_tid(), NULL, curr->get_cv());
542                 break;
543         }
544         default:
545                 break;
546         }
547
548         return updated;
549 }
550
551 /**
552  * @brief Process the current action for release sequence fixup activity
553  *
554  * Performs model-checker release sequence fixups for the current action,
555  * forcing a single pending release sequence to break (with a given, potential
556  * "loose" write) or to complete (i.e., synchronize). If a pending release
557  * sequence forms a complete release sequence, then we must perform the fixup
558  * synchronization, mo_graph additions, etc.
559  *
560  * @param curr The current action; must be a release sequence fixup action
561  * @param work_queue The work queue to which to add work items as they are
562  * generated
563  */
564 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
565 {
566         const ModelAction *write = curr->get_node()->get_relseq_break();
567         struct release_seq *sequence = pending_rel_seqs->back();
568         pending_rel_seqs->pop_back();
569         ASSERT(sequence);
570         ModelAction *acquire = sequence->acquire;
571         const ModelAction *rf = sequence->rf;
572         const ModelAction *release = sequence->release;
573         ASSERT(acquire);
574         ASSERT(release);
575         ASSERT(rf);
576         ASSERT(release->same_thread(rf));
577
578         if (write == NULL) {
579                 /* Must synchronize */
580                 if (!acquire->synchronize_with(release)) {
581                         set_bad_synchronization();
582                         return;
583                 }
584                 /* Re-check all pending release sequences */
585                 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
586                 /* Re-check act for mo_graph edges */
587                 work_queue->push_back(MOEdgeWorkEntry(acquire));
588
589                 /* propagate synchronization to later actions */
590                 action_list_t::reverse_iterator rit = action_trace->rbegin();
591                 for (; (*rit) != acquire; rit++) {
592                         ModelAction *propagate = *rit;
593                         if (acquire->happens_before(propagate)) {
594                                 propagate->synchronize_with(acquire);
595                                 /* Re-check 'propagate' for mo_graph edges */
596                                 work_queue->push_back(MOEdgeWorkEntry(propagate));
597                         }
598                 }
599         } else {
600                 /* Break release sequence with new edges:
601                  *   release --mo--> write --mo--> rf */
602                 mo_graph->addEdge(release, write);
603                 mo_graph->addEdge(write, rf);
604         }
605 }
606
607 /**
608  * Initialize the current action by performing one or more of the following
609  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
610  * in the NodeStack, manipulating backtracking sets, allocating and
611  * initializing clock vectors, and computing the promises to fulfill.
612  *
613  * @param curr The current action, as passed from the user context; may be
614  * freed/invalidated after the execution of this function
615  * @return The current action, as processed by the ModelChecker. Is only the
616  * same as the parameter @a curr if this is a newly-explored action.
617  */
618 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
619 {
620         ModelAction *newcurr;
621
622         if (curr->is_rmwc() || curr->is_rmw()) {
623                 newcurr = process_rmw(curr);
624                 delete curr;
625
626                 if (newcurr->is_rmw())
627                         compute_promises(newcurr);
628                 return newcurr;
629         }
630
631         curr->set_seq_number(get_next_seq_num());
632
633         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
634         if (newcurr) {
635                 /* First restore type and order in case of RMW operation */
636                 if (curr->is_rmwr())
637                         newcurr->copy_typeandorder(curr);
638
639                 ASSERT(curr->get_location() == newcurr->get_location());
640                 newcurr->copy_from_new(curr);
641
642                 /* Discard duplicate ModelAction; use action from NodeStack */
643                 delete curr;
644
645                 /* Always compute new clock vector */
646                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
647         } else {
648                 newcurr = curr;
649
650                 /* Always compute new clock vector */
651                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
652                 /*
653                  * Perform one-time actions when pushing new ModelAction onto
654                  * NodeStack
655                  */
656                 if (newcurr->is_write())
657                         compute_promises(newcurr);
658                 else if (newcurr->is_relseq_fixup())
659                         compute_relseq_breakwrites(newcurr);
660         }
661         return newcurr;
662 }
663
664 /**
665  * This method checks whether a model action is enabled at the given point.
666  * At this point, it checks whether a lock operation would be successful at this point.
667  * If not, it puts the thread in a waiter list.
668  * @param curr is the ModelAction to check whether it is enabled.
669  * @return a bool that indicates whether the action is enabled.
670  */
671 bool ModelChecker::check_action_enabled(ModelAction *curr) {
672         if (curr->is_lock()) {
673                 std::mutex * lock = (std::mutex *)curr->get_location();
674                 struct std::mutex_state * state = lock->get_state();
675                 if (state->islocked) {
676                         //Stick the action in the appropriate waiting queue
677                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
678                         return false;
679                 }
680         }
681
682         return true;
683 }
684
685 /**
686  * This is the heart of the model checker routine. It performs model-checking
687  * actions corresponding to a given "current action." Among other processes, it
688  * calculates reads-from relationships, updates synchronization clock vectors,
689  * forms a memory_order constraints graph, and handles replay/backtrack
690  * execution when running permutations of previously-observed executions.
691  *
692  * @param curr The current action to process
693  * @return The next Thread that must be executed. May be NULL if ModelChecker
694  * makes no choice (e.g., according to replay execution, combining RMW actions,
695  * etc.)
696  */
697 Thread * ModelChecker::check_current_action(ModelAction *curr)
698 {
699         ASSERT(curr);
700
701         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
702
703         if (!check_action_enabled(curr)) {
704                 /* Make the execution look like we chose to run this action
705                  * much later, when a lock is actually available to release */
706                 get_current_thread()->set_pending(curr);
707                 scheduler->sleep(get_current_thread());
708                 return get_next_thread(NULL);
709         }
710
711         ModelAction *newcurr = initialize_curr_action(curr);
712
713         /* Add the action to lists before any other model-checking tasks */
714         if (!second_part_of_rmw)
715                 add_action_to_lists(newcurr);
716
717         /* Build may_read_from set for newly-created actions */
718         if (curr == newcurr && curr->is_read())
719                 build_reads_from_past(curr);
720         curr = newcurr;
721
722         /* Initialize work_queue with the "current action" work */
723         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
724
725         while (!work_queue.empty()) {
726                 WorkQueueEntry work = work_queue.front();
727                 work_queue.pop_front();
728
729                 switch (work.type) {
730                 case WORK_CHECK_CURR_ACTION: {
731                         ModelAction *act = work.action;
732                         bool update = false; /* update this location's release seq's */
733                         bool update_all = false; /* update all release seq's */
734
735                         if (process_thread_action(curr))
736                                 update_all = true;
737
738                         if (act->is_read() && process_read(act, second_part_of_rmw))
739                                 update = true;
740
741                         if (act->is_write() && process_write(act))
742                                 update = true;
743
744                         if (act->is_mutex_op() && process_mutex(act))
745                                 update_all = true;
746
747                         if (act->is_relseq_fixup())
748                                 process_relseq_fixup(curr, &work_queue);
749
750                         if (update_all)
751                                 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
752                         else if (update)
753                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
754                         break;
755                 }
756                 case WORK_CHECK_RELEASE_SEQ:
757                         resolve_release_sequences(work.location, &work_queue);
758                         break;
759                 case WORK_CHECK_MO_EDGES: {
760                         /** @todo Complete verification of work_queue */
761                         ModelAction *act = work.action;
762                         bool updated = false;
763
764                         if (act->is_read()) {
765                                 const ModelAction *rf = act->get_reads_from();
766                                 if (rf != NULL && r_modification_order(act, rf))
767                                         updated = true;
768                         }
769                         if (act->is_write()) {
770                                 if (w_modification_order(act))
771                                         updated = true;
772                         }
773                         mo_graph->commitChanges();
774
775                         if (updated)
776                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
777                         break;
778                 }
779                 default:
780                         ASSERT(false);
781                         break;
782                 }
783         }
784
785         check_curr_backtracking(curr);
786
787         set_backtracking(curr);
788
789         return get_next_thread(curr);
790 }
791
792 /**
793  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
794  * operation from the Thread it is joining with. Must be called after the
795  * completion of the Thread in question.
796  * @param join The THREAD_JOIN action
797  */
798 void ModelChecker::do_complete_join(ModelAction *join)
799 {
800         Thread *blocking = (Thread *)join->get_location();
801         ModelAction *act = get_last_action(blocking->get_id());
802         join->synchronize_with(act);
803 }
804
805 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
806         Node *currnode = curr->get_node();
807         Node *parnode = currnode->get_parent();
808
809         if ((!parnode->backtrack_empty() ||
810                          !currnode->read_from_empty() ||
811                          !currnode->future_value_empty() ||
812                          !currnode->promise_empty() ||
813                          !currnode->relseq_break_empty())
814                         && (!priv->next_backtrack ||
815                                         *curr > *priv->next_backtrack)) {
816                 priv->next_backtrack = curr;
817         }
818 }
819
820 bool ModelChecker::promises_expired() {
821         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
822                 Promise *promise = (*promises)[promise_index];
823                 if (promise->get_expiration()<priv->used_sequence_numbers) {
824                         return true;
825                 }
826         }
827         return false;
828 }
829
830 /** @return whether the current partial trace must be a prefix of a
831  * feasible trace. */
832 bool ModelChecker::isfeasibleprefix() {
833         return promises->size() == 0 && pending_rel_seqs->size() == 0;
834 }
835
836 /** @return whether the current partial trace is feasible. */
837 bool ModelChecker::isfeasible() {
838         if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
839                 DEBUG("Infeasible: RMW violation\n");
840
841         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
842 }
843
844 /** @return whether the current partial trace is feasible other than
845  * multiple RMW reading from the same store. */
846 bool ModelChecker::isfeasibleotherthanRMW() {
847         if (DBG_ENABLED()) {
848                 if (mo_graph->checkForCycles())
849                         DEBUG("Infeasible: modification order cycles\n");
850                 if (failed_promise)
851                         DEBUG("Infeasible: failed promise\n");
852                 if (too_many_reads)
853                         DEBUG("Infeasible: too many reads\n");
854                 if (bad_synchronization)
855                         DEBUG("Infeasible: bad synchronization ordering\n");
856                 if (promises_expired())
857                         DEBUG("Infeasible: promises expired\n");
858         }
859         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
860 }
861
862 /** Returns whether the current completed trace is feasible. */
863 bool ModelChecker::isfinalfeasible() {
864         if (DBG_ENABLED() && promises->size() != 0)
865                 DEBUG("Infeasible: unrevolved promises\n");
866
867         return isfeasible() && promises->size() == 0;
868 }
869
870 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
871 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
872         ModelAction *lastread = get_last_action(act->get_tid());
873         lastread->process_rmw(act);
874         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
875                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
876                 mo_graph->commitChanges();
877         }
878         return lastread;
879 }
880
881 /**
882  * Checks whether a thread has read from the same write for too many times
883  * without seeing the effects of a later write.
884  *
885  * Basic idea:
886  * 1) there must a different write that we could read from that would satisfy the modification order,
887  * 2) we must have read from the same value in excess of maxreads times, and
888  * 3) that other write must have been in the reads_from set for maxreads times.
889  *
890  * If so, we decide that the execution is no longer feasible.
891  */
892 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
893         if (params.maxreads != 0) {
894
895                 if (curr->get_node()->get_read_from_size() <= 1)
896                         return;
897                 //Must make sure that execution is currently feasible...  We could
898                 //accidentally clear by rolling back
899                 if (!isfeasible())
900                         return;
901                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
902                 int tid = id_to_int(curr->get_tid());
903
904                 /* Skip checks */
905                 if ((int)thrd_lists->size() <= tid)
906                         return;
907                 action_list_t *list = &(*thrd_lists)[tid];
908
909                 action_list_t::reverse_iterator rit = list->rbegin();
910                 /* Skip past curr */
911                 for (; (*rit) != curr; rit++)
912                         ;
913                 /* go past curr now */
914                 rit++;
915
916                 action_list_t::reverse_iterator ritcopy = rit;
917                 //See if we have enough reads from the same value
918                 int count = 0;
919                 for (; count < params.maxreads; rit++,count++) {
920                         if (rit==list->rend())
921                                 return;
922                         ModelAction *act = *rit;
923                         if (!act->is_read())
924                                 return;
925                         
926                         if (act->get_reads_from() != rf)
927                                 return;
928                         if (act->get_node()->get_read_from_size() <= 1)
929                                 return;
930                 }
931                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
932                         //Get write
933                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
934
935                         //Need a different write
936                         if (write==rf)
937                                 continue;
938
939                         /* Test to see whether this is a feasible write to read from*/
940                         mo_graph->startChanges();
941                         r_modification_order(curr, write);
942                         bool feasiblereadfrom = isfeasible();
943                         mo_graph->rollbackChanges();
944
945                         if (!feasiblereadfrom)
946                                 continue;
947                         rit = ritcopy;
948
949                         bool feasiblewrite = true;
950                         //new we need to see if this write works for everyone
951
952                         for (int loop = count; loop>0; loop--,rit++) {
953                                 ModelAction *act=*rit;
954                                 bool foundvalue = false;
955                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
956                                         if (act->get_node()->get_read_from_at(i)==write) {
957                                                 foundvalue = true;
958                                                 break;
959                                         }
960                                 }
961                                 if (!foundvalue) {
962                                         feasiblewrite = false;
963                                         break;
964                                 }
965                         }
966                         if (feasiblewrite) {
967                                 too_many_reads = true;
968                                 return;
969                         }
970                 }
971         }
972 }
973
974 /**
975  * Updates the mo_graph with the constraints imposed from the current
976  * read.
977  *
978  * Basic idea is the following: Go through each other thread and find
979  * the lastest action that happened before our read.  Two cases:
980  *
981  * (1) The action is a write => that write must either occur before
982  * the write we read from or be the write we read from.
983  *
984  * (2) The action is a read => the write that that action read from
985  * must occur before the write we read from or be the same write.
986  *
987  * @param curr The current action. Must be a read.
988  * @param rf The action that curr reads from. Must be a write.
989  * @return True if modification order edges were added; false otherwise
990  */
991 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
992 {
993         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
994         unsigned int i;
995         bool added = false;
996         ASSERT(curr->is_read());
997
998         /* Iterate over all threads */
999         for (i = 0; i < thrd_lists->size(); i++) {
1000                 /* Iterate over actions in thread, starting from most recent */
1001                 action_list_t *list = &(*thrd_lists)[i];
1002                 action_list_t::reverse_iterator rit;
1003                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1004                         ModelAction *act = *rit;
1005
1006                         /*
1007                          * Include at most one act per-thread that "happens
1008                          * before" curr. Don't consider reflexively.
1009                          */
1010                         if (act->happens_before(curr) && act != curr) {
1011                                 if (act->is_write()) {
1012                                         if (rf != act) {
1013                                                 mo_graph->addEdge(act, rf);
1014                                                 added = true;
1015                                         }
1016                                 } else {
1017                                         const ModelAction *prevreadfrom = act->get_reads_from();
1018                                         //if the previous read is unresolved, keep going...
1019                                         if (prevreadfrom == NULL)
1020                                                 continue;
1021
1022                                         if (rf != prevreadfrom) {
1023                                                 mo_graph->addEdge(prevreadfrom, rf);
1024                                                 added = true;
1025                                         }
1026                                 }
1027                                 break;
1028                         }
1029                 }
1030         }
1031
1032         return added;
1033 }
1034
1035 /** This method fixes up the modification order when we resolve a
1036  *  promises.  The basic problem is that actions that occur after the
1037  *  read curr could not property add items to the modification order
1038  *  for our read.
1039  *
1040  *  So for each thread, we find the earliest item that happens after
1041  *  the read curr.  This is the item we have to fix up with additional
1042  *  constraints.  If that action is write, we add a MO edge between
1043  *  the Action rf and that action.  If the action is a read, we add a
1044  *  MO edge between the Action rf, and whatever the read accessed.
1045  *
1046  * @param curr is the read ModelAction that we are fixing up MO edges for.
1047  * @param rf is the write ModelAction that curr reads from.
1048  *
1049  */
1050 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1051 {
1052         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1053         unsigned int i;
1054         ASSERT(curr->is_read());
1055
1056         /* Iterate over all threads */
1057         for (i = 0; i < thrd_lists->size(); i++) {
1058                 /* Iterate over actions in thread, starting from most recent */
1059                 action_list_t *list = &(*thrd_lists)[i];
1060                 action_list_t::reverse_iterator rit;
1061                 ModelAction *lastact = NULL;
1062
1063                 /* Find last action that happens after curr that is either not curr or a rmw */
1064                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1065                         ModelAction *act = *rit;
1066                         if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1067                                 lastact = act;
1068                         } else
1069                                 break;
1070                 }
1071
1072                         /* Include at most one act per-thread that "happens before" curr */
1073                 if (lastact != NULL) {
1074                         if (lastact==curr) {
1075                                 //Case 1: The resolved read is a RMW, and we need to make sure
1076                                 //that the write portion of the RMW mod order after rf
1077
1078                                 mo_graph->addEdge(rf, lastact);
1079                         } else if (lastact->is_read()) {
1080                                 //Case 2: The resolved read is a normal read and the next
1081                                 //operation is a read, and we need to make sure the value read
1082                                 //is mod ordered after rf
1083
1084                                 const ModelAction *postreadfrom = lastact->get_reads_from();
1085                                 if (postreadfrom != NULL&&rf != postreadfrom)
1086                                         mo_graph->addEdge(rf, postreadfrom);
1087                         } else {
1088                                 //Case 3: The resolved read is a normal read and the next
1089                                 //operation is a write, and we need to make sure that the
1090                                 //write is mod ordered after rf
1091                                 if (lastact!=rf)
1092                                         mo_graph->addEdge(rf, lastact);
1093                         }
1094                         break;
1095                 }
1096         }
1097 }
1098
1099 /**
1100  * Updates the mo_graph with the constraints imposed from the current write.
1101  *
1102  * Basic idea is the following: Go through each other thread and find
1103  * the lastest action that happened before our write.  Two cases:
1104  *
1105  * (1) The action is a write => that write must occur before
1106  * the current write
1107  *
1108  * (2) The action is a read => the write that that action read from
1109  * must occur before the current write.
1110  *
1111  * This method also handles two other issues:
1112  *
1113  * (I) Sequential Consistency: Making sure that if the current write is
1114  * seq_cst, that it occurs after the previous seq_cst write.
1115  *
1116  * (II) Sending the write back to non-synchronizing reads.
1117  *
1118  * @param curr The current action. Must be a write.
1119  * @return True if modification order edges were added; false otherwise
1120  */
1121 bool ModelChecker::w_modification_order(ModelAction *curr)
1122 {
1123         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1124         unsigned int i;
1125         bool added = false;
1126         ASSERT(curr->is_write());
1127
1128         if (curr->is_seqcst()) {
1129                 /* We have to at least see the last sequentially consistent write,
1130                          so we are initialized. */
1131                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1132                 if (last_seq_cst != NULL) {
1133                         mo_graph->addEdge(last_seq_cst, curr);
1134                         added = true;
1135                 }
1136         }
1137
1138         /* Iterate over all threads */
1139         for (i = 0; i < thrd_lists->size(); i++) {
1140                 /* Iterate over actions in thread, starting from most recent */
1141                 action_list_t *list = &(*thrd_lists)[i];
1142                 action_list_t::reverse_iterator rit;
1143                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1144                         ModelAction *act = *rit;
1145                         if (act == curr) {
1146                                 /*
1147                                  * 1) If RMW and it actually read from something, then we
1148                                  * already have all relevant edges, so just skip to next
1149                                  * thread.
1150                                  * 
1151                                  * 2) If RMW and it didn't read from anything, we should
1152                                  * whatever edge we can get to speed up convergence.
1153                                  *
1154                                  * 3) If normal write, we need to look at earlier actions, so
1155                                  * continue processing list.
1156                                  */
1157                                 if (curr->is_rmw()) {
1158                                         if (curr->get_reads_from()!=NULL)
1159                                                 break;
1160                                         else 
1161                                                 continue;
1162                                 } else
1163                                         continue;
1164                         }
1165
1166                         /*
1167                          * Include at most one act per-thread that "happens
1168                          * before" curr
1169                          */
1170                         if (act->happens_before(curr)) {
1171                                 /*
1172                                  * Note: if act is RMW, just add edge:
1173                                  *   act --mo--> curr
1174                                  * The following edge should be handled elsewhere:
1175                                  *   readfrom(act) --mo--> act
1176                                  */
1177                                 if (act->is_write())
1178                                         mo_graph->addEdge(act, curr);
1179                                 else if (act->is_read()) { 
1180                                         //if previous read accessed a null, just keep going
1181                                         if (act->get_reads_from() == NULL)
1182                                                 continue;
1183                                         mo_graph->addEdge(act->get_reads_from(), curr);
1184                                 }
1185                                 added = true;
1186                                 break;
1187                         } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1188                                                      !act->same_thread(curr)) {
1189                                 /* We have an action that:
1190                                    (1) did not happen before us
1191                                    (2) is a read and we are a write
1192                                    (3) cannot synchronize with us
1193                                    (4) is in a different thread
1194                                    =>
1195                                    that read could potentially read from our write.
1196                                  */
1197                                 if (thin_air_constraint_may_allow(curr, act)) {
1198                                         if (isfeasible() ||
1199                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1200                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1201                                                 futurevalues->push_back(pfv);
1202                                         }
1203                                 }
1204                         }
1205                 }
1206         }
1207
1208         return added;
1209 }
1210
1211 /** Arbitrary reads from the future are not allowed.  Section 29.3
1212  * part 9 places some constraints.  This method checks one result of constraint
1213  * constraint.  Others require compiler support. */
1214 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1215         if (!writer->is_rmw())
1216                 return true;
1217
1218         if (!reader->is_rmw())
1219                 return true;
1220
1221         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1222                 if (search == reader)
1223                         return false;
1224                 if (search->get_tid() == reader->get_tid() &&
1225                                 search->happens_before(reader))
1226                         break;
1227         }
1228
1229         return true;
1230 }
1231
1232 /**
1233  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1234  * The ModelAction under consideration is expected to be taking part in
1235  * release/acquire synchronization as an object of the "reads from" relation.
1236  * Note that this can only provide release sequence support for RMW chains
1237  * which do not read from the future, as those actions cannot be traced until
1238  * their "promise" is fulfilled. Similarly, we may not even establish the
1239  * presence of a release sequence with certainty, as some modification order
1240  * constraints may be decided further in the future. Thus, this function
1241  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1242  * and a boolean representing certainty.
1243  *
1244  * @todo Finish lazy updating, when promises are fulfilled in the future
1245  * @param rf The action that might be part of a release sequence. Must be a
1246  * write.
1247  * @param release_heads A pass-by-reference style return parameter. After
1248  * execution of this function, release_heads will contain the heads of all the
1249  * relevant release sequences, if any exists with certainty
1250  * @param pending A pass-by-reference style return parameter which is only used
1251  * when returning false (i.e., uncertain). Returns most information regarding
1252  * an uncertain release sequence, including any write operations that might
1253  * break the sequence.
1254  * @return true, if the ModelChecker is certain that release_heads is complete;
1255  * false otherwise
1256  */
1257 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1258                 rel_heads_list_t *release_heads,
1259                 struct release_seq *pending) const
1260 {
1261         /* Only check for release sequences if there are no cycles */
1262         if (mo_graph->checkForCycles())
1263                 return false;
1264
1265         while (rf) {
1266                 ASSERT(rf->is_write());
1267
1268                 if (rf->is_release())
1269                         release_heads->push_back(rf);
1270                 if (!rf->is_rmw())
1271                         break; /* End of RMW chain */
1272
1273                 /** @todo Need to be smarter here...  In the linux lock
1274                  * example, this will run to the beginning of the program for
1275                  * every acquire. */
1276                 /** @todo The way to be smarter here is to keep going until 1
1277                  * thread has a release preceded by an acquire and you've seen
1278                  *       both. */
1279
1280                 /* acq_rel RMW is a sufficient stopping condition */
1281                 if (rf->is_acquire() && rf->is_release())
1282                         return true; /* complete */
1283
1284                 rf = rf->get_reads_from();
1285         };
1286         if (!rf) {
1287                 /* read from future: need to settle this later */
1288                 pending->rf = NULL;
1289                 return false; /* incomplete */
1290         }
1291
1292         if (rf->is_release())
1293                 return true; /* complete */
1294
1295         /* else relaxed write; check modification order for contiguous subsequence
1296          * -> rf must be same thread as release */
1297         int tid = id_to_int(rf->get_tid());
1298         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1299         action_list_t *list = &(*thrd_lists)[tid];
1300         action_list_t::const_reverse_iterator rit;
1301
1302         /* Find rf in the thread list */
1303         rit = std::find(list->rbegin(), list->rend(), rf);
1304         ASSERT(rit != list->rend());
1305
1306         /* Find the last write/release */
1307         for (; rit != list->rend(); rit++)
1308                 if ((*rit)->is_release())
1309                         break;
1310         if (rit == list->rend()) {
1311                 /* No write-release in this thread */
1312                 return true; /* complete */
1313         }
1314         ModelAction *release = *rit;
1315
1316         ASSERT(rf->same_thread(release));
1317
1318         pending->writes.clear();
1319
1320         bool certain = true;
1321         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1322                 if (id_to_int(rf->get_tid()) == (int)i)
1323                         continue;
1324                 list = &(*thrd_lists)[i];
1325
1326                 /* Can we ensure no future writes from this thread may break
1327                  * the release seq? */
1328                 bool future_ordered = false;
1329
1330                 ModelAction *last = get_last_action(int_to_id(i));
1331                 Thread *th = get_thread(int_to_id(i));
1332                 if ((last && rf->happens_before(last)) ||
1333                                 !scheduler->is_enabled(th) ||
1334                                 th->is_complete())
1335                         future_ordered = true;
1336
1337                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1338                         const ModelAction *act = *rit;
1339                         /* Reach synchronization -> this thread is complete */
1340                         if (act->happens_before(release))
1341                                 break;
1342                         if (rf->happens_before(act)) {
1343                                 future_ordered = true;
1344                                 continue;
1345                         }
1346
1347                         /* Only writes can break release sequences */
1348                         if (!act->is_write())
1349                                 continue;
1350
1351                         /* Check modification order */
1352                         if (mo_graph->checkReachable(rf, act)) {
1353                                 /* rf --mo--> act */
1354                                 future_ordered = true;
1355                                 continue;
1356                         }
1357                         if (mo_graph->checkReachable(act, release))
1358                                 /* act --mo--> release */
1359                                 break;
1360                         if (mo_graph->checkReachable(release, act) &&
1361                                       mo_graph->checkReachable(act, rf)) {
1362                                 /* release --mo-> act --mo--> rf */
1363                                 return true; /* complete */
1364                         }
1365                         /* act may break release sequence */
1366                         pending->writes.push_back(act);
1367                         certain = false;
1368                 }
1369                 if (!future_ordered)
1370                         certain = false; /* This thread is uncertain */
1371         }
1372
1373         if (certain) {
1374                 release_heads->push_back(release);
1375                 pending->writes.clear();
1376         } else {
1377                 pending->release = release;
1378                 pending->rf = rf;
1379         }
1380         return certain;
1381 }
1382
1383 /**
1384  * A public interface for getting the release sequence head(s) with which a
1385  * given ModelAction must synchronize. This function only returns a non-empty
1386  * result when it can locate a release sequence head with certainty. Otherwise,
1387  * it may mark the internal state of the ModelChecker so that it will handle
1388  * the release sequence at a later time, causing @a act to update its
1389  * synchronization at some later point in execution.
1390  * @param act The 'acquire' action that may read from a release sequence
1391  * @param release_heads A pass-by-reference return parameter. Will be filled
1392  * with the head(s) of the release sequence(s), if they exists with certainty.
1393  * @see ModelChecker::release_seq_heads
1394  */
1395 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1396 {
1397         const ModelAction *rf = act->get_reads_from();
1398         struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1399         sequence->acquire = act;
1400
1401         if (!release_seq_heads(rf, release_heads, sequence)) {
1402                 /* add act to 'lazy checking' list */
1403                 pending_rel_seqs->push_back(sequence);
1404         } else {
1405                 snapshot_free(sequence);
1406         }
1407 }
1408
1409 /**
1410  * Attempt to resolve all stashed operations that might synchronize with a
1411  * release sequence for a given location. This implements the "lazy" portion of
1412  * determining whether or not a release sequence was contiguous, since not all
1413  * modification order information is present at the time an action occurs.
1414  *
1415  * @param location The location/object that should be checked for release
1416  * sequence resolutions. A NULL value means to check all locations.
1417  * @param work_queue The work queue to which to add work items as they are
1418  * generated
1419  * @return True if any updates occurred (new synchronization, new mo_graph
1420  * edges)
1421  */
1422 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1423 {
1424         bool updated = false;
1425         std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1426         while (it != pending_rel_seqs->end()) {
1427                 struct release_seq *pending = *it;
1428                 ModelAction *act = pending->acquire;
1429
1430                 /* Only resolve sequences on the given location, if provided */
1431                 if (location && act->get_location() != location) {
1432                         it++;
1433                         continue;
1434                 }
1435
1436                 const ModelAction *rf = act->get_reads_from();
1437                 rel_heads_list_t release_heads;
1438                 bool complete;
1439                 complete = release_seq_heads(rf, &release_heads, pending);
1440                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1441                         if (!act->has_synchronized_with(release_heads[i])) {
1442                                 if (act->synchronize_with(release_heads[i]))
1443                                         updated = true;
1444                                 else
1445                                         set_bad_synchronization();
1446                         }
1447                 }
1448
1449                 if (updated) {
1450                         /* Re-check all pending release sequences */
1451                         work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1452                         /* Re-check act for mo_graph edges */
1453                         work_queue->push_back(MOEdgeWorkEntry(act));
1454
1455                         /* propagate synchronization to later actions */
1456                         action_list_t::reverse_iterator rit = action_trace->rbegin();
1457                         for (; (*rit) != act; rit++) {
1458                                 ModelAction *propagate = *rit;
1459                                 if (act->happens_before(propagate)) {
1460                                         propagate->synchronize_with(act);
1461                                         /* Re-check 'propagate' for mo_graph edges */
1462                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1463                                 }
1464                         }
1465                 }
1466                 if (complete) {
1467                         it = pending_rel_seqs->erase(it);
1468                         snapshot_free(pending);
1469                 } else {
1470                         it++;
1471                 }
1472         }
1473
1474         // If we resolved promises or data races, see if we have realized a data race.
1475         if (checkDataRaces()) {
1476                 set_assert();
1477         }
1478
1479         return updated;
1480 }
1481
1482 /**
1483  * Performs various bookkeeping operations for the current ModelAction. For
1484  * instance, adds action to the per-object, per-thread action vector and to the
1485  * action trace list of all thread actions.
1486  *
1487  * @param act is the ModelAction to add.
1488  */
1489 void ModelChecker::add_action_to_lists(ModelAction *act)
1490 {
1491         int tid = id_to_int(act->get_tid());
1492         action_trace->push_back(act);
1493
1494         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1495
1496         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1497         if (tid >= (int)vec->size())
1498                 vec->resize(priv->next_thread_id);
1499         (*vec)[tid].push_back(act);
1500
1501         if ((int)thrd_last_action->size() <= tid)
1502                 thrd_last_action->resize(get_num_threads());
1503         (*thrd_last_action)[tid] = act;
1504 }
1505
1506 /**
1507  * @brief Get the last action performed by a particular Thread
1508  * @param tid The thread ID of the Thread in question
1509  * @return The last action in the thread
1510  */
1511 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1512 {
1513         int threadid = id_to_int(tid);
1514         if (threadid < (int)thrd_last_action->size())
1515                 return (*thrd_last_action)[id_to_int(tid)];
1516         else
1517                 return NULL;
1518 }
1519
1520 /**
1521  * Gets the last memory_order_seq_cst write (in the total global sequence)
1522  * performed on a particular object (i.e., memory location), not including the
1523  * current action.
1524  * @param curr The current ModelAction; also denotes the object location to
1525  * check
1526  * @return The last seq_cst write
1527  */
1528 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1529 {
1530         void *location = curr->get_location();
1531         action_list_t *list = obj_map->get_safe_ptr(location);
1532         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1533         action_list_t::reverse_iterator rit;
1534         for (rit = list->rbegin(); rit != list->rend(); rit++)
1535                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1536                         return *rit;
1537         return NULL;
1538 }
1539
1540 /**
1541  * Gets the last unlock operation performed on a particular mutex (i.e., memory
1542  * location). This function identifies the mutex according to the current
1543  * action, which is presumed to perform on the same mutex.
1544  * @param curr The current ModelAction; also denotes the object location to
1545  * check
1546  * @return The last unlock operation
1547  */
1548 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1549 {
1550         void *location = curr->get_location();
1551         action_list_t *list = obj_map->get_safe_ptr(location);
1552         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1553         action_list_t::reverse_iterator rit;
1554         for (rit = list->rbegin(); rit != list->rend(); rit++)
1555                 if ((*rit)->is_unlock())
1556                         return *rit;
1557         return NULL;
1558 }
1559
1560 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1561 {
1562         ModelAction *parent = get_last_action(tid);
1563         if (!parent)
1564                 parent = get_thread(tid)->get_creation();
1565         return parent;
1566 }
1567
1568 /**
1569  * Returns the clock vector for a given thread.
1570  * @param tid The thread whose clock vector we want
1571  * @return Desired clock vector
1572  */
1573 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1574 {
1575         return get_parent_action(tid)->get_cv();
1576 }
1577
1578 /**
1579  * Resolve a set of Promises with a current write. The set is provided in the
1580  * Node corresponding to @a write.
1581  * @param write The ModelAction that is fulfilling Promises
1582  * @return True if promises were resolved; false otherwise
1583  */
1584 bool ModelChecker::resolve_promises(ModelAction *write)
1585 {
1586         bool resolved = false;
1587   std::vector<thread_id_t> threads_to_check;
1588
1589         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1590                 Promise *promise = (*promises)[promise_index];
1591                 if (write->get_node()->get_promise(i)) {
1592                         ModelAction *read = promise->get_action();
1593                         if (read->is_rmw()) {
1594                                 mo_graph->addRMWEdge(write, read);
1595                         }
1596                         read->read_from(write);
1597                         //First fix up the modification order for actions that happened
1598                         //before the read
1599                         r_modification_order(read, write);
1600                         //Next fix up the modification order for actions that happened
1601                         //after the read.
1602                         post_r_modification_order(read, write);
1603                         //Make sure the promise's value matches the write's value
1604                         ASSERT(promise->get_value() == write->get_value());
1605                         delete(promise);
1606                         
1607                         promises->erase(promises->begin() + promise_index);
1608                         threads_to_check.push_back(read->get_tid());
1609
1610                         resolved = true;
1611                 } else
1612                         promise_index++;
1613         }
1614
1615         //Check whether reading these writes has made threads unable to
1616         //resolve promises
1617
1618         for(unsigned int i=0;i<threads_to_check.size();i++)
1619                 mo_check_promises(threads_to_check[i], write);
1620
1621         return resolved;
1622 }
1623
1624 /**
1625  * Compute the set of promises that could potentially be satisfied by this
1626  * action. Note that the set computation actually appears in the Node, not in
1627  * ModelChecker.
1628  * @param curr The ModelAction that may satisfy promises
1629  */
1630 void ModelChecker::compute_promises(ModelAction *curr)
1631 {
1632         for (unsigned int i = 0; i < promises->size(); i++) {
1633                 Promise *promise = (*promises)[i];
1634                 const ModelAction *act = promise->get_action();
1635                 if (!act->happens_before(curr) &&
1636                                 act->is_read() &&
1637                                 !act->could_synchronize_with(curr) &&
1638                                 !act->same_thread(curr) &&
1639                                 promise->get_value() == curr->get_value()) {
1640                         curr->get_node()->set_promise(i);
1641                 }
1642         }
1643 }
1644
1645 /** Checks promises in response to change in ClockVector Threads. */
1646 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1647 {
1648         for (unsigned int i = 0; i < promises->size(); i++) {
1649                 Promise *promise = (*promises)[i];
1650                 const ModelAction *act = promise->get_action();
1651                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1652                                 merge_cv->synchronized_since(act)) {
1653                         if (promise->increment_threads(tid)) {
1654                                 //Promise has failed
1655                                 failed_promise = true;
1656                                 return;
1657                         }
1658                 }
1659         }
1660 }
1661
1662 /** Checks promises in response to addition to modification order for threads.
1663  * Definitions:
1664  * pthread is the thread that performed the read that created the promise
1665  * 
1666  * pread is the read that created the promise
1667  *
1668  * pwrite is either the first write to same location as pread by
1669  * pthread that is sequenced after pread or the value read by the
1670  * first read to the same lcoation as pread by pthread that is
1671  * sequenced after pread..
1672  *
1673  *      1. If tid=pthread, then we check what other threads are reachable
1674  * through the mode order starting with pwrite.  Those threads cannot
1675  * perform a write that will resolve the promise due to modification
1676  * order constraints.
1677  *
1678  * 2. If the tid is not pthread, we check whether pwrite can reach the
1679  * action write through the modification order.  If so, that thread
1680  * cannot perform a future write that will resolve the promise due to
1681  * modificatin order constraints.
1682  *
1683  *      @parem tid The thread that either read from the model action
1684  *      write, or actually did the model action write.
1685  *
1686  *      @parem write The ModelAction representing the relevant write.
1687  */
1688
1689 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1690         void * location = write->get_location();
1691         for (unsigned int i = 0; i < promises->size(); i++) {
1692                 Promise *promise = (*promises)[i];
1693                 const ModelAction *act = promise->get_action();
1694                 
1695                 //Is this promise on the same location?
1696                 if ( act->get_location() != location )
1697                         continue;
1698
1699                 //same thread as the promise
1700                 if ( act->get_tid()==tid ) {
1701
1702                         //do we have a pwrite for the promise, if not, set it
1703                         if (promise->get_write() == NULL ) {
1704                                 promise->set_write(write);
1705                         }
1706                         if (mo_graph->checkPromise(write, promise)) {
1707                                 failed_promise = true;
1708                                 return;
1709                         }
1710                 }
1711                 
1712                 //Don't do any lookups twice for the same thread
1713                 if (promise->has_sync_thread(tid))
1714                         continue;
1715                 
1716                 if (mo_graph->checkReachable(promise->get_write(), write)) {
1717                         if (promise->increment_threads(tid)) {
1718                                 failed_promise = true;
1719                                 return;
1720                         }
1721                 }
1722         }
1723 }
1724
1725 /**
1726  * Compute the set of writes that may break the current pending release
1727  * sequence. This information is extracted from previou release sequence
1728  * calculations.
1729  *
1730  * @param curr The current ModelAction. Must be a release sequence fixup
1731  * action.
1732  */
1733 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1734 {
1735         if (pending_rel_seqs->empty())
1736                 return;
1737
1738         struct release_seq *pending = pending_rel_seqs->back();
1739         for (unsigned int i = 0; i < pending->writes.size(); i++) {
1740                 const ModelAction *write = pending->writes[i];
1741                 curr->get_node()->add_relseq_break(write);
1742         }
1743
1744         /* NULL means don't break the sequence; just synchronize */
1745         curr->get_node()->add_relseq_break(NULL);
1746 }
1747
1748 /**
1749  * Build up an initial set of all past writes that this 'read' action may read
1750  * from. This set is determined by the clock vector's "happens before"
1751  * relationship.
1752  * @param curr is the current ModelAction that we are exploring; it must be a
1753  * 'read' operation.
1754  */
1755 void ModelChecker::build_reads_from_past(ModelAction *curr)
1756 {
1757         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1758         unsigned int i;
1759         ASSERT(curr->is_read());
1760
1761         ModelAction *last_seq_cst = NULL;
1762
1763         /* Track whether this object has been initialized */
1764         bool initialized = false;
1765
1766         if (curr->is_seqcst()) {
1767                 last_seq_cst = get_last_seq_cst(curr);
1768                 /* We have to at least see the last sequentially consistent write,
1769                          so we are initialized. */
1770                 if (last_seq_cst != NULL)
1771                         initialized = true;
1772         }
1773
1774         /* Iterate over all threads */
1775         for (i = 0; i < thrd_lists->size(); i++) {
1776                 /* Iterate over actions in thread, starting from most recent */
1777                 action_list_t *list = &(*thrd_lists)[i];
1778                 action_list_t::reverse_iterator rit;
1779                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1780                         ModelAction *act = *rit;
1781
1782                         /* Only consider 'write' actions */
1783                         if (!act->is_write() || act == curr)
1784                                 continue;
1785
1786                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1787                         if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1788                                 DEBUG("Adding action to may_read_from:\n");
1789                                 if (DBG_ENABLED()) {
1790                                         act->print();
1791                                         curr->print();
1792                                 }
1793                                 curr->get_node()->add_read_from(act);
1794                         }
1795
1796                         /* Include at most one act per-thread that "happens before" curr */
1797                         if (act->happens_before(curr)) {
1798                                 initialized = true;
1799                                 break;
1800                         }
1801                 }
1802         }
1803
1804         if (!initialized) {
1805                 /** @todo Need a more informative way of reporting errors. */
1806                 printf("ERROR: may read from uninitialized atomic\n");
1807         }
1808
1809         if (DBG_ENABLED() || !initialized) {
1810                 printf("Reached read action:\n");
1811                 curr->print();
1812                 printf("Printing may_read_from\n");
1813                 curr->get_node()->print_may_read_from();
1814                 printf("End printing may_read_from\n");
1815         }
1816
1817         ASSERT(initialized);
1818 }
1819
1820 static void print_list(action_list_t *list)
1821 {
1822         action_list_t::iterator it;
1823
1824         printf("---------------------------------------------------------------------\n");
1825         printf("Trace:\n");
1826
1827         for (it = list->begin(); it != list->end(); it++) {
1828                 (*it)->print();
1829         }
1830         printf("---------------------------------------------------------------------\n");
1831 }
1832
1833 #if SUPPORT_MOD_ORDER_DUMP
1834 void ModelChecker::dumpGraph(char *filename) {
1835         char buffer[200];
1836   sprintf(buffer, "%s.dot",filename);
1837   FILE *file=fopen(buffer, "w");
1838   fprintf(file, "digraph %s {\n",filename);
1839         mo_graph->dumpNodes(file);
1840         ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1841         
1842         for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1843                 ModelAction *action=*it;
1844                 if (action->is_read()) {
1845                         fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1846                         if (action->get_reads_from()!=NULL)
1847                                 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1848                 }
1849                 if (thread_array[action->get_tid()] != NULL) {
1850                         fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1851                 }
1852                 
1853                 thread_array[action->get_tid()]=action;
1854         }
1855   fprintf(file,"}\n");
1856         model_free(thread_array);
1857   fclose(file); 
1858 }
1859 #endif
1860
1861 void ModelChecker::print_summary()
1862 {
1863         printf("\n");
1864         printf("Number of executions: %d\n", num_executions);
1865         printf("Number of feasible executions: %d\n", num_feasible_executions);
1866         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1867
1868 #if SUPPORT_MOD_ORDER_DUMP
1869         scheduler->print();
1870         char buffername[100];
1871         sprintf(buffername, "exec%04u", num_executions);
1872         mo_graph->dumpGraphToFile(buffername);
1873         sprintf(buffername, "graph%04u", num_executions);
1874   dumpGraph(buffername);
1875 #endif
1876
1877         if (!isfinalfeasible())
1878                 printf("INFEASIBLE EXECUTION!\n");
1879         print_list(action_trace);
1880         printf("\n");
1881 }
1882
1883 /**
1884  * Add a Thread to the system for the first time. Should only be called once
1885  * per thread.
1886  * @param t The Thread to add
1887  */
1888 void ModelChecker::add_thread(Thread *t)
1889 {
1890         thread_map->put(id_to_int(t->get_id()), t);
1891         scheduler->add_thread(t);
1892 }
1893
1894 /**
1895  * Removes a thread from the scheduler. 
1896  * @param the thread to remove.
1897  */
1898 void ModelChecker::remove_thread(Thread *t)
1899 {
1900         scheduler->remove_thread(t);
1901 }
1902
1903 /**
1904  * @brief Get a Thread reference by its ID
1905  * @param tid The Thread's ID
1906  * @return A Thread reference
1907  */
1908 Thread * ModelChecker::get_thread(thread_id_t tid) const
1909 {
1910         return thread_map->get(id_to_int(tid));
1911 }
1912
1913 /**
1914  * @brief Get a reference to the Thread in which a ModelAction was executed
1915  * @param act The ModelAction
1916  * @return A Thread reference
1917  */
1918 Thread * ModelChecker::get_thread(ModelAction *act) const
1919 {
1920         return get_thread(act->get_tid());
1921 }
1922
1923 /**
1924  * Switch from a user-context to the "master thread" context (a.k.a. system
1925  * context). This switch is made with the intention of exploring a particular
1926  * model-checking action (described by a ModelAction object). Must be called
1927  * from a user-thread context.
1928  *
1929  * @param act The current action that will be explored. May be NULL only if
1930  * trace is exiting via an assertion (see ModelChecker::set_assert and
1931  * ModelChecker::has_asserted).
1932  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1933  */
1934 int ModelChecker::switch_to_master(ModelAction *act)
1935 {
1936         DBG();
1937         Thread *old = thread_current();
1938         set_current_action(act);
1939         old->set_state(THREAD_READY);
1940         return Thread::swap(old, &system_context);
1941 }
1942
1943 /**
1944  * Takes the next step in the execution, if possible.
1945  * @return Returns true (success) if a step was taken and false otherwise.
1946  */
1947 bool ModelChecker::take_step() {
1948         if (has_asserted())
1949                 return false;
1950
1951         Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1952         if (curr) {
1953                 if (curr->get_state() == THREAD_READY) {
1954                         ASSERT(priv->current_action);
1955
1956                         priv->nextThread = check_current_action(priv->current_action);
1957                         priv->current_action = NULL;
1958
1959                         if (curr->is_blocked() || curr->is_complete())
1960                                 scheduler->remove_thread(curr);
1961                 } else {
1962                         ASSERT(false);
1963                 }
1964         }
1965         Thread *next = scheduler->next_thread(priv->nextThread);
1966
1967         /* Infeasible -> don't take any more steps */
1968         if (!isfeasible())
1969                 return false;
1970
1971         DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1972                         next ? id_to_int(next->get_id()) : -1);
1973
1974         /* next == NULL -> don't take any more steps */
1975         if (!next)
1976                 return false;
1977
1978         next->set_state(THREAD_RUNNING);
1979
1980         if (next->get_pending() != NULL) {
1981                 /* restart a pending action */
1982                 set_current_action(next->get_pending());
1983                 next->set_pending(NULL);
1984                 next->set_state(THREAD_READY);
1985                 return true;
1986         }
1987
1988         /* Return false only if swap fails with an error */
1989         return (Thread::swap(&system_context, next) == 0);
1990 }
1991
1992 /** Runs the current execution until threre are no more steps to take. */
1993 void ModelChecker::finish_execution() {
1994         DBG();
1995
1996         while (take_step());
1997 }