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