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