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