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