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