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