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