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