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