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