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