model: more restructuring of read/write processing
[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 second_part_of_rmw is boolean that is true is this is the second action of a rmw.
266  * @return True if processing this read updates the mo_graph.
267  */
268 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
269 {
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                 get_thread(curr)->set_return_value(value);
304                 return updated;
305         }
306 }
307
308 /**
309  * Process a write ModelAction
310  * @param curr The ModelAction to process
311  * @return True if the mo_graph was updated or promises were resolved
312  */
313 bool ModelChecker::process_write(ModelAction *curr)
314 {
315         bool updated_mod_order = w_modification_order(curr);
316         bool updated_promises = resolve_promises(curr);
317
318         if (promises->size() == 0) {
319                 for (unsigned int i = 0; i<futurevalues->size(); i++) {
320                         struct PendingFutureValue pfv = (*futurevalues)[i];
321                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
322                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
323                                 priv->next_backtrack = pfv.act;
324                 }
325                 futurevalues->resize(0);
326         }
327
328         mo_graph->commitChanges();
329         get_thread(curr)->set_return_value(VALUE_NONE);
330         return updated_mod_order || updated_promises;
331 }
332
333 /**
334  * This is the heart of the model checker routine. It performs model-checking
335  * actions corresponding to a given "current action." Among other processes, it
336  * calculates reads-from relationships, updates synchronization clock vectors,
337  * forms a memory_order constraints graph, and handles replay/backtrack
338  * execution when running permutations of previously-observed executions.
339  *
340  * @param curr The current action to process
341  * @return The next Thread that must be executed. May be NULL if ModelChecker
342  * makes no choice (e.g., according to replay execution, combining RMW actions,
343  * etc.)
344  */
345 Thread * ModelChecker::check_current_action(ModelAction *curr)
346 {
347         bool second_part_of_rmw = false;
348
349         ASSERT(curr);
350
351         if (curr->is_rmwc() || curr->is_rmw()) {
352                 ModelAction *tmp = process_rmw(curr);
353                 second_part_of_rmw = true;
354                 delete curr;
355                 curr = tmp;
356                 compute_promises(curr);
357         } else {
358                 ModelAction *tmp = node_stack->explore_action(curr);
359                 if (tmp) {
360                         /* Discard duplicate ModelAction; use action from NodeStack */
361                         /* First restore type and order in case of RMW operation */
362                         if (curr->is_rmwr())
363                                 tmp->copy_typeandorder(curr);
364
365                         /* If we have diverged, we need to reset the clock vector. */
366                         if (diverge == NULL)
367                                 tmp->create_cv(get_parent_action(tmp->get_tid()));
368
369                         delete curr;
370                         curr = tmp;
371                 } else {
372                         /*
373                          * Perform one-time actions when pushing new ModelAction onto
374                          * NodeStack
375                          */
376                         curr->create_cv(get_parent_action(curr->get_tid()));
377                         /* Build may_read_from set */
378                         if (curr->is_read())
379                                 build_reads_from_past(curr);
380                         if (curr->is_write())
381                                 compute_promises(curr);
382                 }
383         }
384
385         /* Thread specific actions */
386         switch (curr->get_type()) {
387         case THREAD_CREATE: {
388                 Thread *th = (Thread *)curr->get_location();
389                 th->set_creation(curr);
390                 break;
391         }
392         case THREAD_JOIN: {
393                 Thread *waiting, *blocking;
394                 waiting = get_thread(curr);
395                 blocking = (Thread *)curr->get_location();
396                 if (!blocking->is_complete()) {
397                         blocking->push_wait_list(curr);
398                         scheduler->sleep(waiting);
399                 }
400                 break;
401         }
402         case THREAD_FINISH: {
403                 Thread *th = get_thread(curr);
404                 while (!th->wait_list_empty()) {
405                         ModelAction *act = th->pop_wait_list();
406                         Thread *wake = get_thread(act);
407                         scheduler->wake(wake);
408                 }
409                 th->complete();
410                 break;
411         }
412         case THREAD_START: {
413                 check_promises(NULL, curr->get_cv());
414                 break;
415         }
416         default:
417                 break;
418         }
419
420         bool updated = false;
421
422         if (curr->is_read() && process_read(curr, second_part_of_rmw))
423                 updated = true;
424
425         if (curr->is_write() && process_write(curr))
426                 updated = true;
427
428         if (updated)
429                 resolve_release_sequences(curr->get_location());
430
431         /* Add action to list.  */
432         if (!second_part_of_rmw)
433                 add_action_to_lists(curr);
434
435         check_curr_backtracking(curr);
436
437         set_backtracking(curr);
438
439         return get_next_thread(curr);
440 }
441
442 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
443         Node *currnode = curr->get_node();
444         Node *parnode = currnode->get_parent();
445
446         if ((!parnode->backtrack_empty() ||
447                          !currnode->read_from_empty() ||
448                          !currnode->future_value_empty() ||
449                          !currnode->promise_empty())
450                         && (!priv->next_backtrack ||
451                                         *curr > *priv->next_backtrack)) {
452                 priv->next_backtrack = curr;
453         }
454 }
455
456 bool ModelChecker::promises_expired() {
457         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
458                 Promise *promise = (*promises)[promise_index];
459                 if (promise->get_expiration()<priv->used_sequence_numbers) {
460                         return true;
461                 }
462         }
463         return false;
464 }
465
466 /** @returns whether the current partial trace must be a prefix of a
467  * feasible trace. */
468 bool ModelChecker::isfeasibleprefix() {
469         return promises->size() == 0 && *lazy_sync_size == 0;
470 }
471
472 /** @returns whether the current partial trace is feasible. */
473 bool ModelChecker::isfeasible() {
474         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
475 }
476
477 /** @returns whether the current partial trace is feasible other than
478  * multiple RMW reading from the same store. */
479 bool ModelChecker::isfeasibleotherthanRMW() {
480         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
481 }
482
483 /** Returns whether the current completed trace is feasible. */
484 bool ModelChecker::isfinalfeasible() {
485         return isfeasible() && promises->size() == 0;
486 }
487
488 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
489 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
490         int tid = id_to_int(act->get_tid());
491         ModelAction *lastread = get_last_action(tid);
492         lastread->process_rmw(act);
493         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
494                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
495                 mo_graph->commitChanges();
496         }
497         return lastread;
498 }
499
500 /**
501  * Checks whether a thread has read from the same write for too many times
502  * without seeing the effects of a later write.
503  *
504  * Basic idea:
505  * 1) there must a different write that we could read from that would satisfy the modification order,
506  * 2) we must have read from the same value in excess of maxreads times, and
507  * 3) that other write must have been in the reads_from set for maxreads times.
508  *
509  * If so, we decide that the execution is no longer feasible.
510  */
511 void ModelChecker::check_recency(ModelAction *curr, bool already_added) {
512         if (params.maxreads != 0) {
513                 if (curr->get_node()->get_read_from_size() <= 1)
514                         return;
515
516                 //Must make sure that execution is currently feasible...  We could
517                 //accidentally clear by rolling back
518                 if (!isfeasible())
519                         return;
520
521                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
522                 int tid = id_to_int(curr->get_tid());
523
524                 /* Skip checks */
525                 if ((int)thrd_lists->size() <= tid)
526                         return;
527
528                 action_list_t *list = &(*thrd_lists)[tid];
529
530                 action_list_t::reverse_iterator rit = list->rbegin();
531                 /* Skip past curr */
532                 if (already_added) {
533                         for (; (*rit) != curr; rit++)
534                                 ;
535                         /* go past curr now */
536                         rit++;
537                 }
538
539                 action_list_t::reverse_iterator ritcopy = rit;
540                 //See if we have enough reads from the same value
541                 int count = 0;
542                 for (; count < params.maxreads; rit++,count++) {
543                         if (rit==list->rend())
544                                 return;
545                         ModelAction *act = *rit;
546                         if (!act->is_read())
547                                 return;
548                         if (act->get_reads_from() != curr->get_reads_from())
549                                 return;
550                         if (act->get_node()->get_read_from_size() <= 1)
551                                 return;
552                 }
553
554                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
555                         //Get write
556                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
557                         //Need a different write
558                         if (write==curr->get_reads_from())
559                                 continue;
560
561                         /* Test to see whether this is a feasible write to read from*/
562                         mo_graph->startChanges();
563                         r_modification_order(curr, write);
564                         bool feasiblereadfrom = isfeasible();
565                         mo_graph->rollbackChanges();
566
567                         if (!feasiblereadfrom)
568                                 continue;
569                         rit = ritcopy;
570
571                         bool feasiblewrite = true;
572                         //new we need to see if this write works for everyone
573
574                         for (int loop = count; loop>0; loop--,rit++) {
575                                 ModelAction *act=*rit;
576                                 bool foundvalue = false;
577                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
578                                         if (act->get_node()->get_read_from_at(i)==write) {
579                                                 foundvalue = true;
580                                                 break;
581                                         }
582                                 }
583                                 if (!foundvalue) {
584                                         feasiblewrite = false;
585                                         break;
586                                 }
587                         }
588                         if (feasiblewrite) {
589                                 too_many_reads = true;
590                                 return;
591                         }
592                 }
593         }
594 }
595
596 /**
597  * Updates the mo_graph with the constraints imposed from the current read.
598  * @param curr The current action. Must be a read.
599  * @param rf The action that curr reads from. Must be a write.
600  * @return True if modification order edges were added; false otherwise
601  */
602 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
603 {
604         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
605         unsigned int i;
606         bool added = false;
607         ASSERT(curr->is_read());
608
609         /* Iterate over all threads */
610         for (i = 0; i < thrd_lists->size(); i++) {
611                 /* Iterate over actions in thread, starting from most recent */
612                 action_list_t *list = &(*thrd_lists)[i];
613                 action_list_t::reverse_iterator rit;
614                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
615                         ModelAction *act = *rit;
616
617                         /* Include at most one act per-thread that "happens before" curr */
618                         if (act->happens_before(curr)) {
619                                 if (act->is_write()) {
620                                         if (rf != act && act != curr) {
621                                                 mo_graph->addEdge(act, rf);
622                                                 added = true;
623                                         }
624                                 } else {
625                                         const ModelAction *prevreadfrom = act->get_reads_from();
626                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
627                                                 mo_graph->addEdge(prevreadfrom, rf);
628                                                 added = true;
629                                         }
630                                 }
631
632                                 break;
633                         }
634                 }
635         }
636
637         return added;
638 }
639
640 /** Updates the mo_graph with the constraints imposed from the current read. */
641 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
642 {
643         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
644         unsigned int i;
645         ASSERT(curr->is_read());
646
647         /* Iterate over all threads */
648         for (i = 0; i < thrd_lists->size(); i++) {
649                 /* Iterate over actions in thread, starting from most recent */
650                 action_list_t *list = &(*thrd_lists)[i];
651                 action_list_t::reverse_iterator rit;
652                 ModelAction *lastact = NULL;
653
654                 /* Find last action that happens after curr */
655                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
656                         ModelAction *act = *rit;
657                         if (curr->happens_before(act)) {
658                                 lastact = act;
659                         } else
660                                 break;
661                 }
662
663                         /* Include at most one act per-thread that "happens before" curr */
664                 if (lastact != NULL) {
665                         if (lastact->is_read()) {
666                                 const ModelAction *postreadfrom = lastact->get_reads_from();
667                                 if (postreadfrom != NULL&&rf != postreadfrom)
668                                         mo_graph->addEdge(rf, postreadfrom);
669                         } else if (rf != lastact) {
670                                 mo_graph->addEdge(rf, lastact);
671                         }
672                         break;
673                 }
674         }
675 }
676
677 /**
678  * Updates the mo_graph with the constraints imposed from the current write.
679  * @param curr The current action. Must be a write.
680  * @return True if modification order edges were added; false otherwise
681  */
682 bool ModelChecker::w_modification_order(ModelAction *curr)
683 {
684         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
685         unsigned int i;
686         bool added = false;
687         ASSERT(curr->is_write());
688
689         if (curr->is_seqcst()) {
690                 /* We have to at least see the last sequentially consistent write,
691                          so we are initialized. */
692                 ModelAction *last_seq_cst = get_last_seq_cst(curr->get_location());
693                 if (last_seq_cst != NULL) {
694                         mo_graph->addEdge(last_seq_cst, curr);
695                         added = true;
696                 }
697         }
698
699         /* Iterate over all threads */
700         for (i = 0; i < thrd_lists->size(); i++) {
701                 /* Iterate over actions in thread, starting from most recent */
702                 action_list_t *list = &(*thrd_lists)[i];
703                 action_list_t::reverse_iterator rit;
704                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
705                         ModelAction *act = *rit;
706
707                         /* Include at most one act per-thread that "happens before" curr */
708                         if (act->happens_before(curr)) {
709                                 /*
710                                  * Note: if act is RMW, just add edge:
711                                  *   act --mo--> curr
712                                  * The following edge should be handled elsewhere:
713                                  *   readfrom(act) --mo--> act
714                                  */
715                                 if (act->is_write()) {
716                                         //RMW shouldn't have an edge to themselves
717                                         if (act!=curr)
718                                                 mo_graph->addEdge(act, curr);
719                                 } else if (act->is_read() && act->get_reads_from() != NULL)
720                                         mo_graph->addEdge(act->get_reads_from(), curr);
721                                 added = true;
722                                 break;
723                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
724                                                      !act->same_thread(curr)) {
725                                 /* We have an action that:
726                                    (1) did not happen before us
727                                    (2) is a read and we are a write
728                                    (3) cannot synchronize with us
729                                    (4) is in a different thread
730                                    =>
731                                    that read could potentially read from our write.
732                                  */
733                                 if (thin_air_constraint_may_allow(curr, act)) {
734                                         if (isfeasible() ||
735                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
736                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
737                                                 futurevalues->push_back(pfv);
738                                         }
739                                 }
740                         }
741                 }
742         }
743
744         return added;
745 }
746
747 /** Arbitrary reads from the future are not allowed.  Section 29.3
748  * part 9 places some constraints.  This method checks one result of constraint
749  * constraint.  Others require compiler support. */
750
751 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
752         if (!writer->is_rmw())
753                 return true;
754
755         if (!reader->is_rmw())
756                 return true;
757
758         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
759                 if (search==reader)
760                         return false;
761                 if (search->get_tid() == reader->get_tid() &&
762                                 search->happens_before(reader))
763                         break;
764         }
765
766         return true;
767 }
768
769 /**
770  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
771  * The ModelAction under consideration is expected to be taking part in
772  * release/acquire synchronization as an object of the "reads from" relation.
773  * Note that this can only provide release sequence support for RMW chains
774  * which do not read from the future, as those actions cannot be traced until
775  * their "promise" is fulfilled. Similarly, we may not even establish the
776  * presence of a release sequence with certainty, as some modification order
777  * constraints may be decided further in the future. Thus, this function
778  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
779  * and a boolean representing certainty.
780  *
781  * @todo Finish lazy updating, when promises are fulfilled in the future
782  * @param rf The action that might be part of a release sequence. Must be a
783  * write.
784  * @param release_heads A pass-by-reference style return parameter.  After
785  * execution of this function, release_heads will contain the heads of all the
786  * relevant release sequences, if any exists
787  * @return true, if the ModelChecker is certain that release_heads is complete;
788  * false otherwise
789  */
790 bool ModelChecker::release_seq_head(const ModelAction *rf,
791                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads) const
792 {
793         if (!rf) {
794                 /* read from future: need to settle this later */
795                 return false; /* incomplete */
796         }
797
798         ASSERT(rf->is_write());
799
800         if (rf->is_release())
801                 release_heads->push_back(rf);
802         if (rf->is_rmw()) {
803                 /* We need a RMW action that is both an acquire and release to stop */
804                 /** @todo Need to be smarter here...  In the linux lock
805                  * example, this will run to the beginning of the program for
806                  * every acquire. */
807                 if (rf->is_acquire() && rf->is_release())
808                         return true; /* complete */
809                 return release_seq_head(rf->get_reads_from(), release_heads);
810         }
811         if (rf->is_release())
812                 return true; /* complete */
813
814         /* else relaxed write; check modification order for contiguous subsequence
815          * -> rf must be same thread as release */
816         int tid = id_to_int(rf->get_tid());
817         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
818         action_list_t *list = &(*thrd_lists)[tid];
819         action_list_t::const_reverse_iterator rit;
820
821         /* Find rf in the thread list */
822         rit = std::find(list->rbegin(), list->rend(), rf);
823         ASSERT(rit != list->rend());
824
825         /* Find the last write/release */
826         for (; rit != list->rend(); rit++)
827                 if ((*rit)->is_release())
828                         break;
829         if (rit == list->rend()) {
830                 /* No write-release in this thread */
831                 return true; /* complete */
832         }
833         ModelAction *release = *rit;
834
835         ASSERT(rf->same_thread(release));
836
837         bool certain = true;
838         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
839                 if (id_to_int(rf->get_tid()) == (int)i)
840                         continue;
841                 list = &(*thrd_lists)[i];
842
843                 /* Can we ensure no future writes from this thread may break
844                  * the release seq? */
845                 bool future_ordered = false;
846
847                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
848                         const ModelAction *act = *rit;
849                         if (!act->is_write())
850                                 continue;
851                         /* Reach synchronization -> this thread is complete */
852                         if (act->happens_before(release))
853                                 break;
854                         if (rf->happens_before(act)) {
855                                 future_ordered = true;
856                                 continue;
857                         }
858
859                         /* Check modification order */
860                         if (mo_graph->checkReachable(rf, act)) {
861                                 /* rf --mo--> act */
862                                 future_ordered = true;
863                                 continue;
864                         }
865                         if (mo_graph->checkReachable(act, release))
866                                 /* act --mo--> release */
867                                 break;
868                         if (mo_graph->checkReachable(release, act) &&
869                                       mo_graph->checkReachable(act, rf)) {
870                                 /* release --mo-> act --mo--> rf */
871                                 return true; /* complete */
872                         }
873                         certain = false;
874                 }
875                 if (!future_ordered)
876                         return false; /* This thread is uncertain */
877         }
878
879         if (certain)
880                 release_heads->push_back(release);
881         return certain;
882 }
883
884 /**
885  * A public interface for getting the release sequence head(s) with which a
886  * given ModelAction must synchronize. This function only returns a non-empty
887  * result when it can locate a release sequence head with certainty. Otherwise,
888  * it may mark the internal state of the ModelChecker so that it will handle
889  * the release sequence at a later time, causing @a act to update its
890  * synchronization at some later point in execution.
891  * @param act The 'acquire' action that may read from a release sequence
892  * @param release_heads A pass-by-reference return parameter. Will be filled
893  * with the head(s) of the release sequence(s), if they exists with certainty.
894  * @see ModelChecker::release_seq_head
895  */
896 void ModelChecker::get_release_seq_heads(ModelAction *act,
897                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > *release_heads)
898 {
899         const ModelAction *rf = act->get_reads_from();
900         bool complete;
901         complete = release_seq_head(rf, release_heads);
902         if (!complete) {
903                 /* add act to 'lazy checking' list */
904                 std::list<ModelAction *> *list;
905                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
906                 list->push_back(act);
907                 (*lazy_sync_size)++;
908         }
909 }
910
911 /**
912  * Attempt to resolve all stashed operations that might synchronize with a
913  * release sequence for a given location. This implements the "lazy" portion of
914  * determining whether or not a release sequence was contiguous, since not all
915  * modification order information is present at the time an action occurs.
916  *
917  * @param location The location/object that should be checked for release
918  * sequence resolutions
919  * @return True if any updates occurred (new synchronization, new mo_graph edges)
920  */
921 bool ModelChecker::resolve_release_sequences(void *location)
922 {
923         std::list<ModelAction *> *list;
924         list = lazy_sync_with_release->getptr(location);
925         if (!list)
926                 return false;
927
928         bool updated = false;
929         std::list<ModelAction *>::iterator it = list->begin();
930         while (it != list->end()) {
931                 ModelAction *act = *it;
932                 const ModelAction *rf = act->get_reads_from();
933                 std::vector< const ModelAction *, MyAlloc<const ModelAction *> > release_heads;
934                 bool complete;
935                 complete = release_seq_head(rf, &release_heads);
936                 for (unsigned int i = 0; i < release_heads.size(); i++) {
937                         if (!act->has_synchronized_with(release_heads[i])) {
938                                 updated = true;
939                                 act->synchronize_with(release_heads[i]);
940                         }
941                 }
942
943                 if (updated) {
944                         /* propagate synchronization to later actions */
945                         action_list_t::reverse_iterator it = action_trace->rbegin();
946                         while ((*it) != act) {
947                                 ModelAction *propagate = *it;
948                                 if (act->happens_before(propagate))
949                                         /** @todo new mo_graph edges along with
950                                          * this synchronization? */
951                                         propagate->synchronize_with(act);
952                         }
953                 }
954                 if (complete) {
955                         it = list->erase(it);
956                         (*lazy_sync_size)--;
957                 } else
958                         it++;
959         }
960
961         // If we resolved promises or data races, see if we have realized a data race.
962         if (checkDataRaces()) {
963                 set_assert();
964         }
965
966         return updated;
967 }
968
969 /**
970  * Performs various bookkeeping operations for the current ModelAction. For
971  * instance, adds action to the per-object, per-thread action vector and to the
972  * action trace list of all thread actions.
973  *
974  * @param act is the ModelAction to add.
975  */
976 void ModelChecker::add_action_to_lists(ModelAction *act)
977 {
978         int tid = id_to_int(act->get_tid());
979         action_trace->push_back(act);
980
981         obj_map->get_safe_ptr(act->get_location())->push_back(act);
982
983         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
984         if (tid >= (int)vec->size())
985                 vec->resize(priv->next_thread_id);
986         (*vec)[tid].push_back(act);
987
988         if ((int)thrd_last_action->size() <= tid)
989                 thrd_last_action->resize(get_num_threads());
990         (*thrd_last_action)[tid] = act;
991 }
992
993 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
994 {
995         int nthreads = get_num_threads();
996         if ((int)thrd_last_action->size() < nthreads)
997                 thrd_last_action->resize(nthreads);
998         return (*thrd_last_action)[id_to_int(tid)];
999 }
1000
1001 /**
1002  * Gets the last memory_order_seq_cst action (in the total global sequence)
1003  * performed on a particular object (i.e., memory location).
1004  * @param location The object location to check
1005  * @return The last seq_cst action performed
1006  */
1007 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
1008 {
1009         action_list_t *list = obj_map->get_safe_ptr(location);
1010         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1011         action_list_t::reverse_iterator rit;
1012         for (rit = list->rbegin(); rit != list->rend(); rit++)
1013                 if ((*rit)->is_write() && (*rit)->is_seqcst())
1014                         return *rit;
1015         return NULL;
1016 }
1017
1018 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1019 {
1020         ModelAction *parent = get_last_action(tid);
1021         if (!parent)
1022                 parent = get_thread(tid)->get_creation();
1023         return parent;
1024 }
1025
1026 /**
1027  * Returns the clock vector for a given thread.
1028  * @param tid The thread whose clock vector we want
1029  * @return Desired clock vector
1030  */
1031 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1032 {
1033         return get_parent_action(tid)->get_cv();
1034 }
1035
1036 /**
1037  * Resolve a set of Promises with a current write. The set is provided in the
1038  * Node corresponding to @a write.
1039  * @param write The ModelAction that is fulfilling Promises
1040  * @return True if promises were resolved; false otherwise
1041  */
1042 bool ModelChecker::resolve_promises(ModelAction *write)
1043 {
1044         bool resolved = false;
1045
1046         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1047                 Promise *promise = (*promises)[promise_index];
1048                 if (write->get_node()->get_promise(i)) {
1049                         ModelAction *read = promise->get_action();
1050                         read->read_from(write);
1051                         if (read->is_rmw()) {
1052                                 mo_graph->addRMWEdge(write, read);
1053                         }
1054                         r_modification_order(read, write);
1055                         post_r_modification_order(read, write);
1056                         promises->erase(promises->begin() + promise_index);
1057                         resolved = true;
1058                 } else
1059                         promise_index++;
1060         }
1061         return resolved;
1062 }
1063
1064 /**
1065  * Compute the set of promises that could potentially be satisfied by this
1066  * action. Note that the set computation actually appears in the Node, not in
1067  * ModelChecker.
1068  * @param curr The ModelAction that may satisfy promises
1069  */
1070 void ModelChecker::compute_promises(ModelAction *curr)
1071 {
1072         for (unsigned int i = 0; i < promises->size(); i++) {
1073                 Promise *promise = (*promises)[i];
1074                 const ModelAction *act = promise->get_action();
1075                 if (!act->happens_before(curr) &&
1076                                 act->is_read() &&
1077                                 !act->is_synchronizing(curr) &&
1078                                 !act->same_thread(curr) &&
1079                                 promise->get_value() == curr->get_value()) {
1080                         curr->get_node()->set_promise(i);
1081                 }
1082         }
1083 }
1084
1085 /** Checks promises in response to change in ClockVector Threads. */
1086 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1087 {
1088         for (unsigned int i = 0; i < promises->size(); i++) {
1089                 Promise *promise = (*promises)[i];
1090                 const ModelAction *act = promise->get_action();
1091                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1092                                 merge_cv->synchronized_since(act)) {
1093                         //This thread is no longer able to send values back to satisfy the promise
1094                         int num_synchronized_threads = promise->increment_threads();
1095                         if (num_synchronized_threads == get_num_threads()) {
1096                                 //Promise has failed
1097                                 failed_promise = true;
1098                                 return;
1099                         }
1100                 }
1101         }
1102 }
1103
1104 /**
1105  * Build up an initial set of all past writes that this 'read' action may read
1106  * from. This set is determined by the clock vector's "happens before"
1107  * relationship.
1108  * @param curr is the current ModelAction that we are exploring; it must be a
1109  * 'read' operation.
1110  */
1111 void ModelChecker::build_reads_from_past(ModelAction *curr)
1112 {
1113         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1114         unsigned int i;
1115         ASSERT(curr->is_read());
1116
1117         ModelAction *last_seq_cst = NULL;
1118
1119         /* Track whether this object has been initialized */
1120         bool initialized = false;
1121
1122         if (curr->is_seqcst()) {
1123                 last_seq_cst = get_last_seq_cst(curr->get_location());
1124                 /* We have to at least see the last sequentially consistent write,
1125                          so we are initialized. */
1126                 if (last_seq_cst != NULL)
1127                         initialized = true;
1128         }
1129
1130         /* Iterate over all threads */
1131         for (i = 0; i < thrd_lists->size(); i++) {
1132                 /* Iterate over actions in thread, starting from most recent */
1133                 action_list_t *list = &(*thrd_lists)[i];
1134                 action_list_t::reverse_iterator rit;
1135                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1136                         ModelAction *act = *rit;
1137
1138                         /* Only consider 'write' actions */
1139                         if (!act->is_write())
1140                                 continue;
1141
1142                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1143                         if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1144                                 DEBUG("Adding action to may_read_from:\n");
1145                                 if (DBG_ENABLED()) {
1146                                         act->print();
1147                                         curr->print();
1148                                 }
1149                                 curr->get_node()->add_read_from(act);
1150                         }
1151
1152                         /* Include at most one act per-thread that "happens before" curr */
1153                         if (act->happens_before(curr)) {
1154                                 initialized = true;
1155                                 break;
1156                         }
1157                 }
1158         }
1159
1160         if (!initialized) {
1161                 /** @todo Need a more informative way of reporting errors. */
1162                 printf("ERROR: may read from uninitialized atomic\n");
1163         }
1164
1165         if (DBG_ENABLED() || !initialized) {
1166                 printf("Reached read action:\n");
1167                 curr->print();
1168                 printf("Printing may_read_from\n");
1169                 curr->get_node()->print_may_read_from();
1170                 printf("End printing may_read_from\n");
1171         }
1172
1173         ASSERT(initialized);
1174 }
1175
1176 static void print_list(action_list_t *list)
1177 {
1178         action_list_t::iterator it;
1179
1180         printf("---------------------------------------------------------------------\n");
1181         printf("Trace:\n");
1182
1183         for (it = list->begin(); it != list->end(); it++) {
1184                 (*it)->print();
1185         }
1186         printf("---------------------------------------------------------------------\n");
1187 }
1188
1189 void ModelChecker::print_summary()
1190 {
1191         printf("\n");
1192         printf("Number of executions: %d\n", num_executions);
1193         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1194
1195         scheduler->print();
1196
1197         if (!isfinalfeasible())
1198                 printf("INFEASIBLE EXECUTION!\n");
1199         print_list(action_trace);
1200         printf("\n");
1201 }
1202
1203 /**
1204  * Add a Thread to the system for the first time. Should only be called once
1205  * per thread.
1206  * @param t The Thread to add
1207  */
1208 void ModelChecker::add_thread(Thread *t)
1209 {
1210         thread_map->put(id_to_int(t->get_id()), t);
1211         scheduler->add_thread(t);
1212 }
1213
1214 void ModelChecker::remove_thread(Thread *t)
1215 {
1216         scheduler->remove_thread(t);
1217 }
1218
1219 /**
1220  * Switch from a user-context to the "master thread" context (a.k.a. system
1221  * context). This switch is made with the intention of exploring a particular
1222  * model-checking action (described by a ModelAction object). Must be called
1223  * from a user-thread context.
1224  * @param act The current action that will be explored. Must not be NULL.
1225  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1226  */
1227 int ModelChecker::switch_to_master(ModelAction *act)
1228 {
1229         DBG();
1230         Thread *old = thread_current();
1231         set_current_action(act);
1232         old->set_state(THREAD_READY);
1233         return Thread::swap(old, &system_context);
1234 }
1235
1236 /**
1237  * Takes the next step in the execution, if possible.
1238  * @return Returns true (success) if a step was taken and false otherwise.
1239  */
1240 bool ModelChecker::take_step() {
1241         Thread *curr, *next;
1242
1243         if (has_asserted())
1244                 return false;
1245
1246         curr = thread_current();
1247         if (curr) {
1248                 if (curr->get_state() == THREAD_READY) {
1249                         ASSERT(priv->current_action);
1250
1251                         priv->nextThread = check_current_action(priv->current_action);
1252                         priv->current_action = NULL;
1253                         if (!curr->is_blocked() && !curr->is_complete())
1254                                 scheduler->add_thread(curr);
1255                 } else {
1256                         ASSERT(false);
1257                 }
1258         }
1259         next = scheduler->next_thread(priv->nextThread);
1260
1261         /* Infeasible -> don't take any more steps */
1262         if (!isfeasible())
1263                 return false;
1264
1265         if (next)
1266                 next->set_state(THREAD_RUNNING);
1267         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1268
1269         /* next == NULL -> don't take any more steps */
1270         if (!next)
1271                 return false;
1272         /* Return false only if swap fails with an error */
1273         return (Thread::swap(&system_context, next) == 0);
1274 }
1275
1276 /** Runs the current execution until threre are no more steps to take. */
1277 void ModelChecker::finish_execution() {
1278         DBG();
1279
1280         while (take_step());
1281 }