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