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