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