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