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