model: add release sequence model_thread ASSERT()
[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                 ASSERT(!th->is_model_thread() || future_ordered);
1338
1339                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1340                         const ModelAction *act = *rit;
1341                         /* Reach synchronization -> this thread is complete */
1342                         if (act->happens_before(release))
1343                                 break;
1344                         if (rf->happens_before(act)) {
1345                                 future_ordered = true;
1346                                 continue;
1347                         }
1348
1349                         /* Only writes can break release sequences */
1350                         if (!act->is_write())
1351                                 continue;
1352
1353                         /* Check modification order */
1354                         if (mo_graph->checkReachable(rf, act)) {
1355                                 /* rf --mo--> act */
1356                                 future_ordered = true;
1357                                 continue;
1358                         }
1359                         if (mo_graph->checkReachable(act, release))
1360                                 /* act --mo--> release */
1361                                 break;
1362                         if (mo_graph->checkReachable(release, act) &&
1363                                       mo_graph->checkReachable(act, rf)) {
1364                                 /* release --mo-> act --mo--> rf */
1365                                 return true; /* complete */
1366                         }
1367                         /* act may break release sequence */
1368                         pending->writes.push_back(act);
1369                         certain = false;
1370                 }
1371                 if (!future_ordered)
1372                         certain = false; /* This thread is uncertain */
1373         }
1374
1375         if (certain) {
1376                 release_heads->push_back(release);
1377                 pending->writes.clear();
1378         } else {
1379                 pending->release = release;
1380                 pending->rf = rf;
1381         }
1382         return certain;
1383 }
1384
1385 /**
1386  * A public interface for getting the release sequence head(s) with which a
1387  * given ModelAction must synchronize. This function only returns a non-empty
1388  * result when it can locate a release sequence head with certainty. Otherwise,
1389  * it may mark the internal state of the ModelChecker so that it will handle
1390  * the release sequence at a later time, causing @a act to update its
1391  * synchronization at some later point in execution.
1392  * @param act The 'acquire' action that may read from a release sequence
1393  * @param release_heads A pass-by-reference return parameter. Will be filled
1394  * with the head(s) of the release sequence(s), if they exists with certainty.
1395  * @see ModelChecker::release_seq_heads
1396  */
1397 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1398 {
1399         const ModelAction *rf = act->get_reads_from();
1400         struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1401         sequence->acquire = act;
1402
1403         if (!release_seq_heads(rf, release_heads, sequence)) {
1404                 /* add act to 'lazy checking' list */
1405                 pending_rel_seqs->push_back(sequence);
1406         } else {
1407                 snapshot_free(sequence);
1408         }
1409 }
1410
1411 /**
1412  * Attempt to resolve all stashed operations that might synchronize with a
1413  * release sequence for a given location. This implements the "lazy" portion of
1414  * determining whether or not a release sequence was contiguous, since not all
1415  * modification order information is present at the time an action occurs.
1416  *
1417  * @param location The location/object that should be checked for release
1418  * sequence resolutions. A NULL value means to check all locations.
1419  * @param work_queue The work queue to which to add work items as they are
1420  * generated
1421  * @return True if any updates occurred (new synchronization, new mo_graph
1422  * edges)
1423  */
1424 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1425 {
1426         bool updated = false;
1427         std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1428         while (it != pending_rel_seqs->end()) {
1429                 struct release_seq *pending = *it;
1430                 ModelAction *act = pending->acquire;
1431
1432                 /* Only resolve sequences on the given location, if provided */
1433                 if (location && act->get_location() != location) {
1434                         it++;
1435                         continue;
1436                 }
1437
1438                 const ModelAction *rf = act->get_reads_from();
1439                 rel_heads_list_t release_heads;
1440                 bool complete;
1441                 complete = release_seq_heads(rf, &release_heads, pending);
1442                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1443                         if (!act->has_synchronized_with(release_heads[i])) {
1444                                 if (act->synchronize_with(release_heads[i]))
1445                                         updated = true;
1446                                 else
1447                                         set_bad_synchronization();
1448                         }
1449                 }
1450
1451                 if (updated) {
1452                         /* Re-check all pending release sequences */
1453                         work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1454                         /* Re-check act for mo_graph edges */
1455                         work_queue->push_back(MOEdgeWorkEntry(act));
1456
1457                         /* propagate synchronization to later actions */
1458                         action_list_t::reverse_iterator rit = action_trace->rbegin();
1459                         for (; (*rit) != act; rit++) {
1460                                 ModelAction *propagate = *rit;
1461                                 if (act->happens_before(propagate)) {
1462                                         propagate->synchronize_with(act);
1463                                         /* Re-check 'propagate' for mo_graph edges */
1464                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1465                                 }
1466                         }
1467                 }
1468                 if (complete) {
1469                         it = pending_rel_seqs->erase(it);
1470                         snapshot_free(pending);
1471                 } else {
1472                         it++;
1473                 }
1474         }
1475
1476         // If we resolved promises or data races, see if we have realized a data race.
1477         if (checkDataRaces()) {
1478                 set_assert();
1479         }
1480
1481         return updated;
1482 }
1483
1484 /**
1485  * Performs various bookkeeping operations for the current ModelAction. For
1486  * instance, adds action to the per-object, per-thread action vector and to the
1487  * action trace list of all thread actions.
1488  *
1489  * @param act is the ModelAction to add.
1490  */
1491 void ModelChecker::add_action_to_lists(ModelAction *act)
1492 {
1493         int tid = id_to_int(act->get_tid());
1494         action_trace->push_back(act);
1495
1496         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1497
1498         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1499         if (tid >= (int)vec->size())
1500                 vec->resize(priv->next_thread_id);
1501         (*vec)[tid].push_back(act);
1502
1503         if ((int)thrd_last_action->size() <= tid)
1504                 thrd_last_action->resize(get_num_threads());
1505         (*thrd_last_action)[tid] = act;
1506 }
1507
1508 /**
1509  * @brief Get the last action performed by a particular Thread
1510  * @param tid The thread ID of the Thread in question
1511  * @return The last action in the thread
1512  */
1513 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1514 {
1515         int threadid = id_to_int(tid);
1516         if (threadid < (int)thrd_last_action->size())
1517                 return (*thrd_last_action)[id_to_int(tid)];
1518         else
1519                 return NULL;
1520 }
1521
1522 /**
1523  * Gets the last memory_order_seq_cst write (in the total global sequence)
1524  * performed on a particular object (i.e., memory location), not including the
1525  * current action.
1526  * @param curr The current ModelAction; also denotes the object location to
1527  * check
1528  * @return The last seq_cst write
1529  */
1530 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1531 {
1532         void *location = curr->get_location();
1533         action_list_t *list = obj_map->get_safe_ptr(location);
1534         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1535         action_list_t::reverse_iterator rit;
1536         for (rit = list->rbegin(); rit != list->rend(); rit++)
1537                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1538                         return *rit;
1539         return NULL;
1540 }
1541
1542 /**
1543  * Gets the last unlock operation performed on a particular mutex (i.e., memory
1544  * location). This function identifies the mutex according to the current
1545  * action, which is presumed to perform on the same mutex.
1546  * @param curr The current ModelAction; also denotes the object location to
1547  * check
1548  * @return The last unlock operation
1549  */
1550 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1551 {
1552         void *location = curr->get_location();
1553         action_list_t *list = obj_map->get_safe_ptr(location);
1554         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1555         action_list_t::reverse_iterator rit;
1556         for (rit = list->rbegin(); rit != list->rend(); rit++)
1557                 if ((*rit)->is_unlock())
1558                         return *rit;
1559         return NULL;
1560 }
1561
1562 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1563 {
1564         ModelAction *parent = get_last_action(tid);
1565         if (!parent)
1566                 parent = get_thread(tid)->get_creation();
1567         return parent;
1568 }
1569
1570 /**
1571  * Returns the clock vector for a given thread.
1572  * @param tid The thread whose clock vector we want
1573  * @return Desired clock vector
1574  */
1575 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1576 {
1577         return get_parent_action(tid)->get_cv();
1578 }
1579
1580 /**
1581  * Resolve a set of Promises with a current write. The set is provided in the
1582  * Node corresponding to @a write.
1583  * @param write The ModelAction that is fulfilling Promises
1584  * @return True if promises were resolved; false otherwise
1585  */
1586 bool ModelChecker::resolve_promises(ModelAction *write)
1587 {
1588         bool resolved = false;
1589   std::vector<thread_id_t> threads_to_check;
1590
1591         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1592                 Promise *promise = (*promises)[promise_index];
1593                 if (write->get_node()->get_promise(i)) {
1594                         ModelAction *read = promise->get_action();
1595                         if (read->is_rmw()) {
1596                                 mo_graph->addRMWEdge(write, read);
1597                         }
1598                         read->read_from(write);
1599                         //First fix up the modification order for actions that happened
1600                         //before the read
1601                         r_modification_order(read, write);
1602                         //Next fix up the modification order for actions that happened
1603                         //after the read.
1604                         post_r_modification_order(read, write);
1605                         //Make sure the promise's value matches the write's value
1606                         ASSERT(promise->get_value() == write->get_value());
1607                         delete(promise);
1608                         
1609                         promises->erase(promises->begin() + promise_index);
1610                         threads_to_check.push_back(read->get_tid());
1611
1612                         resolved = true;
1613                 } else
1614                         promise_index++;
1615         }
1616
1617         //Check whether reading these writes has made threads unable to
1618         //resolve promises
1619
1620         for(unsigned int i=0;i<threads_to_check.size();i++)
1621                 mo_check_promises(threads_to_check[i], write);
1622
1623         return resolved;
1624 }
1625
1626 /**
1627  * Compute the set of promises that could potentially be satisfied by this
1628  * action. Note that the set computation actually appears in the Node, not in
1629  * ModelChecker.
1630  * @param curr The ModelAction that may satisfy promises
1631  */
1632 void ModelChecker::compute_promises(ModelAction *curr)
1633 {
1634         for (unsigned int i = 0; i < promises->size(); i++) {
1635                 Promise *promise = (*promises)[i];
1636                 const ModelAction *act = promise->get_action();
1637                 if (!act->happens_before(curr) &&
1638                                 act->is_read() &&
1639                                 !act->could_synchronize_with(curr) &&
1640                                 !act->same_thread(curr) &&
1641                                 promise->get_value() == curr->get_value()) {
1642                         curr->get_node()->set_promise(i);
1643                 }
1644         }
1645 }
1646
1647 /** Checks promises in response to change in ClockVector Threads. */
1648 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1649 {
1650         for (unsigned int i = 0; i < promises->size(); i++) {
1651                 Promise *promise = (*promises)[i];
1652                 const ModelAction *act = promise->get_action();
1653                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1654                                 merge_cv->synchronized_since(act)) {
1655                         if (promise->increment_threads(tid)) {
1656                                 //Promise has failed
1657                                 failed_promise = true;
1658                                 return;
1659                         }
1660                 }
1661         }
1662 }
1663
1664 /** Checks promises in response to addition to modification order for threads.
1665  * Definitions:
1666  * pthread is the thread that performed the read that created the promise
1667  * 
1668  * pread is the read that created the promise
1669  *
1670  * pwrite is either the first write to same location as pread by
1671  * pthread that is sequenced after pread or the value read by the
1672  * first read to the same lcoation as pread by pthread that is
1673  * sequenced after pread..
1674  *
1675  *      1. If tid=pthread, then we check what other threads are reachable
1676  * through the mode order starting with pwrite.  Those threads cannot
1677  * perform a write that will resolve the promise due to modification
1678  * order constraints.
1679  *
1680  * 2. If the tid is not pthread, we check whether pwrite can reach the
1681  * action write through the modification order.  If so, that thread
1682  * cannot perform a future write that will resolve the promise due to
1683  * modificatin order constraints.
1684  *
1685  *      @parem tid The thread that either read from the model action
1686  *      write, or actually did the model action write.
1687  *
1688  *      @parem write The ModelAction representing the relevant write.
1689  */
1690
1691 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1692         void * location = write->get_location();
1693         for (unsigned int i = 0; i < promises->size(); i++) {
1694                 Promise *promise = (*promises)[i];
1695                 const ModelAction *act = promise->get_action();
1696                 
1697                 //Is this promise on the same location?
1698                 if ( act->get_location() != location )
1699                         continue;
1700
1701                 //same thread as the promise
1702                 if ( act->get_tid()==tid ) {
1703
1704                         //do we have a pwrite for the promise, if not, set it
1705                         if (promise->get_write() == NULL ) {
1706                                 promise->set_write(write);
1707                         }
1708                         if (mo_graph->checkPromise(write, promise)) {
1709                                 failed_promise = true;
1710                                 return;
1711                         }
1712                 }
1713                 
1714                 //Don't do any lookups twice for the same thread
1715                 if (promise->has_sync_thread(tid))
1716                         continue;
1717                 
1718                 if (mo_graph->checkReachable(promise->get_write(), write)) {
1719                         if (promise->increment_threads(tid)) {
1720                                 failed_promise = true;
1721                                 return;
1722                         }
1723                 }
1724         }
1725 }
1726
1727 /**
1728  * Compute the set of writes that may break the current pending release
1729  * sequence. This information is extracted from previou release sequence
1730  * calculations.
1731  *
1732  * @param curr The current ModelAction. Must be a release sequence fixup
1733  * action.
1734  */
1735 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1736 {
1737         if (pending_rel_seqs->empty())
1738                 return;
1739
1740         struct release_seq *pending = pending_rel_seqs->back();
1741         for (unsigned int i = 0; i < pending->writes.size(); i++) {
1742                 const ModelAction *write = pending->writes[i];
1743                 curr->get_node()->add_relseq_break(write);
1744         }
1745
1746         /* NULL means don't break the sequence; just synchronize */
1747         curr->get_node()->add_relseq_break(NULL);
1748 }
1749
1750 /**
1751  * Build up an initial set of all past writes that this 'read' action may read
1752  * from. This set is determined by the clock vector's "happens before"
1753  * relationship.
1754  * @param curr is the current ModelAction that we are exploring; it must be a
1755  * 'read' operation.
1756  */
1757 void ModelChecker::build_reads_from_past(ModelAction *curr)
1758 {
1759         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1760         unsigned int i;
1761         ASSERT(curr->is_read());
1762
1763         ModelAction *last_seq_cst = NULL;
1764
1765         /* Track whether this object has been initialized */
1766         bool initialized = false;
1767
1768         if (curr->is_seqcst()) {
1769                 last_seq_cst = get_last_seq_cst(curr);
1770                 /* We have to at least see the last sequentially consistent write,
1771                          so we are initialized. */
1772                 if (last_seq_cst != NULL)
1773                         initialized = true;
1774         }
1775
1776         /* Iterate over all threads */
1777         for (i = 0; i < thrd_lists->size(); i++) {
1778                 /* Iterate over actions in thread, starting from most recent */
1779                 action_list_t *list = &(*thrd_lists)[i];
1780                 action_list_t::reverse_iterator rit;
1781                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1782                         ModelAction *act = *rit;
1783
1784                         /* Only consider 'write' actions */
1785                         if (!act->is_write() || act == curr)
1786                                 continue;
1787
1788                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1789                         if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1790                                 DEBUG("Adding action to may_read_from:\n");
1791                                 if (DBG_ENABLED()) {
1792                                         act->print();
1793                                         curr->print();
1794                                 }
1795                                 curr->get_node()->add_read_from(act);
1796                         }
1797
1798                         /* Include at most one act per-thread that "happens before" curr */
1799                         if (act->happens_before(curr)) {
1800                                 initialized = true;
1801                                 break;
1802                         }
1803                 }
1804         }
1805
1806         if (!initialized) {
1807                 /** @todo Need a more informative way of reporting errors. */
1808                 printf("ERROR: may read from uninitialized atomic\n");
1809         }
1810
1811         if (DBG_ENABLED() || !initialized) {
1812                 printf("Reached read action:\n");
1813                 curr->print();
1814                 printf("Printing may_read_from\n");
1815                 curr->get_node()->print_may_read_from();
1816                 printf("End printing may_read_from\n");
1817         }
1818
1819         ASSERT(initialized);
1820 }
1821
1822 static void print_list(action_list_t *list)
1823 {
1824         action_list_t::iterator it;
1825
1826         printf("---------------------------------------------------------------------\n");
1827         printf("Trace:\n");
1828
1829         for (it = list->begin(); it != list->end(); it++) {
1830                 (*it)->print();
1831         }
1832         printf("---------------------------------------------------------------------\n");
1833 }
1834
1835 #if SUPPORT_MOD_ORDER_DUMP
1836 void ModelChecker::dumpGraph(char *filename) {
1837         char buffer[200];
1838   sprintf(buffer, "%s.dot",filename);
1839   FILE *file=fopen(buffer, "w");
1840   fprintf(file, "digraph %s {\n",filename);
1841         mo_graph->dumpNodes(file);
1842         ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1843         
1844         for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1845                 ModelAction *action=*it;
1846                 if (action->is_read()) {
1847                         fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1848                         if (action->get_reads_from()!=NULL)
1849                                 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1850                 }
1851                 if (thread_array[action->get_tid()] != NULL) {
1852                         fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1853                 }
1854                 
1855                 thread_array[action->get_tid()]=action;
1856         }
1857   fprintf(file,"}\n");
1858         model_free(thread_array);
1859   fclose(file); 
1860 }
1861 #endif
1862
1863 void ModelChecker::print_summary()
1864 {
1865         printf("\n");
1866         printf("Number of executions: %d\n", num_executions);
1867         printf("Number of feasible executions: %d\n", num_feasible_executions);
1868         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1869
1870 #if SUPPORT_MOD_ORDER_DUMP
1871         scheduler->print();
1872         char buffername[100];
1873         sprintf(buffername, "exec%04u", num_executions);
1874         mo_graph->dumpGraphToFile(buffername);
1875         sprintf(buffername, "graph%04u", num_executions);
1876   dumpGraph(buffername);
1877 #endif
1878
1879         if (!isfinalfeasible())
1880                 printf("INFEASIBLE EXECUTION!\n");
1881         print_list(action_trace);
1882         printf("\n");
1883 }
1884
1885 /**
1886  * Add a Thread to the system for the first time. Should only be called once
1887  * per thread.
1888  * @param t The Thread to add
1889  */
1890 void ModelChecker::add_thread(Thread *t)
1891 {
1892         thread_map->put(id_to_int(t->get_id()), t);
1893         scheduler->add_thread(t);
1894 }
1895
1896 /**
1897  * Removes a thread from the scheduler. 
1898  * @param the thread to remove.
1899  */
1900 void ModelChecker::remove_thread(Thread *t)
1901 {
1902         scheduler->remove_thread(t);
1903 }
1904
1905 /**
1906  * @brief Get a Thread reference by its ID
1907  * @param tid The Thread's ID
1908  * @return A Thread reference
1909  */
1910 Thread * ModelChecker::get_thread(thread_id_t tid) const
1911 {
1912         return thread_map->get(id_to_int(tid));
1913 }
1914
1915 /**
1916  * @brief Get a reference to the Thread in which a ModelAction was executed
1917  * @param act The ModelAction
1918  * @return A Thread reference
1919  */
1920 Thread * ModelChecker::get_thread(ModelAction *act) const
1921 {
1922         return get_thread(act->get_tid());
1923 }
1924
1925 /**
1926  * Switch from a user-context to the "master thread" context (a.k.a. system
1927  * context). This switch is made with the intention of exploring a particular
1928  * model-checking action (described by a ModelAction object). Must be called
1929  * from a user-thread context.
1930  *
1931  * @param act The current action that will be explored. May be NULL only if
1932  * trace is exiting via an assertion (see ModelChecker::set_assert and
1933  * ModelChecker::has_asserted).
1934  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1935  */
1936 int ModelChecker::switch_to_master(ModelAction *act)
1937 {
1938         DBG();
1939         Thread *old = thread_current();
1940         set_current_action(act);
1941         old->set_state(THREAD_READY);
1942         return Thread::swap(old, &system_context);
1943 }
1944
1945 /**
1946  * Takes the next step in the execution, if possible.
1947  * @return Returns true (success) if a step was taken and false otherwise.
1948  */
1949 bool ModelChecker::take_step() {
1950         if (has_asserted())
1951                 return false;
1952
1953         Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1954         if (curr) {
1955                 if (curr->get_state() == THREAD_READY) {
1956                         ASSERT(priv->current_action);
1957
1958                         priv->nextThread = check_current_action(priv->current_action);
1959                         priv->current_action = NULL;
1960
1961                         if (curr->is_blocked() || curr->is_complete())
1962                                 scheduler->remove_thread(curr);
1963                 } else {
1964                         ASSERT(false);
1965                 }
1966         }
1967         Thread *next = scheduler->next_thread(priv->nextThread);
1968
1969         /* Infeasible -> don't take any more steps */
1970         if (!isfeasible())
1971                 return false;
1972
1973         DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1974                         next ? id_to_int(next->get_id()) : -1);
1975
1976         /* When no more threads, or when execution replay chooses the
1977          * 'model_thread': launch end-of-execution release sequence fixups */
1978         if (!pending_rel_seqs->empty() && (!next || next->is_model_thread())) {
1979                 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
1980                                 pending_rel_seqs->size());
1981                 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
1982                                 std::memory_order_seq_cst, NULL, VALUE_NONE,
1983                                 model_thread);
1984                 set_current_action(fixup);
1985                 return true;
1986         }
1987
1988         /* next == NULL -> don't take any more steps */
1989         if (!next)
1990                 return false;
1991
1992         next->set_state(THREAD_RUNNING);
1993
1994         if (next->get_pending() != NULL) {
1995                 /* restart a pending action */
1996                 set_current_action(next->get_pending());
1997                 next->set_pending(NULL);
1998                 next->set_state(THREAD_READY);
1999                 return true;
2000         }
2001
2002         /* Return false only if swap fails with an error */
2003         return (Thread::swap(&system_context, next) == 0);
2004 }
2005
2006 /** Runs the current execution until threre are no more steps to take. */
2007 void ModelChecker::finish_execution() {
2008         DBG();
2009
2010         while (take_step());
2011 }