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