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