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