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