model: check_current_action returns its 'nextThread'
[model-checker.git] / model.cc
1 #include <stdio.h>
2
3 #include "model.h"
4 #include "action.h"
5 #include "nodestack.h"
6 #include "schedule.h"
7 #include "snapshot-interface.h"
8 #include "common.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
11 #include "promise.h"
12
13 #define INITIAL_THREAD_ID       0
14
15 ModelChecker *model;
16
17 /** @brief Constructor */
18 ModelChecker::ModelChecker(struct model_params params) :
19         /* Initialize default scheduler */
20         scheduler(new Scheduler()),
21         /* First thread created will have id INITIAL_THREAD_ID */
22         next_thread_id(INITIAL_THREAD_ID),
23         used_sequence_numbers(0),
24         num_executions(0),
25         params(params),
26         current_action(NULL),
27         diverge(NULL),
28         nextThread(NULL),
29         action_trace(new action_list_t()),
30         thread_map(new HashTable<int, Thread *, int>()),
31         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
32         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
33         promises(new std::vector<Promise *>()),
34         lazy_sync_with_release(new HashTable<void *, std::list<ModelAction *>, uintptr_t, 4>()),
35         thrd_last_action(new std::vector<ModelAction *>(1)),
36         node_stack(new NodeStack()),
37         next_backtrack(NULL),
38         mo_graph(new CycleGraph()),
39         failed_promise(false)
40 {
41 }
42
43 /** @brief Destructor */
44 ModelChecker::~ModelChecker()
45 {
46         for (int i = 0; i < get_num_threads(); i++)
47                 delete thread_map->get(i);
48         delete thread_map;
49
50         delete obj_thrd_map;
51         delete obj_map;
52         delete action_trace;
53
54         for (unsigned int i = 0; i < promises->size(); i++)
55                 delete (*promises)[i];
56         delete promises;
57
58         delete lazy_sync_with_release;
59
60         delete thrd_last_action;
61         delete node_stack;
62         delete scheduler;
63         delete mo_graph;
64 }
65
66 /**
67  * Restores user program to initial state and resets all model-checker data
68  * structures.
69  */
70 void ModelChecker::reset_to_initial_state()
71 {
72         DEBUG("+++ Resetting to initial state +++\n");
73         node_stack->reset_execution();
74         current_action = NULL;
75         next_thread_id = INITIAL_THREAD_ID;
76         used_sequence_numbers = 0;
77         nextThread = NULL;
78         next_backtrack = NULL;
79         failed_promise = false;
80         snapshotObject->backTrackBeforeStep(0);
81 }
82
83 /** @returns a thread ID for a new Thread */
84 thread_id_t ModelChecker::get_next_id()
85 {
86         return next_thread_id++;
87 }
88
89 /** @returns the number of user threads created during this execution */
90 int ModelChecker::get_num_threads()
91 {
92         return next_thread_id;
93 }
94
95 /** @returns a sequence number for a new ModelAction */
96 modelclock_t ModelChecker::get_next_seq_num()
97 {
98         return ++used_sequence_numbers;
99 }
100
101 /**
102  * Choose the next thread in the replay sequence.
103  *
104  * If the replay sequence has reached the 'diverge' point, returns a thread
105  * from the backtracking set. Otherwise, simply returns the next thread in the
106  * sequence that is being replayed.
107  */
108 Thread * ModelChecker::get_next_replay_thread()
109 {
110         thread_id_t tid;
111
112         /* Have we completed exploring the preselected path? */
113         if (diverge == NULL)
114                 return NULL;
115
116         /* Else, we are trying to replay an execution */
117         ModelAction *next = node_stack->get_next()->get_action();
118
119         if (next == diverge) {
120                 Node *nextnode = next->get_node();
121                 /* Reached divergence point */
122                 if (nextnode->increment_promise()) {
123                         /* The next node will try to satisfy a different set of promises. */
124                         tid = next->get_tid();
125                         node_stack->pop_restofstack(2);
126                 } else if (nextnode->increment_read_from()) {
127                         /* The next node will read from a different value. */
128                         tid = next->get_tid();
129                         node_stack->pop_restofstack(2);
130                 } else if (nextnode->increment_future_value()) {
131                         /* The next node will try to read from a different future value. */
132                         tid = next->get_tid();
133                         node_stack->pop_restofstack(2);
134                 } else {
135                         /* Make a different thread execute for next step */
136                         Node *node = nextnode->get_parent();
137                         tid = node->get_next_backtrack();
138                         node_stack->pop_restofstack(1);
139                 }
140                 DEBUG("*** Divergence point ***\n");
141                 diverge = NULL;
142         } else {
143                 tid = next->get_tid();
144         }
145         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
146         ASSERT(tid != THREAD_ID_T_NONE);
147         return thread_map->get(id_to_int(tid));
148 }
149
150 /**
151  * Queries the model-checker for more executions to explore and, if one
152  * exists, resets the model-checker state to execute a new execution.
153  *
154  * @return If there are more executions to explore, return true. Otherwise,
155  * return false.
156  */
157 bool ModelChecker::next_execution()
158 {
159         DBG();
160
161         num_executions++;
162
163         if (isfinalfeasible() || DBG_ENABLED())
164                 print_summary();
165
166         if ((diverge = model->get_next_backtrack()) == NULL)
167                 return false;
168
169         if (DBG_ENABLED()) {
170                 printf("Next execution will diverge at:\n");
171                 diverge->print();
172         }
173
174         model->reset_to_initial_state();
175         return true;
176 }
177
178 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
179 {
180         action_type type = act->get_type();
181
182         switch (type) {
183                 case ATOMIC_READ:
184                 case ATOMIC_WRITE:
185                 case ATOMIC_RMW:
186                         break;
187                 default:
188                         return NULL;
189         }
190         /* linear search: from most recent to oldest */
191         action_list_t *list = obj_map->get_safe_ptr(act->get_location());
192         action_list_t::reverse_iterator rit;
193         for (rit = list->rbegin(); rit != list->rend(); rit++) {
194                 ModelAction *prev = *rit;
195                 if (act->is_synchronizing(prev))
196                         return prev;
197         }
198         return NULL;
199 }
200
201 void ModelChecker::set_backtracking(ModelAction *act)
202 {
203         ModelAction *prev;
204         Node *node;
205         Thread *t = get_thread(act->get_tid());
206
207         prev = get_last_conflict(act);
208         if (prev == NULL)
209                 return;
210
211         node = prev->get_node()->get_parent();
212
213         while (!node->is_enabled(t))
214                 t = t->get_parent();
215
216         /* Check if this has been explored already */
217         if (node->has_been_explored(t->get_id()))
218                 return;
219
220         /* Cache the latest backtracking point */
221         if (!next_backtrack || *prev > *next_backtrack)
222                 next_backtrack = prev;
223
224         /* If this is a new backtracking point, mark the tree */
225         if (!node->set_backtrack(t->get_id()))
226                 return;
227         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
228                         prev->get_tid(), t->get_id());
229         if (DBG_ENABLED()) {
230                 prev->print();
231                 act->print();
232         }
233 }
234
235 /**
236  * Returns last backtracking point. The model checker will explore a different
237  * path for this point in the next execution.
238  * @return The ModelAction at which the next execution should diverge.
239  */
240 ModelAction * ModelChecker::get_next_backtrack()
241 {
242         ModelAction *next = next_backtrack;
243         next_backtrack = NULL;
244         return next;
245 }
246
247 Thread * ModelChecker::check_current_action(ModelAction *curr)
248 {
249         bool already_added = false;
250
251         ASSERT(curr);
252
253         if (curr->is_rmwc() || curr->is_rmw()) {
254                 ModelAction *tmp = process_rmw(curr);
255                 already_added = true;
256                 delete curr;
257                 curr = tmp;
258         } else {
259                 ModelAction *tmp = node_stack->explore_action(curr);
260                 if (tmp) {
261                         /* Discard duplicate ModelAction; use action from NodeStack */
262                         /* First restore type and order in case of RMW operation */
263                         if (curr->is_rmwr())
264                                 tmp->copy_typeandorder(curr);
265
266                         /* If we have diverged, we need to reset the clock vector. */
267                         if (diverge == NULL)
268                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
269
270                         delete curr;
271                         curr = tmp;
272                 } else {
273                         /*
274                          * Perform one-time actions when pushing new ModelAction onto
275                          * NodeStack
276                          */
277                         curr->create_cv(get_parent_action(curr->get_tid()));
278                         /* Build may_read_from set */
279                         if (curr->is_read())
280                                 build_reads_from_past(curr);
281                         if (curr->is_write())
282                                 compute_promises(curr);
283                 }
284         }
285
286         /* Assign 'creation' parent */
287         if (curr->get_type() == THREAD_CREATE) {
288                 Thread *th = (Thread *)curr->get_location();
289                 th->set_creation(curr);
290         }
291
292         /* Deal with new thread */
293         if (curr->get_type() == THREAD_START)
294                 check_promises(NULL, curr->get_cv());
295
296         /* Assign reads_from values */
297         Thread *th = get_thread(curr->get_tid());
298         uint64_t value = VALUE_NONE;
299         bool updated = false;
300         if (curr->is_read()) {
301                 const ModelAction *reads_from = curr->get_node()->get_read_from();
302                 if (reads_from != NULL) {
303                         value = reads_from->get_value();
304                         /* Assign reads_from, perform release/acquire synchronization */
305                         curr->read_from(reads_from);
306                         if (r_modification_order(curr,reads_from))
307                                 updated = true;
308                 } else {
309                         /* Read from future value */
310                         value = curr->get_node()->get_future_value();
311                         curr->read_from(NULL);
312                         Promise *valuepromise = new Promise(curr, value);
313                         promises->push_back(valuepromise);
314                 }
315         } else if (curr->is_write()) {
316                 if (w_modification_order(curr))
317                         updated = true;;
318                 if (resolve_promises(curr))
319                         updated = true;
320         }
321
322         if (updated)
323                 resolve_release_sequences(curr->get_location());
324
325         th->set_return_value(value);
326
327         /* Add action to list.  */
328         if (!already_added)
329                 add_action_to_lists(curr);
330
331         Node *currnode = curr->get_node();
332         Node *parnode = currnode->get_parent();
333
334         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
335                   !currnode->future_value_empty() || !currnode->promise_empty())
336                 if (!next_backtrack || *curr > *next_backtrack)
337                         next_backtrack = curr;
338
339         set_backtracking(curr);
340
341         /* Do not split atomic actions. */
342         if (curr->is_rmwr())
343                 return thread_current();
344         else
345                 return get_next_replay_thread();
346 }
347
348 /** @returns whether the current partial trace is feasible. */
349 bool ModelChecker::isfeasible() {
350         return !mo_graph->checkForCycles() && !failed_promise;
351 }
352
353 /** Returns whether the current completed trace is feasible. */
354 bool ModelChecker::isfinalfeasible() {
355         return isfeasible() && promises->size() == 0;
356 }
357
358 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
359 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
360         int tid = id_to_int(act->get_tid());
361         ModelAction *lastread = get_last_action(tid);
362         lastread->process_rmw(act);
363         if (act->is_rmw())
364                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
365         return lastread;
366 }
367
368 /**
369  * Updates the mo_graph with the constraints imposed from the current read.
370  * @param curr The current action. Must be a read.
371  * @param rf The action that curr reads from. Must be a write.
372  * @return True if modification order edges were added; false otherwise
373  */
374 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
375 {
376         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
377         unsigned int i;
378         bool added = false;
379         ASSERT(curr->is_read());
380
381         /* Iterate over all threads */
382         for (i = 0; i < thrd_lists->size(); i++) {
383                 /* Iterate over actions in thread, starting from most recent */
384                 action_list_t *list = &(*thrd_lists)[i];
385                 action_list_t::reverse_iterator rit;
386                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
387                         ModelAction *act = *rit;
388
389                         /* Include at most one act per-thread that "happens before" curr */
390                         if (act->happens_before(curr)) {
391                                 if (act->is_read()) {
392                                         const ModelAction *prevreadfrom = act->get_reads_from();
393                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
394                                                 mo_graph->addEdge(prevreadfrom, rf);
395                                                 added = true;
396                                         }
397                                 } else if (rf != act) {
398                                         mo_graph->addEdge(act, rf);
399                                         added = true;
400                                 }
401                                 break;
402                         }
403                 }
404         }
405
406         return added;
407 }
408
409 /** Updates the mo_graph with the constraints imposed from the current read. */
410 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
411 {
412         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
413         unsigned int i;
414         ASSERT(curr->is_read());
415
416         /* Iterate over all threads */
417         for (i = 0; i < thrd_lists->size(); i++) {
418                 /* Iterate over actions in thread, starting from most recent */
419                 action_list_t *list = &(*thrd_lists)[i];
420                 action_list_t::reverse_iterator rit;
421                 ModelAction *lastact = NULL;
422
423                 /* Find last action that happens after curr */
424                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
425                         ModelAction *act = *rit;
426                         if (curr->happens_before(act)) {
427                                 lastact = act;
428                         } else
429                                 break;
430                 }
431
432                         /* Include at most one act per-thread that "happens before" curr */
433                 if (lastact != NULL) {
434                         if (lastact->is_read()) {
435                                 const ModelAction *postreadfrom = lastact->get_reads_from();
436                                 if (postreadfrom != NULL&&rf != postreadfrom)
437                                         mo_graph->addEdge(rf, postreadfrom);
438                         } else if (rf != lastact) {
439                                 mo_graph->addEdge(rf, lastact);
440                         }
441                         break;
442                 }
443         }
444 }
445
446 /**
447  * Updates the mo_graph with the constraints imposed from the current write.
448  * @param curr The current action. Must be a write.
449  * @return True if modification order edges were added; false otherwise
450  */
451 bool ModelChecker::w_modification_order(ModelAction *curr)
452 {
453         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
454         unsigned int i;
455         bool added = false;
456         ASSERT(curr->is_write());
457
458         if (curr->is_seqcst()) {
459                 /* We have to at least see the last sequentially consistent write,
460                          so we are initialized. */
461                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
462                 if (last_seq_cst != NULL) {
463                         mo_graph->addEdge(last_seq_cst, curr);
464                         added = true;
465                 }
466         }
467
468         /* Iterate over all threads */
469         for (i = 0; i < thrd_lists->size(); i++) {
470                 /* Iterate over actions in thread, starting from most recent */
471                 action_list_t *list = &(*thrd_lists)[i];
472                 action_list_t::reverse_iterator rit;
473                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
474                         ModelAction *act = *rit;
475
476                         /* Include at most one act per-thread that "happens before" curr */
477                         if (act->happens_before(curr)) {
478                                 if (act->is_read())
479                                         mo_graph->addEdge(act->get_reads_from(), curr);
480                                 else
481                                         mo_graph->addEdge(act, curr);
482                                 added = true;
483                                 break;
484                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
485                                                      !act->same_thread(curr)) {
486                                 /* We have an action that:
487                                    (1) did not happen before us
488                                    (2) is a read and we are a write
489                                    (3) cannot synchronize with us
490                                    (4) is in a different thread
491                                    =>
492                                    that read could potentially read from our write.
493                                  */
494                                 if (act->get_node()->add_future_value(curr->get_value()) &&
495                                                 (!next_backtrack || *act > *next_backtrack))
496                                         next_backtrack = act;
497                         }
498                 }
499         }
500
501         return added;
502 }
503
504 /**
505  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
506  * The ModelAction under consideration is expected to be taking part in
507  * release/acquire synchronization as an object of the "reads from" relation.
508  * Note that this can only provide release sequence support for RMW chains
509  * which do not read from the future, as those actions cannot be traced until
510  * their "promise" is fulfilled. Similarly, we may not even establish the
511  * presence of a release sequence with certainty, as some modification order
512  * constraints may be decided further in the future. Thus, this function
513  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
514  * and a boolean representing certainty.
515  *
516  * @todo Finish lazy updating, when promises are fulfilled in the future
517  * @param rf The action that might be part of a release sequence. Must be a
518  * write.
519  * @param release_heads A pass-by-reference style return parameter.  After
520  * execution of this function, release_heads will contain the heads of all the
521  * relevant release sequences, if any exists
522  * @return true, if the ModelChecker is certain that release_heads is complete;
523  * false otherwise
524  */
525 bool ModelChecker::release_seq_head(const ModelAction *rf,
526                 std::vector<const ModelAction *> *release_heads) const
527 {
528         ASSERT(rf->is_write());
529         if (!rf) {
530                 /* read from future: need to settle this later */
531                 return false; /* incomplete */
532         }
533         if (rf->is_release())
534                 release_heads->push_back(rf);
535         if (rf->is_rmw()) {
536                 if (rf->is_acquire())
537                         return true; /* complete */
538                 return release_seq_head(rf->get_reads_from(), release_heads);
539         }
540         if (rf->is_release())
541                 return true; /* complete */
542
543         /* else relaxed write; check modification order for contiguous subsequence
544          * -> rf must be same thread as release */
545         int tid = id_to_int(rf->get_tid());
546         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
547         action_list_t *list = &(*thrd_lists)[tid];
548         action_list_t::const_reverse_iterator rit;
549
550         /* Find rf in the thread list */
551         for (rit = list->rbegin(); rit != list->rend(); rit++)
552                 if (*rit == rf)
553                         break;
554
555         /* Find the last write/release */
556         for (; rit != list->rend(); rit++)
557                 if ((*rit)->is_release())
558                         break;
559         if (rit == list->rend()) {
560                 /* No write-release in this thread */
561                 return true; /* complete */
562         }
563         ModelAction *release = *rit;
564
565         ASSERT(rf->same_thread(release));
566
567         bool certain = true;
568         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
569                 if (id_to_int(rf->get_tid()) == (int)i)
570                         continue;
571                 list = &(*thrd_lists)[i];
572                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
573                         const ModelAction *act = *rit;
574                         if (!act->is_write())
575                                 continue;
576                         /* Reach synchronization -> this thread is complete */
577                         if (act->happens_before(release))
578                                 break;
579                         if (rf->happens_before(act))
580                                 continue;
581
582                         /* Check modification order */
583                         if (mo_graph->checkReachable(rf, act))
584                                 /* rf --mo--> act */
585                                 continue;
586                         if (mo_graph->checkReachable(act, release))
587                                 /* act --mo--> release */
588                                 break;
589                         if (mo_graph->checkReachable(release, act) &&
590                                       mo_graph->checkReachable(act, rf)) {
591                                 /* release --mo-> act --mo--> rf */
592                                 return true; /* complete */
593                         }
594                         certain = false;
595                 }
596         }
597
598         if (certain)
599                 release_heads->push_back(release);
600         return certain;
601 }
602
603 /**
604  * A public interface for getting the release sequence head(s) with which a
605  * given ModelAction must synchronize. This function only returns a non-empty
606  * result when it can locate a release sequence head with certainty. Otherwise,
607  * it may mark the internal state of the ModelChecker so that it will handle
608  * the release sequence at a later time, causing @a act to update its
609  * synchronization at some later point in execution.
610  * @param act The 'acquire' action that may read from a release sequence
611  * @param release_heads A pass-by-reference return parameter. Will be filled
612  * with the head(s) of the release sequence(s), if they exists with certainty.
613  * @see ModelChecker::release_seq_head
614  */
615 void ModelChecker::get_release_seq_heads(ModelAction *act,
616                 std::vector<const ModelAction *> *release_heads)
617 {
618         const ModelAction *rf = act->get_reads_from();
619         bool complete;
620         complete = release_seq_head(rf, release_heads);
621         if (!complete) {
622                 /* add act to 'lazy checking' list */
623                 std::list<ModelAction *> *list;
624                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
625                 list->push_back(act);
626         }
627 }
628
629 /**
630  * Attempt to resolve all stashed operations that might synchronize with a
631  * release sequence for a given location. This implements the "lazy" portion of
632  * determining whether or not a release sequence was contiguous, since not all
633  * modification order information is present at the time an action occurs.
634  *
635  * @param location The location/object that should be checked for release
636  * sequence resolutions
637  * @return True if any updates occurred (new synchronization, new mo_graph edges)
638  */
639 bool ModelChecker::resolve_release_sequences(void *location)
640 {
641         std::list<ModelAction *> *list;
642         list = lazy_sync_with_release->getptr(location);
643         if (!list)
644                 return false;
645
646         bool updated = false;
647         std::list<ModelAction *>::iterator it = list->begin();
648         while (it != list->end()) {
649                 ModelAction *act = *it;
650                 const ModelAction *rf = act->get_reads_from();
651                 std::vector<const ModelAction *> release_heads;
652                 bool complete;
653                 complete = release_seq_head(rf, &release_heads);
654                 for (unsigned int i = 0; i < release_heads.size(); i++) {
655                         if (!act->has_synchronized_with(release_heads[i])) {
656                                 updated = true;
657                                 act->synchronize_with(release_heads[i]);
658                         }
659                 }
660
661                 if (updated) {
662                         /* propagate synchronization to later actions */
663                         action_list_t::reverse_iterator it = action_trace->rbegin();
664                         while ((*it) != act) {
665                                 ModelAction *propagate = *it;
666                                 if (act->happens_before(propagate))
667                                         /** @todo new mo_graph edges along with
668                                          * this synchronization? */
669                                         propagate->synchronize_with(act);
670                         }
671                 }
672                 if (complete)
673                         it = list->erase(it);
674                 else
675                         it++;
676         }
677
678         return updated;
679 }
680
681 /**
682  * Performs various bookkeeping operations for the current ModelAction. For
683  * instance, adds action to the per-object, per-thread action vector and to the
684  * action trace list of all thread actions.
685  *
686  * @param act is the ModelAction to add.
687  */
688 void ModelChecker::add_action_to_lists(ModelAction *act)
689 {
690         int tid = id_to_int(act->get_tid());
691         action_trace->push_back(act);
692
693         obj_map->get_safe_ptr(act->get_location())->push_back(act);
694
695         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
696         if (tid >= (int)vec->size())
697                 vec->resize(next_thread_id);
698         (*vec)[tid].push_back(act);
699
700         if ((int)thrd_last_action->size() <= tid)
701                 thrd_last_action->resize(get_num_threads());
702         (*thrd_last_action)[tid] = act;
703 }
704
705 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
706 {
707         int nthreads = get_num_threads();
708         if ((int)thrd_last_action->size() < nthreads)
709                 thrd_last_action->resize(nthreads);
710         return (*thrd_last_action)[id_to_int(tid)];
711 }
712
713 /**
714  * Gets the last memory_order_seq_cst action (in the total global sequence)
715  * performed on a particular object (i.e., memory location).
716  * @param location The object location to check
717  * @return The last seq_cst action performed
718  */
719 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
720 {
721         action_list_t *list = obj_map->get_safe_ptr(location);
722         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
723         action_list_t::reverse_iterator rit;
724         for (rit = list->rbegin(); rit != list->rend(); rit++)
725                 if ((*rit)->is_write() && (*rit)->is_seqcst())
726                         return *rit;
727         return NULL;
728 }
729
730 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
731 {
732         ModelAction *parent = get_last_action(tid);
733         if (!parent)
734                 parent = get_thread(tid)->get_creation();
735         return parent;
736 }
737
738 /**
739  * Returns the clock vector for a given thread.
740  * @param tid The thread whose clock vector we want
741  * @return Desired clock vector
742  */
743 ClockVector * ModelChecker::get_cv(thread_id_t tid)
744 {
745         return get_parent_action(tid)->get_cv();
746 }
747
748 /**
749  * Resolve a set of Promises with a current write. The set is provided in the
750  * Node corresponding to @a write.
751  * @param write The ModelAction that is fulfilling Promises
752  * @return True if promises were resolved; false otherwise
753  */
754 bool ModelChecker::resolve_promises(ModelAction *write)
755 {
756         bool resolved = false;
757         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
758                 Promise *promise = (*promises)[promise_index];
759                 if (write->get_node()->get_promise(i)) {
760                         ModelAction *read = promise->get_action();
761                         read->read_from(write);
762                         r_modification_order(read, write);
763                         post_r_modification_order(read, write);
764                         promises->erase(promises->begin() + promise_index);
765                         resolved = true;
766                 } else
767                         promise_index++;
768         }
769         return resolved;
770 }
771
772 /**
773  * Compute the set of promises that could potentially be satisfied by this
774  * action. Note that the set computation actually appears in the Node, not in
775  * ModelChecker.
776  * @param curr The ModelAction that may satisfy promises
777  */
778 void ModelChecker::compute_promises(ModelAction *curr)
779 {
780         for (unsigned int i = 0; i < promises->size(); i++) {
781                 Promise *promise = (*promises)[i];
782                 const ModelAction *act = promise->get_action();
783                 if (!act->happens_before(curr) &&
784                                 act->is_read() &&
785                                 !act->is_synchronizing(curr) &&
786                                 !act->same_thread(curr) &&
787                                 promise->get_value() == curr->get_value()) {
788                         curr->get_node()->set_promise(i);
789                 }
790         }
791 }
792
793 /** Checks promises in response to change in ClockVector Threads. */
794 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
795 {
796         for (unsigned int i = 0; i < promises->size(); i++) {
797                 Promise *promise = (*promises)[i];
798                 const ModelAction *act = promise->get_action();
799                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
800                                 merge_cv->synchronized_since(act)) {
801                         //This thread is no longer able to send values back to satisfy the promise
802                         int num_synchronized_threads = promise->increment_threads();
803                         if (num_synchronized_threads == model->get_num_threads()) {
804                                 //Promise has failed
805                                 failed_promise = true;
806                                 return;
807                         }
808                 }
809         }
810 }
811
812 /**
813  * Build up an initial set of all past writes that this 'read' action may read
814  * from. This set is determined by the clock vector's "happens before"
815  * relationship.
816  * @param curr is the current ModelAction that we are exploring; it must be a
817  * 'read' operation.
818  */
819 void ModelChecker::build_reads_from_past(ModelAction *curr)
820 {
821         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
822         unsigned int i;
823         ASSERT(curr->is_read());
824
825         ModelAction *last_seq_cst = NULL;
826
827         /* Track whether this object has been initialized */
828         bool initialized = false;
829
830         if (curr->is_seqcst()) {
831                 last_seq_cst = get_last_seq_cst(curr->get_location());
832                 /* We have to at least see the last sequentially consistent write,
833                          so we are initialized. */
834                 if (last_seq_cst != NULL)
835                         initialized = true;
836         }
837
838         /* Iterate over all threads */
839         for (i = 0; i < thrd_lists->size(); i++) {
840                 /* Iterate over actions in thread, starting from most recent */
841                 action_list_t *list = &(*thrd_lists)[i];
842                 action_list_t::reverse_iterator rit;
843                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
844                         ModelAction *act = *rit;
845
846                         /* Only consider 'write' actions */
847                         if (!act->is_write())
848                                 continue;
849
850                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
851                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
852                                 DEBUG("Adding action to may_read_from:\n");
853                                 if (DBG_ENABLED()) {
854                                         act->print();
855                                         curr->print();
856                                 }
857                                 curr->get_node()->add_read_from(act);
858                         }
859
860                         /* Include at most one act per-thread that "happens before" curr */
861                         if (act->happens_before(curr)) {
862                                 initialized = true;
863                                 break;
864                         }
865                 }
866         }
867
868         if (!initialized) {
869                 /** @todo Need a more informative way of reporting errors. */
870                 printf("ERROR: may read from uninitialized atomic\n");
871         }
872
873         if (DBG_ENABLED() || !initialized) {
874                 printf("Reached read action:\n");
875                 curr->print();
876                 printf("Printing may_read_from\n");
877                 curr->get_node()->print_may_read_from();
878                 printf("End printing may_read_from\n");
879         }
880
881         ASSERT(initialized);
882 }
883
884 static void print_list(action_list_t *list)
885 {
886         action_list_t::iterator it;
887
888         printf("---------------------------------------------------------------------\n");
889         printf("Trace:\n");
890
891         for (it = list->begin(); it != list->end(); it++) {
892                 (*it)->print();
893         }
894         printf("---------------------------------------------------------------------\n");
895 }
896
897 void ModelChecker::print_summary()
898 {
899         printf("\n");
900         printf("Number of executions: %d\n", num_executions);
901         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
902
903         scheduler->print();
904
905         if (!isfinalfeasible())
906                 printf("INFEASIBLE EXECUTION!\n");
907         print_list(action_trace);
908         printf("\n");
909 }
910
911 /**
912  * Add a Thread to the system for the first time. Should only be called once
913  * per thread.
914  * @param t The Thread to add
915  */
916 void ModelChecker::add_thread(Thread *t)
917 {
918         thread_map->put(id_to_int(t->get_id()), t);
919         scheduler->add_thread(t);
920 }
921
922 void ModelChecker::remove_thread(Thread *t)
923 {
924         scheduler->remove_thread(t);
925 }
926
927 /**
928  * Switch from a user-context to the "master thread" context (a.k.a. system
929  * context). This switch is made with the intention of exploring a particular
930  * model-checking action (described by a ModelAction object). Must be called
931  * from a user-thread context.
932  * @param act The current action that will be explored. May be NULL, although
933  * there is little reason to switch to the model-checker without an action to
934  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
935  * yield control without performing any progress; see thrd_join()).
936  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
937  */
938 int ModelChecker::switch_to_master(ModelAction *act)
939 {
940         DBG();
941         Thread *old = thread_current();
942         set_current_action(act);
943         old->set_state(THREAD_READY);
944         return Thread::swap(old, &system_context);
945 }
946
947 /**
948  * Takes the next step in the execution, if possible.
949  * @return Returns true (success) if a step was taken and false otherwise.
950  */
951 bool ModelChecker::take_step() {
952         Thread *curr, *next;
953
954         curr = thread_current();
955         if (curr) {
956                 if (curr->get_state() == THREAD_READY) {
957                         if (current_action) {
958                                 nextThread = check_current_action(current_action);
959                                 current_action = NULL;
960                         }
961                         scheduler->add_thread(curr);
962                 } else if (curr->get_state() == THREAD_RUNNING) {
963                         /* Stopped while running; i.e., completed */
964                         curr->complete();
965                 } else {
966                         ASSERT(false);
967                 }
968         }
969         next = scheduler->next_thread(nextThread);
970
971         /* Infeasible -> don't take any more steps */
972         if (!isfeasible())
973                 return false;
974
975         if (next)
976                 next->set_state(THREAD_RUNNING);
977         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
978
979         /* next == NULL -> don't take any more steps */
980         if (!next)
981                 return false;
982         /* Return false only if swap fails with an error */
983         return (Thread::swap(&system_context, next) == 0);
984 }
985
986 /** Runs the current execution until threre are no more steps to take. */
987 void ModelChecker::finish_execution() {
988         DBG();
989
990         while (take_step());
991 }