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