model/schedule: revise 'nextThread' data flow
[c11tester.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 void ModelChecker::check_current_action(void)
248 {
249         ModelAction *curr = this->current_action;
250         bool already_added = false;
251         this->current_action = NULL;
252         if (!curr) {
253                 DEBUG("trying to push NULL action...\n");
254                 return;
255         }
256
257         if (curr->is_rmwc() || curr->is_rmw()) {
258                 ModelAction *tmp = process_rmw(curr);
259                 already_added = true;
260                 delete curr;
261                 curr = tmp;
262         } else {
263                 ModelAction *tmp = node_stack->explore_action(curr);
264                 if (tmp) {
265                         /* Discard duplicate ModelAction; use action from NodeStack */
266                         /* First restore type and order in case of RMW operation */
267                         if (curr->is_rmwr())
268                                 tmp->copy_typeandorder(curr);
269
270                         /* If we have diverged, we need to reset the clock vector. */
271                         if (diverge == NULL)
272                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
273
274                         delete curr;
275                         curr = tmp;
276                 } else {
277                         /*
278                          * Perform one-time actions when pushing new ModelAction onto
279                          * NodeStack
280                          */
281                         curr->create_cv(get_parent_action(curr->get_tid()));
282                         /* Build may_read_from set */
283                         if (curr->is_read())
284                                 build_reads_from_past(curr);
285                         if (curr->is_write())
286                                 compute_promises(curr);
287                 }
288         }
289
290         /* Assign 'creation' parent */
291         if (curr->get_type() == THREAD_CREATE) {
292                 Thread *th = (Thread *)curr->get_location();
293                 th->set_creation(curr);
294         }
295
296         /* Deal with new thread */
297         if (curr->get_type() == THREAD_START)
298                 check_promises(NULL, curr->get_cv());
299
300         /* Assign reads_from values */
301         Thread *th = get_thread(curr->get_tid());
302         uint64_t value = VALUE_NONE;
303         bool updated = false;
304         if (curr->is_read()) {
305                 const ModelAction *reads_from = curr->get_node()->get_read_from();
306                 if (reads_from != NULL) {
307                         value = reads_from->get_value();
308                         /* Assign reads_from, perform release/acquire synchronization */
309                         curr->read_from(reads_from);
310                         if (r_modification_order(curr,reads_from))
311                                 updated = true;
312                 } else {
313                         /* Read from future value */
314                         value = curr->get_node()->get_future_value();
315                         curr->read_from(NULL);
316                         Promise *valuepromise = new Promise(curr, value);
317                         promises->push_back(valuepromise);
318                 }
319         } else if (curr->is_write()) {
320                 if (w_modification_order(curr))
321                         updated = true;;
322                 if (resolve_promises(curr))
323                         updated = true;
324         }
325
326         if (updated)
327                 resolve_release_sequences(curr->get_location());
328
329         th->set_return_value(value);
330
331         /* Add action to list.  */
332         if (!already_added)
333                 add_action_to_lists(curr);
334
335         /** @todo Is there a better interface for setting the next thread rather
336                  than this field/convoluted approach?  Perhaps like just returning
337                  it or something? */
338
339         /* Do not split atomic actions. */
340         if (curr->is_rmwr())
341                 nextThread = thread_current();
342         else
343                 nextThread = get_next_replay_thread();
344
345         Node *currnode = curr->get_node();
346         Node *parnode = currnode->get_parent();
347
348         if (!parnode->backtrack_empty() || !currnode->read_from_empty() ||
349                   !currnode->future_value_empty() || !currnode->promise_empty())
350                 if (!next_backtrack || *curr > *next_backtrack)
351                         next_backtrack = curr;
352
353         set_backtracking(curr);
354 }
355
356 /** @returns whether the current partial trace is feasible. */
357 bool ModelChecker::isfeasible() {
358         return !mo_graph->checkForCycles() && !failed_promise;
359 }
360
361 /** Returns whether the current completed trace is feasible. */
362 bool ModelChecker::isfinalfeasible() {
363         return isfeasible() && promises->size() == 0;
364 }
365
366 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
367 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
368         int tid = id_to_int(act->get_tid());
369         ModelAction *lastread = get_last_action(tid);
370         lastread->process_rmw(act);
371         if (act->is_rmw())
372                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
373         return lastread;
374 }
375
376 /**
377  * Updates the mo_graph with the constraints imposed from the current read.
378  * @param curr The current action. Must be a read.
379  * @param rf The action that curr reads from. Must be a write.
380  * @return True if modification order edges were added; false otherwise
381  */
382 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
383 {
384         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
385         unsigned int i;
386         bool added = false;
387         ASSERT(curr->is_read());
388
389         /* Iterate over all threads */
390         for (i = 0; i < thrd_lists->size(); i++) {
391                 /* Iterate over actions in thread, starting from most recent */
392                 action_list_t *list = &(*thrd_lists)[i];
393                 action_list_t::reverse_iterator rit;
394                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
395                         ModelAction *act = *rit;
396
397                         /* Include at most one act per-thread that "happens before" curr */
398                         if (act->happens_before(curr)) {
399                                 if (act->is_read()) {
400                                         const ModelAction *prevreadfrom = act->get_reads_from();
401                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
402                                                 mo_graph->addEdge(prevreadfrom, rf);
403                                                 added = true;
404                                         }
405                                 } else if (rf != act) {
406                                         mo_graph->addEdge(act, rf);
407                                         added = true;
408                                 }
409                                 break;
410                         }
411                 }
412         }
413
414         return added;
415 }
416
417 /** Updates the mo_graph with the constraints imposed from the current read. */
418 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
419 {
420         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
421         unsigned int i;
422         ASSERT(curr->is_read());
423
424         /* Iterate over all threads */
425         for (i = 0; i < thrd_lists->size(); i++) {
426                 /* Iterate over actions in thread, starting from most recent */
427                 action_list_t *list = &(*thrd_lists)[i];
428                 action_list_t::reverse_iterator rit;
429                 ModelAction *lastact = NULL;
430
431                 /* Find last action that happens after curr */
432                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
433                         ModelAction *act = *rit;
434                         if (curr->happens_before(act)) {
435                                 lastact = act;
436                         } else
437                                 break;
438                 }
439
440                         /* Include at most one act per-thread that "happens before" curr */
441                 if (lastact != NULL) {
442                         if (lastact->is_read()) {
443                                 const ModelAction *postreadfrom = lastact->get_reads_from();
444                                 if (postreadfrom != NULL&&rf != postreadfrom)
445                                         mo_graph->addEdge(rf, postreadfrom);
446                         } else if (rf != lastact) {
447                                 mo_graph->addEdge(rf, lastact);
448                         }
449                         break;
450                 }
451         }
452 }
453
454 /**
455  * Updates the mo_graph with the constraints imposed from the current write.
456  * @param curr The current action. Must be a write.
457  * @return True if modification order edges were added; false otherwise
458  */
459 bool ModelChecker::w_modification_order(ModelAction *curr)
460 {
461         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
462         unsigned int i;
463         bool added = false;
464         ASSERT(curr->is_write());
465
466         if (curr->is_seqcst()) {
467                 /* We have to at least see the last sequentially consistent write,
468                          so we are initialized. */
469                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
470                 if (last_seq_cst != NULL) {
471                         mo_graph->addEdge(last_seq_cst, curr);
472                         added = true;
473                 }
474         }
475
476         /* Iterate over all threads */
477         for (i = 0; i < thrd_lists->size(); i++) {
478                 /* Iterate over actions in thread, starting from most recent */
479                 action_list_t *list = &(*thrd_lists)[i];
480                 action_list_t::reverse_iterator rit;
481                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
482                         ModelAction *act = *rit;
483
484                         /* Include at most one act per-thread that "happens before" curr */
485                         if (act->happens_before(curr)) {
486                                 if (act->is_read())
487                                         mo_graph->addEdge(act->get_reads_from(), curr);
488                                 else
489                                         mo_graph->addEdge(act, curr);
490                                 added = true;
491                                 break;
492                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
493                                                      !act->same_thread(curr)) {
494                                 /* We have an action that:
495                                    (1) did not happen before us
496                                    (2) is a read and we are a write
497                                    (3) cannot synchronize with us
498                                    (4) is in a different thread
499                                    =>
500                                    that read could potentially read from our write.
501                                  */
502                                 if (act->get_node()->add_future_value(curr->get_value()) &&
503                                                 (!next_backtrack || *act > *next_backtrack))
504                                         next_backtrack = act;
505                         }
506                 }
507         }
508
509         return added;
510 }
511
512 /**
513  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
514  * The ModelAction under consideration is expected to be taking part in
515  * release/acquire synchronization as an object of the "reads from" relation.
516  * Note that this can only provide release sequence support for RMW chains
517  * which do not read from the future, as those actions cannot be traced until
518  * their "promise" is fulfilled. Similarly, we may not even establish the
519  * presence of a release sequence with certainty, as some modification order
520  * constraints may be decided further in the future. Thus, this function
521  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
522  * and a boolean representing certainty.
523  *
524  * @todo Finish lazy updating, when promises are fulfilled in the future
525  * @param rf The action that might be part of a release sequence. Must be a
526  * write.
527  * @param release_heads A pass-by-reference style return parameter.  After
528  * execution of this function, release_heads will contain the heads of all the
529  * relevant release sequences, if any exists
530  * @return true, if the ModelChecker is certain that release_heads is complete;
531  * false otherwise
532  */
533 bool ModelChecker::release_seq_head(const ModelAction *rf,
534                 std::vector<const ModelAction *> *release_heads) const
535 {
536         ASSERT(rf->is_write());
537         if (!rf) {
538                 /* read from future: need to settle this later */
539                 return false; /* incomplete */
540         }
541         if (rf->is_release())
542                 release_heads->push_back(rf);
543         if (rf->is_rmw()) {
544                 if (rf->is_acquire())
545                         return true; /* complete */
546                 return release_seq_head(rf->get_reads_from(), release_heads);
547         }
548         if (rf->is_release())
549                 return true; /* complete */
550
551         /* else relaxed write; check modification order for contiguous subsequence
552          * -> rf must be same thread as release */
553         int tid = id_to_int(rf->get_tid());
554         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
555         action_list_t *list = &(*thrd_lists)[tid];
556         action_list_t::const_reverse_iterator rit;
557
558         /* Find rf in the thread list */
559         for (rit = list->rbegin(); rit != list->rend(); rit++)
560                 if (*rit == rf)
561                         break;
562
563         /* Find the last write/release */
564         for (; rit != list->rend(); rit++)
565                 if ((*rit)->is_release())
566                         break;
567         if (rit == list->rend()) {
568                 /* No write-release in this thread */
569                 return true; /* complete */
570         }
571         ModelAction *release = *rit;
572
573         ASSERT(rf->same_thread(release));
574
575         bool certain = true;
576         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
577                 if (id_to_int(rf->get_tid()) == (int)i)
578                         continue;
579                 list = &(*thrd_lists)[i];
580                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
581                         const ModelAction *act = *rit;
582                         if (!act->is_write())
583                                 continue;
584                         /* Reach synchronization -> this thread is complete */
585                         if (act->happens_before(release))
586                                 break;
587                         if (rf->happens_before(act))
588                                 continue;
589
590                         /* Check modification order */
591                         if (mo_graph->checkReachable(rf, act))
592                                 /* rf --mo--> act */
593                                 continue;
594                         if (mo_graph->checkReachable(act, release))
595                                 /* act --mo--> release */
596                                 break;
597                         if (mo_graph->checkReachable(release, act) &&
598                                       mo_graph->checkReachable(act, rf)) {
599                                 /* release --mo-> act --mo--> rf */
600                                 return true; /* complete */
601                         }
602                         certain = false;
603                 }
604         }
605
606         if (certain)
607                 release_heads->push_back(release);
608         return certain;
609 }
610
611 /**
612  * A public interface for getting the release sequence head(s) with which a
613  * given ModelAction must synchronize. This function only returns a non-empty
614  * result when it can locate a release sequence head with certainty. Otherwise,
615  * it may mark the internal state of the ModelChecker so that it will handle
616  * the release sequence at a later time, causing @a act to update its
617  * synchronization at some later point in execution.
618  * @param act The 'acquire' action that may read from a release sequence
619  * @param release_heads A pass-by-reference return parameter. Will be filled
620  * with the head(s) of the release sequence(s), if they exists with certainty.
621  * @see ModelChecker::release_seq_head
622  */
623 void ModelChecker::get_release_seq_heads(ModelAction *act,
624                 std::vector<const ModelAction *> *release_heads)
625 {
626         const ModelAction *rf = act->get_reads_from();
627         bool complete;
628         complete = release_seq_head(rf, release_heads);
629         if (!complete) {
630                 /* add act to 'lazy checking' list */
631                 std::list<ModelAction *> *list;
632                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
633                 list->push_back(act);
634         }
635 }
636
637 /**
638  * Attempt to resolve all stashed operations that might synchronize with a
639  * release sequence for a given location. This implements the "lazy" portion of
640  * determining whether or not a release sequence was contiguous, since not all
641  * modification order information is present at the time an action occurs.
642  *
643  * @param location The location/object that should be checked for release
644  * sequence resolutions
645  * @return True if any updates occurred (new synchronization, new mo_graph edges)
646  */
647 bool ModelChecker::resolve_release_sequences(void *location)
648 {
649         std::list<ModelAction *> *list;
650         list = lazy_sync_with_release->getptr(location);
651         if (!list)
652                 return false;
653
654         bool updated = false;
655         std::list<ModelAction *>::iterator it = list->begin();
656         while (it != list->end()) {
657                 ModelAction *act = *it;
658                 const ModelAction *rf = act->get_reads_from();
659                 std::vector<const ModelAction *> release_heads;
660                 bool complete;
661                 complete = release_seq_head(rf, &release_heads);
662                 for (unsigned int i = 0; i < release_heads.size(); i++) {
663                         if (!act->has_synchronized_with(release_heads[i])) {
664                                 updated = true;
665                                 act->synchronize_with(release_heads[i]);
666                         }
667                 }
668
669                 if (updated) {
670                         /* propagate synchronization to later actions */
671                         action_list_t::reverse_iterator it = action_trace->rbegin();
672                         while ((*it) != act) {
673                                 ModelAction *propagate = *it;
674                                 if (act->happens_before(propagate))
675                                         /** @todo new mo_graph edges along with
676                                          * this synchronization? */
677                                         propagate->synchronize_with(act);
678                         }
679                 }
680                 if (complete)
681                         it = list->erase(it);
682                 else
683                         it++;
684         }
685
686         return updated;
687 }
688
689 /**
690  * Performs various bookkeeping operations for the current ModelAction. For
691  * instance, adds action to the per-object, per-thread action vector and to the
692  * action trace list of all thread actions.
693  *
694  * @param act is the ModelAction to add.
695  */
696 void ModelChecker::add_action_to_lists(ModelAction *act)
697 {
698         int tid = id_to_int(act->get_tid());
699         action_trace->push_back(act);
700
701         obj_map->get_safe_ptr(act->get_location())->push_back(act);
702
703         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
704         if (tid >= (int)vec->size())
705                 vec->resize(next_thread_id);
706         (*vec)[tid].push_back(act);
707
708         if ((int)thrd_last_action->size() <= tid)
709                 thrd_last_action->resize(get_num_threads());
710         (*thrd_last_action)[tid] = act;
711 }
712
713 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
714 {
715         int nthreads = get_num_threads();
716         if ((int)thrd_last_action->size() < nthreads)
717                 thrd_last_action->resize(nthreads);
718         return (*thrd_last_action)[id_to_int(tid)];
719 }
720
721 /**
722  * Gets the last memory_order_seq_cst action (in the total global sequence)
723  * performed on a particular object (i.e., memory location).
724  * @param location The object location to check
725  * @return The last seq_cst action performed
726  */
727 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
728 {
729         action_list_t *list = obj_map->get_safe_ptr(location);
730         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
731         action_list_t::reverse_iterator rit;
732         for (rit = list->rbegin(); rit != list->rend(); rit++)
733                 if ((*rit)->is_write() && (*rit)->is_seqcst())
734                         return *rit;
735         return NULL;
736 }
737
738 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
739 {
740         ModelAction *parent = get_last_action(tid);
741         if (!parent)
742                 parent = get_thread(tid)->get_creation();
743         return parent;
744 }
745
746 /**
747  * Returns the clock vector for a given thread.
748  * @param tid The thread whose clock vector we want
749  * @return Desired clock vector
750  */
751 ClockVector * ModelChecker::get_cv(thread_id_t tid)
752 {
753         return get_parent_action(tid)->get_cv();
754 }
755
756 /**
757  * Resolve a set of Promises with a current write. The set is provided in the
758  * Node corresponding to @a write.
759  * @param write The ModelAction that is fulfilling Promises
760  * @return True if promises were resolved; false otherwise
761  */
762 bool ModelChecker::resolve_promises(ModelAction *write)
763 {
764         bool resolved = false;
765         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
766                 Promise *promise = (*promises)[promise_index];
767                 if (write->get_node()->get_promise(i)) {
768                         ModelAction *read = promise->get_action();
769                         read->read_from(write);
770                         r_modification_order(read, write);
771                         post_r_modification_order(read, write);
772                         promises->erase(promises->begin() + promise_index);
773                         resolved = true;
774                 } else
775                         promise_index++;
776         }
777         return resolved;
778 }
779
780 /**
781  * Compute the set of promises that could potentially be satisfied by this
782  * action. Note that the set computation actually appears in the Node, not in
783  * ModelChecker.
784  * @param curr The ModelAction that may satisfy promises
785  */
786 void ModelChecker::compute_promises(ModelAction *curr)
787 {
788         for (unsigned int i = 0; i < promises->size(); i++) {
789                 Promise *promise = (*promises)[i];
790                 const ModelAction *act = promise->get_action();
791                 if (!act->happens_before(curr) &&
792                                 act->is_read() &&
793                                 !act->is_synchronizing(curr) &&
794                                 !act->same_thread(curr) &&
795                                 promise->get_value() == curr->get_value()) {
796                         curr->get_node()->set_promise(i);
797                 }
798         }
799 }
800
801 /** Checks promises in response to change in ClockVector Threads. */
802 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
803 {
804         for (unsigned int i = 0; i < promises->size(); i++) {
805                 Promise *promise = (*promises)[i];
806                 const ModelAction *act = promise->get_action();
807                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
808                                 merge_cv->synchronized_since(act)) {
809                         //This thread is no longer able to send values back to satisfy the promise
810                         int num_synchronized_threads = promise->increment_threads();
811                         if (num_synchronized_threads == model->get_num_threads()) {
812                                 //Promise has failed
813                                 failed_promise = true;
814                                 return;
815                         }
816                 }
817         }
818 }
819
820 /**
821  * Build up an initial set of all past writes that this 'read' action may read
822  * from. This set is determined by the clock vector's "happens before"
823  * relationship.
824  * @param curr is the current ModelAction that we are exploring; it must be a
825  * 'read' operation.
826  */
827 void ModelChecker::build_reads_from_past(ModelAction *curr)
828 {
829         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
830         unsigned int i;
831         ASSERT(curr->is_read());
832
833         ModelAction *last_seq_cst = NULL;
834
835         /* Track whether this object has been initialized */
836         bool initialized = false;
837
838         if (curr->is_seqcst()) {
839                 last_seq_cst = get_last_seq_cst(curr->get_location());
840                 /* We have to at least see the last sequentially consistent write,
841                          so we are initialized. */
842                 if (last_seq_cst != NULL)
843                         initialized = true;
844         }
845
846         /* Iterate over all threads */
847         for (i = 0; i < thrd_lists->size(); i++) {
848                 /* Iterate over actions in thread, starting from most recent */
849                 action_list_t *list = &(*thrd_lists)[i];
850                 action_list_t::reverse_iterator rit;
851                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
852                         ModelAction *act = *rit;
853
854                         /* Only consider 'write' actions */
855                         if (!act->is_write())
856                                 continue;
857
858                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
859                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
860                                 DEBUG("Adding action to may_read_from:\n");
861                                 if (DBG_ENABLED()) {
862                                         act->print();
863                                         curr->print();
864                                 }
865                                 curr->get_node()->add_read_from(act);
866                         }
867
868                         /* Include at most one act per-thread that "happens before" curr */
869                         if (act->happens_before(curr)) {
870                                 initialized = true;
871                                 break;
872                         }
873                 }
874         }
875
876         if (!initialized) {
877                 /** @todo Need a more informative way of reporting errors. */
878                 printf("ERROR: may read from uninitialized atomic\n");
879         }
880
881         if (DBG_ENABLED() || !initialized) {
882                 printf("Reached read action:\n");
883                 curr->print();
884                 printf("Printing may_read_from\n");
885                 curr->get_node()->print_may_read_from();
886                 printf("End printing may_read_from\n");
887         }
888
889         ASSERT(initialized);
890 }
891
892 static void print_list(action_list_t *list)
893 {
894         action_list_t::iterator it;
895
896         printf("---------------------------------------------------------------------\n");
897         printf("Trace:\n");
898
899         for (it = list->begin(); it != list->end(); it++) {
900                 (*it)->print();
901         }
902         printf("---------------------------------------------------------------------\n");
903 }
904
905 void ModelChecker::print_summary()
906 {
907         printf("\n");
908         printf("Number of executions: %d\n", num_executions);
909         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
910
911         scheduler->print();
912
913         if (!isfinalfeasible())
914                 printf("INFEASIBLE EXECUTION!\n");
915         print_list(action_trace);
916         printf("\n");
917 }
918
919 /**
920  * Add a Thread to the system for the first time. Should only be called once
921  * per thread.
922  * @param t The Thread to add
923  */
924 void ModelChecker::add_thread(Thread *t)
925 {
926         thread_map->put(id_to_int(t->get_id()), t);
927         scheduler->add_thread(t);
928 }
929
930 void ModelChecker::remove_thread(Thread *t)
931 {
932         scheduler->remove_thread(t);
933 }
934
935 /**
936  * Switch from a user-context to the "master thread" context (a.k.a. system
937  * context). This switch is made with the intention of exploring a particular
938  * model-checking action (described by a ModelAction object). Must be called
939  * from a user-thread context.
940  * @param act The current action that will be explored. May be NULL, although
941  * there is little reason to switch to the model-checker without an action to
942  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
943  * yield control without performing any progress; see thrd_join()).
944  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
945  */
946 int ModelChecker::switch_to_master(ModelAction *act)
947 {
948         DBG();
949         Thread *old = thread_current();
950         set_current_action(act);
951         old->set_state(THREAD_READY);
952         return Thread::swap(old, &system_context);
953 }
954
955 /**
956  * Takes the next step in the execution, if possible.
957  * @return Returns true (success) if a step was taken and false otherwise.
958  */
959 bool ModelChecker::take_step() {
960         Thread *curr, *next;
961
962         curr = thread_current();
963         if (curr) {
964                 if (curr->get_state() == THREAD_READY) {
965                         check_current_action();
966                         scheduler->add_thread(curr);
967                 } else if (curr->get_state() == THREAD_RUNNING) {
968                         /* Stopped while running; i.e., completed */
969                         curr->complete();
970                 } else {
971                         ASSERT(false);
972                 }
973         }
974         next = scheduler->next_thread(nextThread);
975
976         /* Infeasible -> don't take any more steps */
977         if (!isfeasible())
978                 return false;
979
980         if (next)
981                 next->set_state(THREAD_RUNNING);
982         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
983
984         /* next == NULL -> don't take any more steps */
985         if (!next)
986                 return false;
987         /* Return false only if swap fails with an error */
988         return (Thread::swap(&system_context, next) == 0);
989 }
990
991 /** Runs the current execution until threre are no more steps to take. */
992 void ModelChecker::finish_execution() {
993         DBG();
994
995         while (take_step());
996 }