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