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