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