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