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