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