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