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