Merge branch 'norris'
[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                 /**
580                  * @todo Forcing a synchronization requires that we set
581                  * modification order constraints. For instance, we can't allow
582                  * a fixup sequence in which two separate read-acquire
583                  * operations read from the same sequence, where the first one
584                  * synchronizes and the other doesn't. Essentially, we can't
585                  * allow any writes to insert themselves between 'release' and
586                  * 'rf'
587                  */
588
589                 /* Must synchronize */
590                 if (!acquire->synchronize_with(release)) {
591                         set_bad_synchronization();
592                         return;
593                 }
594                 /* Re-check all pending release sequences */
595                 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
596                 /* Re-check act for mo_graph edges */
597                 work_queue->push_back(MOEdgeWorkEntry(acquire));
598
599                 /* propagate synchronization to later actions */
600                 action_list_t::reverse_iterator rit = action_trace->rbegin();
601                 for (; (*rit) != acquire; rit++) {
602                         ModelAction *propagate = *rit;
603                         if (acquire->happens_before(propagate)) {
604                                 propagate->synchronize_with(acquire);
605                                 /* Re-check 'propagate' for mo_graph edges */
606                                 work_queue->push_back(MOEdgeWorkEntry(propagate));
607                         }
608                 }
609         } else {
610                 /* Break release sequence with new edges:
611                  *   release --mo--> write --mo--> rf */
612                 mo_graph->addEdge(release, write);
613                 mo_graph->addEdge(write, rf);
614         }
615
616         /* See if we have realized a data race */
617         if (checkDataRaces())
618                 set_assert();
619 }
620
621 /**
622  * Initialize the current action by performing one or more of the following
623  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
624  * in the NodeStack, manipulating backtracking sets, allocating and
625  * initializing clock vectors, and computing the promises to fulfill.
626  *
627  * @param curr The current action, as passed from the user context; may be
628  * freed/invalidated after the execution of this function
629  * @return The current action, as processed by the ModelChecker. Is only the
630  * same as the parameter @a curr if this is a newly-explored action.
631  */
632 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
633 {
634         ModelAction *newcurr;
635
636         if (curr->is_rmwc() || curr->is_rmw()) {
637                 newcurr = process_rmw(curr);
638                 delete curr;
639
640                 if (newcurr->is_rmw())
641                         compute_promises(newcurr);
642                 return newcurr;
643         }
644
645         curr->set_seq_number(get_next_seq_num());
646
647         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
648         if (newcurr) {
649                 /* First restore type and order in case of RMW operation */
650                 if (curr->is_rmwr())
651                         newcurr->copy_typeandorder(curr);
652
653                 ASSERT(curr->get_location() == newcurr->get_location());
654                 newcurr->copy_from_new(curr);
655
656                 /* Discard duplicate ModelAction; use action from NodeStack */
657                 delete curr;
658
659                 /* Always compute new clock vector */
660                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
661         } else {
662                 newcurr = curr;
663
664                 /* Always compute new clock vector */
665                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
666                 /*
667                  * Perform one-time actions when pushing new ModelAction onto
668                  * NodeStack
669                  */
670                 if (newcurr->is_write())
671                         compute_promises(newcurr);
672                 else if (newcurr->is_relseq_fixup())
673                         compute_relseq_breakwrites(newcurr);
674         }
675         return newcurr;
676 }
677
678 /**
679  * This method checks whether a model action is enabled at the given point.
680  * At this point, it checks whether a lock operation would be successful at this point.
681  * If not, it puts the thread in a waiter list.
682  * @param curr is the ModelAction to check whether it is enabled.
683  * @return a bool that indicates whether the action is enabled.
684  */
685 bool ModelChecker::check_action_enabled(ModelAction *curr) {
686         if (curr->is_lock()) {
687                 std::mutex * lock = (std::mutex *)curr->get_location();
688                 struct std::mutex_state * state = lock->get_state();
689                 if (state->islocked) {
690                         //Stick the action in the appropriate waiting queue
691                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
692                         return false;
693                 }
694         }
695
696         return true;
697 }
698
699 /**
700  * This is the heart of the model checker routine. It performs model-checking
701  * actions corresponding to a given "current action." Among other processes, it
702  * calculates reads-from relationships, updates synchronization clock vectors,
703  * forms a memory_order constraints graph, and handles replay/backtrack
704  * execution when running permutations of previously-observed executions.
705  *
706  * @param curr The current action to process
707  * @return The next Thread that must be executed. May be NULL if ModelChecker
708  * makes no choice (e.g., according to replay execution, combining RMW actions,
709  * etc.)
710  */
711 Thread * ModelChecker::check_current_action(ModelAction *curr)
712 {
713         ASSERT(curr);
714
715         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
716
717         if (!check_action_enabled(curr)) {
718                 /* Make the execution look like we chose to run this action
719                  * much later, when a lock is actually available to release */
720                 get_current_thread()->set_pending(curr);
721                 scheduler->sleep(get_current_thread());
722                 return get_next_thread(NULL);
723         }
724
725         ModelAction *newcurr = initialize_curr_action(curr);
726
727         /* Add the action to lists before any other model-checking tasks */
728         if (!second_part_of_rmw)
729                 add_action_to_lists(newcurr);
730
731         /* Build may_read_from set for newly-created actions */
732         if (curr == newcurr && curr->is_read())
733                 build_reads_from_past(curr);
734         curr = newcurr;
735
736         /* Initialize work_queue with the "current action" work */
737         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
738
739         while (!work_queue.empty()) {
740                 WorkQueueEntry work = work_queue.front();
741                 work_queue.pop_front();
742
743                 switch (work.type) {
744                 case WORK_CHECK_CURR_ACTION: {
745                         ModelAction *act = work.action;
746                         bool update = false; /* update this location's release seq's */
747                         bool update_all = false; /* update all release seq's */
748
749                         if (process_thread_action(curr))
750                                 update_all = true;
751
752                         if (act->is_read() && process_read(act, second_part_of_rmw))
753                                 update = true;
754
755                         if (act->is_write() && process_write(act))
756                                 update = true;
757
758                         if (act->is_mutex_op() && process_mutex(act))
759                                 update_all = true;
760
761                         if (act->is_relseq_fixup())
762                                 process_relseq_fixup(curr, &work_queue);
763
764                         if (update_all)
765                                 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
766                         else if (update)
767                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
768                         break;
769                 }
770                 case WORK_CHECK_RELEASE_SEQ:
771                         resolve_release_sequences(work.location, &work_queue);
772                         break;
773                 case WORK_CHECK_MO_EDGES: {
774                         /** @todo Complete verification of work_queue */
775                         ModelAction *act = work.action;
776                         bool updated = false;
777
778                         if (act->is_read()) {
779                                 const ModelAction *rf = act->get_reads_from();
780                                 if (rf != NULL && r_modification_order(act, rf))
781                                         updated = true;
782                         }
783                         if (act->is_write()) {
784                                 if (w_modification_order(act))
785                                         updated = true;
786                         }
787                         mo_graph->commitChanges();
788
789                         if (updated)
790                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
791                         break;
792                 }
793                 default:
794                         ASSERT(false);
795                         break;
796                 }
797         }
798
799         check_curr_backtracking(curr);
800
801         set_backtracking(curr);
802
803         return get_next_thread(curr);
804 }
805
806 /**
807  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
808  * operation from the Thread it is joining with. Must be called after the
809  * completion of the Thread in question.
810  * @param join The THREAD_JOIN action
811  */
812 void ModelChecker::do_complete_join(ModelAction *join)
813 {
814         Thread *blocking = (Thread *)join->get_location();
815         ModelAction *act = get_last_action(blocking->get_id());
816         join->synchronize_with(act);
817 }
818
819 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
820         Node *currnode = curr->get_node();
821         Node *parnode = currnode->get_parent();
822
823         if ((!parnode->backtrack_empty() ||
824                          !currnode->read_from_empty() ||
825                          !currnode->future_value_empty() ||
826                          !currnode->promise_empty() ||
827                          !currnode->relseq_break_empty())
828                         && (!priv->next_backtrack ||
829                                         *curr > *priv->next_backtrack)) {
830                 priv->next_backtrack = curr;
831         }
832 }
833
834 bool ModelChecker::promises_expired() {
835         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
836                 Promise *promise = (*promises)[promise_index];
837                 if (promise->get_expiration()<priv->used_sequence_numbers) {
838                         return true;
839                 }
840         }
841         return false;
842 }
843
844 /** @return whether the current partial trace must be a prefix of a
845  * feasible trace. */
846 bool ModelChecker::isfeasibleprefix() {
847         return promises->size() == 0 && pending_rel_seqs->size() == 0;
848 }
849
850 /** @return whether the current partial trace is feasible. */
851 bool ModelChecker::isfeasible() {
852         if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
853                 DEBUG("Infeasible: RMW violation\n");
854
855         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
856 }
857
858 /** @return whether the current partial trace is feasible other than
859  * multiple RMW reading from the same store. */
860 bool ModelChecker::isfeasibleotherthanRMW() {
861         if (DBG_ENABLED()) {
862                 if (mo_graph->checkForCycles())
863                         DEBUG("Infeasible: modification order cycles\n");
864                 if (failed_promise)
865                         DEBUG("Infeasible: failed promise\n");
866                 if (too_many_reads)
867                         DEBUG("Infeasible: too many reads\n");
868                 if (bad_synchronization)
869                         DEBUG("Infeasible: bad synchronization ordering\n");
870                 if (promises_expired())
871                         DEBUG("Infeasible: promises expired\n");
872         }
873         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
874 }
875
876 /** Returns whether the current completed trace is feasible. */
877 bool ModelChecker::isfinalfeasible() {
878         if (DBG_ENABLED() && promises->size() != 0)
879                 DEBUG("Infeasible: unrevolved promises\n");
880
881         return isfeasible() && promises->size() == 0;
882 }
883
884 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
885 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
886         ModelAction *lastread = get_last_action(act->get_tid());
887         lastread->process_rmw(act);
888         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
889                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
890                 mo_graph->commitChanges();
891         }
892         return lastread;
893 }
894
895 /**
896  * Checks whether a thread has read from the same write for too many times
897  * without seeing the effects of a later write.
898  *
899  * Basic idea:
900  * 1) there must a different write that we could read from that would satisfy the modification order,
901  * 2) we must have read from the same value in excess of maxreads times, and
902  * 3) that other write must have been in the reads_from set for maxreads times.
903  *
904  * If so, we decide that the execution is no longer feasible.
905  */
906 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
907         if (params.maxreads != 0) {
908
909                 if (curr->get_node()->get_read_from_size() <= 1)
910                         return;
911                 //Must make sure that execution is currently feasible...  We could
912                 //accidentally clear by rolling back
913                 if (!isfeasible())
914                         return;
915                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
916                 int tid = id_to_int(curr->get_tid());
917
918                 /* Skip checks */
919                 if ((int)thrd_lists->size() <= tid)
920                         return;
921                 action_list_t *list = &(*thrd_lists)[tid];
922
923                 action_list_t::reverse_iterator rit = list->rbegin();
924                 /* Skip past curr */
925                 for (; (*rit) != curr; rit++)
926                         ;
927                 /* go past curr now */
928                 rit++;
929
930                 action_list_t::reverse_iterator ritcopy = rit;
931                 //See if we have enough reads from the same value
932                 int count = 0;
933                 for (; count < params.maxreads; rit++,count++) {
934                         if (rit==list->rend())
935                                 return;
936                         ModelAction *act = *rit;
937                         if (!act->is_read())
938                                 return;
939                         
940                         if (act->get_reads_from() != rf)
941                                 return;
942                         if (act->get_node()->get_read_from_size() <= 1)
943                                 return;
944                 }
945                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
946                         //Get write
947                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
948
949                         //Need a different write
950                         if (write==rf)
951                                 continue;
952
953                         /* Test to see whether this is a feasible write to read from*/
954                         mo_graph->startChanges();
955                         r_modification_order(curr, write);
956                         bool feasiblereadfrom = isfeasible();
957                         mo_graph->rollbackChanges();
958
959                         if (!feasiblereadfrom)
960                                 continue;
961                         rit = ritcopy;
962
963                         bool feasiblewrite = true;
964                         //new we need to see if this write works for everyone
965
966                         for (int loop = count; loop>0; loop--,rit++) {
967                                 ModelAction *act=*rit;
968                                 bool foundvalue = false;
969                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
970                                         if (act->get_node()->get_read_from_at(i)==write) {
971                                                 foundvalue = true;
972                                                 break;
973                                         }
974                                 }
975                                 if (!foundvalue) {
976                                         feasiblewrite = false;
977                                         break;
978                                 }
979                         }
980                         if (feasiblewrite) {
981                                 too_many_reads = true;
982                                 return;
983                         }
984                 }
985         }
986 }
987
988 /**
989  * Updates the mo_graph with the constraints imposed from the current
990  * read.
991  *
992  * Basic idea is the following: Go through each other thread and find
993  * the lastest action that happened before our read.  Two cases:
994  *
995  * (1) The action is a write => that write must either occur before
996  * the write we read from or be the write we read from.
997  *
998  * (2) The action is a read => the write that that action read from
999  * must occur before the write we read from or be the same write.
1000  *
1001  * @param curr The current action. Must be a read.
1002  * @param rf The action that curr reads from. Must be a write.
1003  * @return True if modification order edges were added; false otherwise
1004  */
1005 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
1006 {
1007         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1008         unsigned int i;
1009         bool added = false;
1010         ASSERT(curr->is_read());
1011
1012         /* Iterate over all threads */
1013         for (i = 0; i < thrd_lists->size(); i++) {
1014                 /* Iterate over actions in thread, starting from most recent */
1015                 action_list_t *list = &(*thrd_lists)[i];
1016                 action_list_t::reverse_iterator rit;
1017                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1018                         ModelAction *act = *rit;
1019
1020                         /*
1021                          * Include at most one act per-thread that "happens
1022                          * before" curr. Don't consider reflexively.
1023                          */
1024                         if (act->happens_before(curr) && act != curr) {
1025                                 if (act->is_write()) {
1026                                         if (rf != act) {
1027                                                 mo_graph->addEdge(act, rf);
1028                                                 added = true;
1029                                         }
1030                                 } else {
1031                                         const ModelAction *prevreadfrom = act->get_reads_from();
1032                                         //if the previous read is unresolved, keep going...
1033                                         if (prevreadfrom == NULL)
1034                                                 continue;
1035
1036                                         if (rf != prevreadfrom) {
1037                                                 mo_graph->addEdge(prevreadfrom, rf);
1038                                                 added = true;
1039                                         }
1040                                 }
1041                                 break;
1042                         }
1043                 }
1044         }
1045
1046         return added;
1047 }
1048
1049 /** This method fixes up the modification order when we resolve a
1050  *  promises.  The basic problem is that actions that occur after the
1051  *  read curr could not property add items to the modification order
1052  *  for our read.
1053  *
1054  *  So for each thread, we find the earliest item that happens after
1055  *  the read curr.  This is the item we have to fix up with additional
1056  *  constraints.  If that action is write, we add a MO edge between
1057  *  the Action rf and that action.  If the action is a read, we add a
1058  *  MO edge between the Action rf, and whatever the read accessed.
1059  *
1060  * @param curr is the read ModelAction that we are fixing up MO edges for.
1061  * @param rf is the write ModelAction that curr reads from.
1062  *
1063  */
1064 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1065 {
1066         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1067         unsigned int i;
1068         ASSERT(curr->is_read());
1069
1070         /* Iterate over all threads */
1071         for (i = 0; i < thrd_lists->size(); i++) {
1072                 /* Iterate over actions in thread, starting from most recent */
1073                 action_list_t *list = &(*thrd_lists)[i];
1074                 action_list_t::reverse_iterator rit;
1075                 ModelAction *lastact = NULL;
1076
1077                 /* Find last action that happens after curr that is either not curr or a rmw */
1078                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1079                         ModelAction *act = *rit;
1080                         if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1081                                 lastact = act;
1082                         } else
1083                                 break;
1084                 }
1085
1086                         /* Include at most one act per-thread that "happens before" curr */
1087                 if (lastact != NULL) {
1088                         if (lastact==curr) {
1089                                 //Case 1: The resolved read is a RMW, and we need to make sure
1090                                 //that the write portion of the RMW mod order after rf
1091
1092                                 mo_graph->addEdge(rf, lastact);
1093                         } else if (lastact->is_read()) {
1094                                 //Case 2: The resolved read is a normal read and the next
1095                                 //operation is a read, and we need to make sure the value read
1096                                 //is mod ordered after rf
1097
1098                                 const ModelAction *postreadfrom = lastact->get_reads_from();
1099                                 if (postreadfrom != NULL&&rf != postreadfrom)
1100                                         mo_graph->addEdge(rf, postreadfrom);
1101                         } else {
1102                                 //Case 3: The resolved read is a normal read and the next
1103                                 //operation is a write, and we need to make sure that the
1104                                 //write is mod ordered after rf
1105                                 if (lastact!=rf)
1106                                         mo_graph->addEdge(rf, lastact);
1107                         }
1108                         break;
1109                 }
1110         }
1111 }
1112
1113 /**
1114  * Updates the mo_graph with the constraints imposed from the current write.
1115  *
1116  * Basic idea is the following: Go through each other thread and find
1117  * the lastest action that happened before our write.  Two cases:
1118  *
1119  * (1) The action is a write => that write must occur before
1120  * the current write
1121  *
1122  * (2) The action is a read => the write that that action read from
1123  * must occur before the current write.
1124  *
1125  * This method also handles two other issues:
1126  *
1127  * (I) Sequential Consistency: Making sure that if the current write is
1128  * seq_cst, that it occurs after the previous seq_cst write.
1129  *
1130  * (II) Sending the write back to non-synchronizing reads.
1131  *
1132  * @param curr The current action. Must be a write.
1133  * @return True if modification order edges were added; false otherwise
1134  */
1135 bool ModelChecker::w_modification_order(ModelAction *curr)
1136 {
1137         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1138         unsigned int i;
1139         bool added = false;
1140         ASSERT(curr->is_write());
1141
1142         if (curr->is_seqcst()) {
1143                 /* We have to at least see the last sequentially consistent write,
1144                          so we are initialized. */
1145                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1146                 if (last_seq_cst != NULL) {
1147                         mo_graph->addEdge(last_seq_cst, curr);
1148                         added = true;
1149                 }
1150         }
1151
1152         /* Iterate over all threads */
1153         for (i = 0; i < thrd_lists->size(); i++) {
1154                 /* Iterate over actions in thread, starting from most recent */
1155                 action_list_t *list = &(*thrd_lists)[i];
1156                 action_list_t::reverse_iterator rit;
1157                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1158                         ModelAction *act = *rit;
1159                         if (act == curr) {
1160                                 /*
1161                                  * 1) If RMW and it actually read from something, then we
1162                                  * already have all relevant edges, so just skip to next
1163                                  * thread.
1164                                  * 
1165                                  * 2) If RMW and it didn't read from anything, we should
1166                                  * whatever edge we can get to speed up convergence.
1167                                  *
1168                                  * 3) If normal write, we need to look at earlier actions, so
1169                                  * continue processing list.
1170                                  */
1171                                 if (curr->is_rmw()) {
1172                                         if (curr->get_reads_from()!=NULL)
1173                                                 break;
1174                                         else 
1175                                                 continue;
1176                                 } else
1177                                         continue;
1178                         }
1179
1180                         /*
1181                          * Include at most one act per-thread that "happens
1182                          * before" curr
1183                          */
1184                         if (act->happens_before(curr)) {
1185                                 /*
1186                                  * Note: if act is RMW, just add edge:
1187                                  *   act --mo--> curr
1188                                  * The following edge should be handled elsewhere:
1189                                  *   readfrom(act) --mo--> act
1190                                  */
1191                                 if (act->is_write())
1192                                         mo_graph->addEdge(act, curr);
1193                                 else if (act->is_read()) { 
1194                                         //if previous read accessed a null, just keep going
1195                                         if (act->get_reads_from() == NULL)
1196                                                 continue;
1197                                         mo_graph->addEdge(act->get_reads_from(), curr);
1198                                 }
1199                                 added = true;
1200                                 break;
1201                         } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1202                                                      !act->same_thread(curr)) {
1203                                 /* We have an action that:
1204                                    (1) did not happen before us
1205                                    (2) is a read and we are a write
1206                                    (3) cannot synchronize with us
1207                                    (4) is in a different thread
1208                                    =>
1209                                    that read could potentially read from our write.
1210                                  */
1211                                 if (thin_air_constraint_may_allow(curr, act)) {
1212                                         if (isfeasible() ||
1213                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1214                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1215                                                 futurevalues->push_back(pfv);
1216                                         }
1217                                 }
1218                         }
1219                 }
1220         }
1221
1222         return added;
1223 }
1224
1225 /** Arbitrary reads from the future are not allowed.  Section 29.3
1226  * part 9 places some constraints.  This method checks one result of constraint
1227  * constraint.  Others require compiler support. */
1228 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1229         if (!writer->is_rmw())
1230                 return true;
1231
1232         if (!reader->is_rmw())
1233                 return true;
1234
1235         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1236                 if (search == reader)
1237                         return false;
1238                 if (search->get_tid() == reader->get_tid() &&
1239                                 search->happens_before(reader))
1240                         break;
1241         }
1242
1243         return true;
1244 }
1245
1246 /**
1247  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1248  * The ModelAction under consideration is expected to be taking part in
1249  * release/acquire synchronization as an object of the "reads from" relation.
1250  * Note that this can only provide release sequence support for RMW chains
1251  * which do not read from the future, as those actions cannot be traced until
1252  * their "promise" is fulfilled. Similarly, we may not even establish the
1253  * presence of a release sequence with certainty, as some modification order
1254  * constraints may be decided further in the future. Thus, this function
1255  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1256  * and a boolean representing certainty.
1257  *
1258  * @todo Finish lazy updating, when promises are fulfilled in the future
1259  * @param rf The action that might be part of a release sequence. Must be a
1260  * write.
1261  * @param release_heads A pass-by-reference style return parameter. After
1262  * execution of this function, release_heads will contain the heads of all the
1263  * relevant release sequences, if any exists with certainty
1264  * @param pending A pass-by-reference style return parameter which is only used
1265  * when returning false (i.e., uncertain). Returns most information regarding
1266  * an uncertain release sequence, including any write operations that might
1267  * break the sequence.
1268  * @return true, if the ModelChecker is certain that release_heads is complete;
1269  * false otherwise
1270  */
1271 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1272                 rel_heads_list_t *release_heads,
1273                 struct release_seq *pending) const
1274 {
1275         /* Only check for release sequences if there are no cycles */
1276         if (mo_graph->checkForCycles())
1277                 return false;
1278
1279         while (rf) {
1280                 ASSERT(rf->is_write());
1281
1282                 if (rf->is_release())
1283                         release_heads->push_back(rf);
1284                 if (!rf->is_rmw())
1285                         break; /* End of RMW chain */
1286
1287                 /** @todo Need to be smarter here...  In the linux lock
1288                  * example, this will run to the beginning of the program for
1289                  * every acquire. */
1290                 /** @todo The way to be smarter here is to keep going until 1
1291                  * thread has a release preceded by an acquire and you've seen
1292                  *       both. */
1293
1294                 /* acq_rel RMW is a sufficient stopping condition */
1295                 if (rf->is_acquire() && rf->is_release())
1296                         return true; /* complete */
1297
1298                 rf = rf->get_reads_from();
1299         };
1300         if (!rf) {
1301                 /* read from future: need to settle this later */
1302                 pending->rf = NULL;
1303                 return false; /* incomplete */
1304         }
1305
1306         if (rf->is_release())
1307                 return true; /* complete */
1308
1309         /* else relaxed write; check modification order for contiguous subsequence
1310          * -> rf must be same thread as release */
1311         int tid = id_to_int(rf->get_tid());
1312         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1313         action_list_t *list = &(*thrd_lists)[tid];
1314         action_list_t::const_reverse_iterator rit;
1315
1316         /* Find rf in the thread list */
1317         rit = std::find(list->rbegin(), list->rend(), rf);
1318         ASSERT(rit != list->rend());
1319
1320         /* Find the last write/release */
1321         for (; rit != list->rend(); rit++)
1322                 if ((*rit)->is_release())
1323                         break;
1324         if (rit == list->rend()) {
1325                 /* No write-release in this thread */
1326                 return true; /* complete */
1327         }
1328         ModelAction *release = *rit;
1329
1330         ASSERT(rf->same_thread(release));
1331
1332         pending->writes.clear();
1333
1334         bool certain = true;
1335         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1336                 if (id_to_int(rf->get_tid()) == (int)i)
1337                         continue;
1338                 list = &(*thrd_lists)[i];
1339
1340                 /* Can we ensure no future writes from this thread may break
1341                  * the release seq? */
1342                 bool future_ordered = false;
1343
1344                 ModelAction *last = get_last_action(int_to_id(i));
1345                 Thread *th = get_thread(int_to_id(i));
1346                 if ((last && rf->happens_before(last)) ||
1347                                 !scheduler->is_enabled(th) ||
1348                                 th->is_complete())
1349                         future_ordered = true;
1350
1351                 ASSERT(!th->is_model_thread() || future_ordered);
1352
1353                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1354                         const ModelAction *act = *rit;
1355                         /* Reach synchronization -> this thread is complete */
1356                         if (act->happens_before(release))
1357                                 break;
1358                         if (rf->happens_before(act)) {
1359                                 future_ordered = true;
1360                                 continue;
1361                         }
1362
1363                         /* Only writes can break release sequences */
1364                         if (!act->is_write())
1365                                 continue;
1366
1367                         /* Check modification order */
1368                         if (mo_graph->checkReachable(rf, act)) {
1369                                 /* rf --mo--> act */
1370                                 future_ordered = true;
1371                                 continue;
1372                         }
1373                         if (mo_graph->checkReachable(act, release))
1374                                 /* act --mo--> release */
1375                                 break;
1376                         if (mo_graph->checkReachable(release, act) &&
1377                                       mo_graph->checkReachable(act, rf)) {
1378                                 /* release --mo-> act --mo--> rf */
1379                                 return true; /* complete */
1380                         }
1381                         /* act may break release sequence */
1382                         pending->writes.push_back(act);
1383                         certain = false;
1384                 }
1385                 if (!future_ordered)
1386                         certain = false; /* This thread is uncertain */
1387         }
1388
1389         if (certain) {
1390                 release_heads->push_back(release);
1391                 pending->writes.clear();
1392         } else {
1393                 pending->release = release;
1394                 pending->rf = rf;
1395         }
1396         return certain;
1397 }
1398
1399 /**
1400  * A public interface for getting the release sequence head(s) with which a
1401  * given ModelAction must synchronize. This function only returns a non-empty
1402  * result when it can locate a release sequence head with certainty. Otherwise,
1403  * it may mark the internal state of the ModelChecker so that it will handle
1404  * the release sequence at a later time, causing @a act to update its
1405  * synchronization at some later point in execution.
1406  * @param act The 'acquire' action that may read from a release sequence
1407  * @param release_heads A pass-by-reference return parameter. Will be filled
1408  * with the head(s) of the release sequence(s), if they exists with certainty.
1409  * @see ModelChecker::release_seq_heads
1410  */
1411 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1412 {
1413         const ModelAction *rf = act->get_reads_from();
1414         struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1415         sequence->acquire = act;
1416
1417         if (!release_seq_heads(rf, release_heads, sequence)) {
1418                 /* add act to 'lazy checking' list */
1419                 pending_rel_seqs->push_back(sequence);
1420         } else {
1421                 snapshot_free(sequence);
1422         }
1423 }
1424
1425 /**
1426  * Attempt to resolve all stashed operations that might synchronize with a
1427  * release sequence for a given location. This implements the "lazy" portion of
1428  * determining whether or not a release sequence was contiguous, since not all
1429  * modification order information is present at the time an action occurs.
1430  *
1431  * @param location The location/object that should be checked for release
1432  * sequence resolutions. A NULL value means to check all locations.
1433  * @param work_queue The work queue to which to add work items as they are
1434  * generated
1435  * @return True if any updates occurred (new synchronization, new mo_graph
1436  * edges)
1437  */
1438 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1439 {
1440         bool updated = false;
1441         std::vector<struct release_seq *>::iterator it = pending_rel_seqs->begin();
1442         while (it != pending_rel_seqs->end()) {
1443                 struct release_seq *pending = *it;
1444                 ModelAction *act = pending->acquire;
1445
1446                 /* Only resolve sequences on the given location, if provided */
1447                 if (location && act->get_location() != location) {
1448                         it++;
1449                         continue;
1450                 }
1451
1452                 const ModelAction *rf = act->get_reads_from();
1453                 rel_heads_list_t release_heads;
1454                 bool complete;
1455                 complete = release_seq_heads(rf, &release_heads, pending);
1456                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1457                         if (!act->has_synchronized_with(release_heads[i])) {
1458                                 if (act->synchronize_with(release_heads[i]))
1459                                         updated = true;
1460                                 else
1461                                         set_bad_synchronization();
1462                         }
1463                 }
1464
1465                 if (updated) {
1466                         /* Re-check all pending release sequences */
1467                         work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1468                         /* Re-check act for mo_graph edges */
1469                         work_queue->push_back(MOEdgeWorkEntry(act));
1470
1471                         /* propagate synchronization to later actions */
1472                         action_list_t::reverse_iterator rit = action_trace->rbegin();
1473                         for (; (*rit) != act; rit++) {
1474                                 ModelAction *propagate = *rit;
1475                                 if (act->happens_before(propagate)) {
1476                                         propagate->synchronize_with(act);
1477                                         /* Re-check 'propagate' for mo_graph edges */
1478                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1479                                 }
1480                         }
1481                 }
1482                 if (complete) {
1483                         it = pending_rel_seqs->erase(it);
1484                         snapshot_free(pending);
1485                 } else {
1486                         it++;
1487                 }
1488         }
1489
1490         // If we resolved promises or data races, see if we have realized a data race.
1491         if (checkDataRaces()) {
1492                 set_assert();
1493         }
1494
1495         return updated;
1496 }
1497
1498 /**
1499  * Performs various bookkeeping operations for the current ModelAction. For
1500  * instance, adds action to the per-object, per-thread action vector and to the
1501  * action trace list of all thread actions.
1502  *
1503  * @param act is the ModelAction to add.
1504  */
1505 void ModelChecker::add_action_to_lists(ModelAction *act)
1506 {
1507         int tid = id_to_int(act->get_tid());
1508         action_trace->push_back(act);
1509
1510         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1511
1512         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1513         if (tid >= (int)vec->size())
1514                 vec->resize(priv->next_thread_id);
1515         (*vec)[tid].push_back(act);
1516
1517         if ((int)thrd_last_action->size() <= tid)
1518                 thrd_last_action->resize(get_num_threads());
1519         (*thrd_last_action)[tid] = act;
1520 }
1521
1522 /**
1523  * @brief Get the last action performed by a particular Thread
1524  * @param tid The thread ID of the Thread in question
1525  * @return The last action in the thread
1526  */
1527 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1528 {
1529         int threadid = id_to_int(tid);
1530         if (threadid < (int)thrd_last_action->size())
1531                 return (*thrd_last_action)[id_to_int(tid)];
1532         else
1533                 return NULL;
1534 }
1535
1536 /**
1537  * Gets the last memory_order_seq_cst write (in the total global sequence)
1538  * performed on a particular object (i.e., memory location), not including the
1539  * current action.
1540  * @param curr The current ModelAction; also denotes the object location to
1541  * check
1542  * @return The last seq_cst write
1543  */
1544 ModelAction * ModelChecker::get_last_seq_cst(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) | seq_cst(t_i) && isWrite(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_write() && (*rit)->is_seqcst() && (*rit) != curr)
1552                         return *rit;
1553         return NULL;
1554 }
1555
1556 /**
1557  * Gets the last unlock operation performed on a particular mutex (i.e., memory
1558  * location). This function identifies the mutex according to the current
1559  * action, which is presumed to perform on the same mutex.
1560  * @param curr The current ModelAction; also denotes the object location to
1561  * check
1562  * @return The last unlock operation
1563  */
1564 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1565 {
1566         void *location = curr->get_location();
1567         action_list_t *list = obj_map->get_safe_ptr(location);
1568         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1569         action_list_t::reverse_iterator rit;
1570         for (rit = list->rbegin(); rit != list->rend(); rit++)
1571                 if ((*rit)->is_unlock())
1572                         return *rit;
1573         return NULL;
1574 }
1575
1576 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1577 {
1578         ModelAction *parent = get_last_action(tid);
1579         if (!parent)
1580                 parent = get_thread(tid)->get_creation();
1581         return parent;
1582 }
1583
1584 /**
1585  * Returns the clock vector for a given thread.
1586  * @param tid The thread whose clock vector we want
1587  * @return Desired clock vector
1588  */
1589 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1590 {
1591         return get_parent_action(tid)->get_cv();
1592 }
1593
1594 /**
1595  * Resolve a set of Promises with a current write. The set is provided in the
1596  * Node corresponding to @a write.
1597  * @param write The ModelAction that is fulfilling Promises
1598  * @return True if promises were resolved; false otherwise
1599  */
1600 bool ModelChecker::resolve_promises(ModelAction *write)
1601 {
1602         bool resolved = false;
1603   std::vector<thread_id_t> threads_to_check;
1604
1605         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1606                 Promise *promise = (*promises)[promise_index];
1607                 if (write->get_node()->get_promise(i)) {
1608                         ModelAction *read = promise->get_action();
1609                         if (read->is_rmw()) {
1610                                 mo_graph->addRMWEdge(write, read);
1611                         }
1612                         read->read_from(write);
1613                         //First fix up the modification order for actions that happened
1614                         //before the read
1615                         r_modification_order(read, write);
1616                         //Next fix up the modification order for actions that happened
1617                         //after the read.
1618                         post_r_modification_order(read, write);
1619                         //Make sure the promise's value matches the write's value
1620                         ASSERT(promise->get_value() == write->get_value());
1621                         delete(promise);
1622                         
1623                         promises->erase(promises->begin() + promise_index);
1624                         threads_to_check.push_back(read->get_tid());
1625
1626                         resolved = true;
1627                 } else
1628                         promise_index++;
1629         }
1630
1631         //Check whether reading these writes has made threads unable to
1632         //resolve promises
1633
1634         for(unsigned int i=0;i<threads_to_check.size();i++)
1635                 mo_check_promises(threads_to_check[i], write);
1636
1637         return resolved;
1638 }
1639
1640 /**
1641  * Compute the set of promises that could potentially be satisfied by this
1642  * action. Note that the set computation actually appears in the Node, not in
1643  * ModelChecker.
1644  * @param curr The ModelAction that may satisfy promises
1645  */
1646 void ModelChecker::compute_promises(ModelAction *curr)
1647 {
1648         for (unsigned int i = 0; i < promises->size(); i++) {
1649                 Promise *promise = (*promises)[i];
1650                 const ModelAction *act = promise->get_action();
1651                 if (!act->happens_before(curr) &&
1652                                 act->is_read() &&
1653                                 !act->could_synchronize_with(curr) &&
1654                                 !act->same_thread(curr) &&
1655                                 promise->get_value() == curr->get_value()) {
1656                         curr->get_node()->set_promise(i);
1657                 }
1658         }
1659 }
1660
1661 /** Checks promises in response to change in ClockVector Threads. */
1662 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1663 {
1664         for (unsigned int i = 0; i < promises->size(); i++) {
1665                 Promise *promise = (*promises)[i];
1666                 const ModelAction *act = promise->get_action();
1667                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1668                                 merge_cv->synchronized_since(act)) {
1669                         if (promise->increment_threads(tid)) {
1670                                 //Promise has failed
1671                                 failed_promise = true;
1672                                 return;
1673                         }
1674                 }
1675         }
1676 }
1677
1678 /** Checks promises in response to addition to modification order for threads.
1679  * Definitions:
1680  * pthread is the thread that performed the read that created the promise
1681  * 
1682  * pread is the read that created the promise
1683  *
1684  * pwrite is either the first write to same location as pread by
1685  * pthread that is sequenced after pread or the value read by the
1686  * first read to the same lcoation as pread by pthread that is
1687  * sequenced after pread..
1688  *
1689  *      1. If tid=pthread, then we check what other threads are reachable
1690  * through the mode order starting with pwrite.  Those threads cannot
1691  * perform a write that will resolve the promise due to modification
1692  * order constraints.
1693  *
1694  * 2. If the tid is not pthread, we check whether pwrite can reach the
1695  * action write through the modification order.  If so, that thread
1696  * cannot perform a future write that will resolve the promise due to
1697  * modificatin order constraints.
1698  *
1699  *      @parem tid The thread that either read from the model action
1700  *      write, or actually did the model action write.
1701  *
1702  *      @parem write The ModelAction representing the relevant write.
1703  */
1704
1705 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1706         void * location = write->get_location();
1707         for (unsigned int i = 0; i < promises->size(); i++) {
1708                 Promise *promise = (*promises)[i];
1709                 const ModelAction *act = promise->get_action();
1710                 
1711                 //Is this promise on the same location?
1712                 if ( act->get_location() != location )
1713                         continue;
1714
1715                 //same thread as the promise
1716                 if ( act->get_tid()==tid ) {
1717
1718                         //do we have a pwrite for the promise, if not, set it
1719                         if (promise->get_write() == NULL ) {
1720                                 promise->set_write(write);
1721                         }
1722                         if (mo_graph->checkPromise(write, promise)) {
1723                                 failed_promise = true;
1724                                 return;
1725                         }
1726                 }
1727                 
1728                 //Don't do any lookups twice for the same thread
1729                 if (promise->has_sync_thread(tid))
1730                         continue;
1731                 
1732                 if (mo_graph->checkReachable(promise->get_write(), write)) {
1733                         if (promise->increment_threads(tid)) {
1734                                 failed_promise = true;
1735                                 return;
1736                         }
1737                 }
1738         }
1739 }
1740
1741 /**
1742  * Compute the set of writes that may break the current pending release
1743  * sequence. This information is extracted from previou release sequence
1744  * calculations.
1745  *
1746  * @param curr The current ModelAction. Must be a release sequence fixup
1747  * action.
1748  */
1749 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1750 {
1751         if (pending_rel_seqs->empty())
1752                 return;
1753
1754         struct release_seq *pending = pending_rel_seqs->back();
1755         for (unsigned int i = 0; i < pending->writes.size(); i++) {
1756                 const ModelAction *write = pending->writes[i];
1757                 curr->get_node()->add_relseq_break(write);
1758         }
1759
1760         /* NULL means don't break the sequence; just synchronize */
1761         curr->get_node()->add_relseq_break(NULL);
1762 }
1763
1764 /**
1765  * Build up an initial set of all past writes that this 'read' action may read
1766  * from. This set is determined by the clock vector's "happens before"
1767  * relationship.
1768  * @param curr is the current ModelAction that we are exploring; it must be a
1769  * 'read' operation.
1770  */
1771 void ModelChecker::build_reads_from_past(ModelAction *curr)
1772 {
1773         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1774         unsigned int i;
1775         ASSERT(curr->is_read());
1776
1777         ModelAction *last_seq_cst = NULL;
1778
1779         /* Track whether this object has been initialized */
1780         bool initialized = false;
1781
1782         if (curr->is_seqcst()) {
1783                 last_seq_cst = get_last_seq_cst(curr);
1784                 /* We have to at least see the last sequentially consistent write,
1785                          so we are initialized. */
1786                 if (last_seq_cst != NULL)
1787                         initialized = true;
1788         }
1789
1790         /* Iterate over all threads */
1791         for (i = 0; i < thrd_lists->size(); i++) {
1792                 /* Iterate over actions in thread, starting from most recent */
1793                 action_list_t *list = &(*thrd_lists)[i];
1794                 action_list_t::reverse_iterator rit;
1795                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1796                         ModelAction *act = *rit;
1797
1798                         /* Only consider 'write' actions */
1799                         if (!act->is_write() || act == curr)
1800                                 continue;
1801
1802                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1803                         if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1804                                 DEBUG("Adding action to may_read_from:\n");
1805                                 if (DBG_ENABLED()) {
1806                                         act->print();
1807                                         curr->print();
1808                                 }
1809                                 curr->get_node()->add_read_from(act);
1810                         }
1811
1812                         /* Include at most one act per-thread that "happens before" curr */
1813                         if (act->happens_before(curr)) {
1814                                 initialized = true;
1815                                 break;
1816                         }
1817                 }
1818         }
1819
1820         if (!initialized) {
1821                 /** @todo Need a more informative way of reporting errors. */
1822                 printf("ERROR: may read from uninitialized atomic\n");
1823         }
1824
1825         if (DBG_ENABLED() || !initialized) {
1826                 printf("Reached read action:\n");
1827                 curr->print();
1828                 printf("Printing may_read_from\n");
1829                 curr->get_node()->print_may_read_from();
1830                 printf("End printing may_read_from\n");
1831         }
1832
1833         ASSERT(initialized);
1834 }
1835
1836 static void print_list(action_list_t *list)
1837 {
1838         action_list_t::iterator it;
1839
1840         printf("---------------------------------------------------------------------\n");
1841         printf("Trace:\n");
1842
1843         for (it = list->begin(); it != list->end(); it++) {
1844                 (*it)->print();
1845         }
1846         printf("---------------------------------------------------------------------\n");
1847 }
1848
1849 #if SUPPORT_MOD_ORDER_DUMP
1850 void ModelChecker::dumpGraph(char *filename) {
1851         char buffer[200];
1852   sprintf(buffer, "%s.dot",filename);
1853   FILE *file=fopen(buffer, "w");
1854   fprintf(file, "digraph %s {\n",filename);
1855         mo_graph->dumpNodes(file);
1856         ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1857         
1858         for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1859                 ModelAction *action=*it;
1860                 if (action->is_read()) {
1861                         fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1862                         if (action->get_reads_from()!=NULL)
1863                                 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1864                 }
1865                 if (thread_array[action->get_tid()] != NULL) {
1866                         fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1867                 }
1868                 
1869                 thread_array[action->get_tid()]=action;
1870         }
1871   fprintf(file,"}\n");
1872         model_free(thread_array);
1873   fclose(file); 
1874 }
1875 #endif
1876
1877 void ModelChecker::print_summary()
1878 {
1879         printf("\n");
1880         printf("Number of executions: %d\n", num_executions);
1881         printf("Number of feasible executions: %d\n", num_feasible_executions);
1882         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1883
1884 #if SUPPORT_MOD_ORDER_DUMP
1885         scheduler->print();
1886         char buffername[100];
1887         sprintf(buffername, "exec%04u", num_executions);
1888         mo_graph->dumpGraphToFile(buffername);
1889         sprintf(buffername, "graph%04u", num_executions);
1890   dumpGraph(buffername);
1891 #endif
1892
1893         if (!isfinalfeasible())
1894                 printf("INFEASIBLE EXECUTION!\n");
1895         print_list(action_trace);
1896         printf("\n");
1897 }
1898
1899 /**
1900  * Add a Thread to the system for the first time. Should only be called once
1901  * per thread.
1902  * @param t The Thread to add
1903  */
1904 void ModelChecker::add_thread(Thread *t)
1905 {
1906         thread_map->put(id_to_int(t->get_id()), t);
1907         scheduler->add_thread(t);
1908 }
1909
1910 /**
1911  * Removes a thread from the scheduler. 
1912  * @param the thread to remove.
1913  */
1914 void ModelChecker::remove_thread(Thread *t)
1915 {
1916         scheduler->remove_thread(t);
1917 }
1918
1919 /**
1920  * @brief Get a Thread reference by its ID
1921  * @param tid The Thread's ID
1922  * @return A Thread reference
1923  */
1924 Thread * ModelChecker::get_thread(thread_id_t tid) const
1925 {
1926         return thread_map->get(id_to_int(tid));
1927 }
1928
1929 /**
1930  * @brief Get a reference to the Thread in which a ModelAction was executed
1931  * @param act The ModelAction
1932  * @return A Thread reference
1933  */
1934 Thread * ModelChecker::get_thread(ModelAction *act) const
1935 {
1936         return get_thread(act->get_tid());
1937 }
1938
1939 /**
1940  * Switch from a user-context to the "master thread" context (a.k.a. system
1941  * context). This switch is made with the intention of exploring a particular
1942  * model-checking action (described by a ModelAction object). Must be called
1943  * from a user-thread context.
1944  *
1945  * @param act The current action that will be explored. May be NULL only if
1946  * trace is exiting via an assertion (see ModelChecker::set_assert and
1947  * ModelChecker::has_asserted).
1948  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1949  */
1950 int ModelChecker::switch_to_master(ModelAction *act)
1951 {
1952         DBG();
1953         Thread *old = thread_current();
1954         set_current_action(act);
1955         old->set_state(THREAD_READY);
1956         return Thread::swap(old, &system_context);
1957 }
1958
1959 /**
1960  * Takes the next step in the execution, if possible.
1961  * @return Returns true (success) if a step was taken and false otherwise.
1962  */
1963 bool ModelChecker::take_step() {
1964         if (has_asserted())
1965                 return false;
1966
1967         Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
1968         if (curr) {
1969                 if (curr->get_state() == THREAD_READY) {
1970                         ASSERT(priv->current_action);
1971
1972                         priv->nextThread = check_current_action(priv->current_action);
1973                         priv->current_action = NULL;
1974
1975                         if (curr->is_blocked() || curr->is_complete())
1976                                 scheduler->remove_thread(curr);
1977                 } else {
1978                         ASSERT(false);
1979                 }
1980         }
1981         Thread *next = scheduler->next_thread(priv->nextThread);
1982
1983         /* Infeasible -> don't take any more steps */
1984         if (!isfeasible())
1985                 return false;
1986
1987         DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
1988                         next ? id_to_int(next->get_id()) : -1);
1989
1990         /*
1991          * Launch end-of-execution release sequence fixups only when there are:
1992          *
1993          * (1) no more user threads to run (or when execution replay chooses
1994          *     the 'model_thread')
1995          * (2) pending release sequences
1996          * (3) pending assertions (i.e., data races)
1997          * (4) no pending promises
1998          */
1999         if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
2000                         isfinalfeasible() && !unrealizedraces.empty()) {
2001                 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
2002                                 pending_rel_seqs->size());
2003                 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2004                                 std::memory_order_seq_cst, NULL, VALUE_NONE,
2005                                 model_thread);
2006                 set_current_action(fixup);
2007                 return true;
2008         }
2009
2010         /* next == NULL -> don't take any more steps */
2011         if (!next)
2012                 return false;
2013
2014         next->set_state(THREAD_RUNNING);
2015
2016         if (next->get_pending() != NULL) {
2017                 /* restart a pending action */
2018                 set_current_action(next->get_pending());
2019                 next->set_pending(NULL);
2020                 next->set_state(THREAD_READY);
2021                 return true;
2022         }
2023
2024         /* Return false only if swap fails with an error */
2025         return (Thread::swap(&system_context, next) == 0);
2026 }
2027
2028 /** Runs the current execution until threre are no more steps to take. */
2029 void ModelChecker::finish_execution() {
2030         DBG();
2031
2032         while (take_step());
2033 }