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