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