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