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