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