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