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