changes
[c11tester.git] / model.cc
1 #include <stdio.h>
2
3 #include "model.h"
4 #include "action.h"
5 #include "nodestack.h"
6 #include "schedule.h"
7 #include "snapshot-interface.h"
8 #include "common.h"
9 #include "clockvector.h"
10 #include "cyclegraph.h"
11 #include "promise.h"
12
13 #define INITIAL_THREAD_ID       0
14
15 ModelChecker *model;
16
17 /** @brief Constructor */
18 ModelChecker::ModelChecker()
19         :
20         /* Initialize default scheduler */
21         scheduler(new Scheduler()),
22         /* First thread created will have id INITIAL_THREAD_ID */
23         next_thread_id(INITIAL_THREAD_ID),
24         used_sequence_numbers(0),
25
26         num_executions(0),
27         current_action(NULL),
28         diverge(NULL),
29         nextThread(THREAD_ID_T_NONE),
30         action_trace(new action_list_t()),
31         thread_map(new HashTable<int, Thread *, int>()),
32         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
34         promises(new std::vector<Promise *>()),
35         thrd_last_action(new std::vector<ModelAction *>(1)),
36         node_stack(new NodeStack()),
37         next_backtrack(NULL),
38         cyclegraph(new CycleGraph()),
39         failed_promise(false)
40 {
41 }
42
43 /** @brief Destructor */
44 ModelChecker::~ModelChecker()
45 {
46         /*      std::map<int, Thread *>::iterator it;
47         for (it = thread_map->begin(); it != thread_map->end(); it++)
48         delete (*it).second;*/
49         delete thread_map;
50
51         delete obj_thrd_map;
52         delete obj_map;
53         delete action_trace;
54         delete thrd_last_action;
55         delete node_stack;
56         delete scheduler;
57         delete cyclegraph;
58 }
59
60 /**
61  * Restores user program to initial state and resets all model-checker data
62  * structures.
63  */
64 void ModelChecker::reset_to_initial_state()
65 {
66         DEBUG("+++ Resetting to initial state +++\n");
67         node_stack->reset_execution();
68         current_action = NULL;
69         next_thread_id = INITIAL_THREAD_ID;
70         used_sequence_numbers = 0;
71         nextThread = 0;
72         next_backtrack = NULL;
73         failed_promise = false;
74         snapshotObject->backTrackBeforeStep(0);
75 }
76
77 /** @returns a thread ID for a new Thread */
78 thread_id_t ModelChecker::get_next_id()
79 {
80         return next_thread_id++;
81 }
82
83 /** @returns the number of user threads created during this execution */
84 int ModelChecker::get_num_threads()
85 {
86         return next_thread_id;
87 }
88
89 /** @returns a sequence number for a new ModelAction */
90 modelclock_t ModelChecker::get_next_seq_num()
91 {
92         return ++used_sequence_numbers;
93 }
94
95 /**
96  * Performs the "scheduling" for the model-checker. That is, it checks if the
97  * model-checker has selected a "next thread to run" and returns it, if
98  * available. This function should be called from the Scheduler routine, where
99  * the Scheduler falls back to a default scheduling routine if needed.
100  *
101  * @return The next thread chosen by the model-checker. If the model-checker
102  * makes no selection, retuns NULL.
103  */
104 Thread * ModelChecker::schedule_next_thread()
105 {
106         Thread *t;
107         if (nextThread == THREAD_ID_T_NONE)
108                 return NULL;
109         t = thread_map->get(id_to_int(nextThread));
110
111         ASSERT(t != NULL);
112
113         return t;
114 }
115
116 /**
117  * Choose the next thread in the replay sequence.
118  *
119  * If the replay sequence has reached the 'diverge' point, returns a thread
120  * from the backtracking set. Otherwise, simply returns the next thread in the
121  * sequence that is being replayed.
122  */
123 thread_id_t ModelChecker::get_next_replay_thread()
124 {
125         thread_id_t tid;
126
127         /* Have we completed exploring the preselected path? */
128         if (diverge == NULL)
129                 return THREAD_ID_T_NONE;
130
131         /* Else, we are trying to replay an execution */
132         ModelAction * next = node_stack->get_next()->get_action();
133
134         if (next == diverge) {
135                 Node *nextnode = next->get_node();
136                 /* Reached divergence point */
137                 if (nextnode->increment_read_from()) {
138                         /* The next node will read from a different value. */
139                         tid = next->get_tid();
140                         node_stack->pop_restofstack(2);
141                 } else if (nextnode->increment_future_values()) {
142                         /* The next node will try to read from a different future value. */
143                         tid = next->get_tid();
144                         node_stack->pop_restofstack(2);
145                 } else {
146                         /* Make a different thread execute for next step */
147                         Node *node = nextnode->get_parent();
148                         tid = node->get_next_backtrack();
149                         node_stack->pop_restofstack(1);
150                 }
151                 DEBUG("*** Divergence point ***\n");
152                 diverge = NULL;
153         } else {
154                 tid = next->get_tid();
155         }
156         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
157         return tid;
158 }
159
160 /**
161  * Queries the model-checker for more executions to explore and, if one
162  * exists, resets the model-checker state to execute a new execution.
163  *
164  * @return If there are more executions to explore, return true. Otherwise,
165  * return false.
166  */
167 bool ModelChecker::next_execution()
168 {
169         DBG();
170
171         num_executions++;
172
173         if (isfeasible() || DBG_ENABLED())
174                 print_summary();
175
176         if ((diverge = model->get_next_backtrack()) == NULL)
177                 return false;
178
179         if (DBG_ENABLED()) {
180                 printf("Next execution will diverge at:\n");
181                 diverge->print();
182         }
183
184         model->reset_to_initial_state();
185         return true;
186 }
187
188 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
189 {
190         action_type type = act->get_type();
191
192         switch (type) {
193                 case ATOMIC_READ:
194                 case ATOMIC_WRITE:
195                 case ATOMIC_RMW:
196                         break;
197                 default:
198                         return NULL;
199         }
200         /* linear search: from most recent to oldest */
201         action_list_t *list = obj_map->ensureptr(act->get_location());
202         action_list_t::reverse_iterator rit;
203         for (rit = list->rbegin(); rit != list->rend(); rit++) {
204                 ModelAction *prev = *rit;
205                 if (act->is_synchronizing(prev))
206                         return prev;
207         }
208         return NULL;
209 }
210
211 void ModelChecker::set_backtracking(ModelAction *act)
212 {
213         ModelAction *prev;
214         Node *node;
215         Thread *t = get_thread(act->get_tid());
216
217         prev = get_last_conflict(act);
218         if (prev == NULL)
219                 return;
220
221         node = prev->get_node()->get_parent();
222
223         while (!node->is_enabled(t))
224                 t = t->get_parent();
225
226         /* Check if this has been explored already */
227         if (node->has_been_explored(t->get_id()))
228                 return;
229
230         /* Cache the latest backtracking point */
231         if (!next_backtrack || *prev > *next_backtrack)
232                 next_backtrack = prev;
233
234         /* If this is a new backtracking point, mark the tree */
235         if (!node->set_backtrack(t->get_id()))
236                 return;
237         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
238                         prev->get_tid(), t->get_id());
239         if (DBG_ENABLED()) {
240                 prev->print();
241                 act->print();
242         }
243 }
244
245 /**
246  * Returns last backtracking point. The model checker will explore a different
247  * path for this point in the next execution.
248  * @return The ModelAction at which the next execution should diverge.
249  */
250 ModelAction * ModelChecker::get_next_backtrack()
251 {
252         ModelAction *next = next_backtrack;
253         next_backtrack = NULL;
254         return next;
255 }
256
257 void ModelChecker::check_current_action(void)
258 {
259         ModelAction *curr = this->current_action;
260         bool already_added = false;
261         this->current_action = NULL;
262         if (!curr) {
263                 DEBUG("trying to push NULL action...\n");
264                 return;
265         }
266
267         if (curr->is_rmwc()||curr->is_rmw()) {
268                 ModelAction *tmp=process_rmw(curr);
269                 already_added = true;
270                 delete curr;
271                 curr=tmp;
272         } else {
273                 ModelAction * tmp = node_stack->explore_action(curr);
274                 if (tmp) {
275                         /* Discard duplicate ModelAction; use action from NodeStack */
276                         /* First restore type and order in case of RMW operation */
277                         if (curr->is_rmwr())
278                                 tmp->copy_typeandorder(curr);
279                         delete curr;
280                         curr = tmp;
281                 } else {
282                         /*
283                          * Perform one-time actions when pushing new ModelAction onto
284                          * NodeStack
285                          */
286                         curr->create_cv(get_parent_action(curr->get_tid()));
287                         /* Build may_read_from set */
288                         if (curr->is_read())
289                                 build_reads_from_past(curr);
290                 }
291         }
292
293         /* Assign 'creation' parent */
294         if (curr->get_type() == THREAD_CREATE) {
295                 Thread *th = (Thread *)curr->get_location();
296                 th->set_creation(curr);
297         }
298
299         /* Deal with new thread */
300         if (curr->get_type() == THREAD_START) {
301                 check_promises(NULL, curr->get_cv());
302         }
303
304         /* Assign reads_from values */
305         Thread *th = get_thread(curr->get_tid());
306         uint64_t value = VALUE_NONE;
307         if (curr->is_read()) {
308                 const ModelAction *reads_from = curr->get_node()->get_read_from();
309                 if (reads_from!=NULL) {
310                         value = reads_from->get_value();
311                         /* Assign reads_from, perform release/acquire synchronization */
312                         curr->read_from(reads_from);
313                         r_modification_order(curr,reads_from);
314                 } else {
315                         /* Read from future value */
316                         value = curr->get_node()->get_future_value();
317                         curr->read_from(NULL);
318                         Promise * valuepromise=new Promise(curr, value);
319                         promises->push_back(valuepromise);
320                 }
321         } else if (curr->is_write()) {
322                 w_modification_order(curr);
323         }
324
325         th->set_return_value(value);
326
327         /* Add action to list.  */
328         if (!already_added)
329                 add_action_to_lists(curr);
330
331         /* Is there a better interface for setting the next thread rather
332                  than this field/convoluted approach?  Perhaps like just returning
333                  it or something? */
334
335         /* Do not split atomic actions. */
336         if (curr->is_rmwr()) {
337                 nextThread = thread_current()->get_id();
338         } else {
339                 nextThread = get_next_replay_thread();
340         }
341
342         Node *currnode = curr->get_node();
343         Node *parnode = currnode->get_parent();
344
345         if (!parnode->backtrack_empty()||!currnode->readsfrom_empty()||!currnode->futurevalues_empty())
346                 if (!next_backtrack || *curr > *next_backtrack)
347                         next_backtrack = curr;
348         
349         set_backtracking(curr);
350 }
351
352 /** @returns whether the current trace is feasible. */
353 bool ModelChecker::isfeasible() {
354         return !cyclegraph->checkForCycles() && !failed_promise;
355 }
356
357 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
358 ModelAction * ModelChecker::process_rmw(ModelAction * act) {
359         int tid = id_to_int(act->get_tid());
360         ModelAction *lastread=get_last_action(tid);
361         lastread->process_rmw(act);
362         if (act->is_rmw())
363                 cyclegraph->addRMWEdge(lastread, lastread->get_reads_from());
364         return lastread;
365 }
366
367 /**
368  * Updates the cyclegraph with the constraints imposed from the current read.
369  * @param curr The current action. Must be a read.
370  * @param rf The action that curr reads from. Must be a write.
371  */
372 void ModelChecker::r_modification_order(ModelAction * curr, const ModelAction *rf) {
373         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
374         unsigned int i;
375         ASSERT(curr->is_read());
376
377         /* Iterate over all threads */
378         for (i = 0; i < thrd_lists->size(); i++) {
379                 /* Iterate over actions in thread, starting from most recent */
380                 action_list_t *list = &(*thrd_lists)[i];
381                 action_list_t::reverse_iterator rit;
382                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
383                         ModelAction *act = *rit;
384
385                         /* Include at most one act per-thread that "happens before" curr */
386                         if (act->happens_before(curr)) {
387                                 if (act->is_read()) {
388                                         const ModelAction * prevreadfrom=act->get_reads_from();
389                                         if (rf!=prevreadfrom)
390                                                 cyclegraph->addEdge(rf, prevreadfrom);
391                                 } else if (rf!=act) {
392                                         cyclegraph->addEdge(rf, act);
393                                 }
394                                 break;
395                         }
396                 }
397         }
398 }
399
400 /**
401  * Updates the cyclegraph with the constraints imposed from the current write.
402  * @param curr The current action. Must be a write.
403  */
404 void ModelChecker::w_modification_order(ModelAction * curr) {
405         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
406         unsigned int i;
407         ASSERT(curr->is_write());
408
409         if (curr->is_seqcst()) {
410                 /* We have to at least see the last sequentially consistent write,
411                          so we are initialized. */
412                 ModelAction * last_seq_cst=get_last_seq_cst(curr->get_location());
413                 if (last_seq_cst!=NULL)
414                         cyclegraph->addEdge(curr, last_seq_cst);
415         }
416
417         /* Iterate over all threads */
418         for (i = 0; i < thrd_lists->size(); i++) {
419                 /* Iterate over actions in thread, starting from most recent */
420                 action_list_t *list = &(*thrd_lists)[i];
421                 action_list_t::reverse_iterator rit;
422                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
423                         ModelAction *act = *rit;
424
425                         /* Include at most one act per-thread that "happens before" curr */
426                         if (act->happens_before(curr)) {
427                                 if (act->is_read()) {
428                                         cyclegraph->addEdge(curr, act->get_reads_from());
429                                 } else
430                                         cyclegraph->addEdge(curr, act);
431                                 break;
432                         } else {
433                                 if (act->is_read()&&!act->is_synchronizing(curr)&&!act->same_thread(curr)) {
434                                         /* We have an action that:
435                                                  (1) did not happen before us
436                                                  (2) is a read and we are a write
437                                                  (3) cannot synchronize with us
438                                                  (4) is in a different thread 
439                                                  =>
440                                                  that read could potentially read from our write.
441                                         */
442
443                                         if (act->get_node()->add_future_value(curr->get_value())&&
444                                                         (!next_backtrack || *act > * next_backtrack))
445                                                 next_backtrack = act;
446                                 }
447                         }
448                 }
449         }
450 }
451
452 /**
453  * Performs various bookkeeping operations for the current ModelAction. For
454  * instance, adds action to the per-object, per-thread action vector and to the
455  * action trace list of all thread actions.
456  *
457  * @param act is the ModelAction to add.
458  */
459 void ModelChecker::add_action_to_lists(ModelAction *act)
460 {
461         int tid = id_to_int(act->get_tid());
462         action_trace->push_back(act);
463
464         obj_map->ensureptr(act->get_location())->push_back(act);
465
466         std::vector<action_list_t> *vec = obj_thrd_map->ensureptr(act->get_location());
467         if (tid >= (int)vec->size())
468                 vec->resize(next_thread_id);
469         (*vec)[tid].push_back(act);
470
471         if ((int)thrd_last_action->size() <= tid)
472                 thrd_last_action->resize(get_num_threads());
473         (*thrd_last_action)[tid] = act;
474 }
475
476 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
477 {
478         int nthreads = get_num_threads();
479         if ((int)thrd_last_action->size() < nthreads)
480                 thrd_last_action->resize(nthreads);
481         return (*thrd_last_action)[id_to_int(tid)];
482 }
483
484 /**
485  * Gets the last memory_order_seq_cst action (in the total global sequence)
486  * performed on a particular object (i.e., memory location).
487  * @param location The object location to check
488  * @return The last seq_cst action performed
489  */
490 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
491 {
492         action_list_t *list = obj_map->ensureptr(location);
493         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
494         action_list_t::reverse_iterator rit;
495         for (rit = list->rbegin(); rit != list->rend(); rit++)
496                 if ((*rit)->is_write() && (*rit)->is_seqcst())
497                         return *rit;
498         return NULL;
499 }
500
501 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
502 {
503         ModelAction *parent = get_last_action(tid);
504         if (!parent)
505                 parent = get_thread(tid)->get_creation();
506         return parent;
507 }
508
509 /**
510  * Returns the clock vector for a given thread.
511  * @param tid The thread whose clock vector we want
512  * @return Desired clock vector
513  */
514 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
515         return get_parent_action(tid)->get_cv();
516 }
517
518 /** Checks promises in response to change in ClockVector Threads. */
519
520 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector * merge_cv) {
521         for(unsigned int i=0;i<promises->size();i++) {
522                 Promise * promise=(*promises)[i];
523                 const ModelAction * act=promise->get_action();
524                 if ((old_cv==NULL||!old_cv->synchronized_since(act))&&
525                                 merge_cv->synchronized_since(act)) {
526                         //This thread is no longer able to send values back to satisfy the promise
527                         int num_synchronized_threads=promise->increment_threads();
528                         if (num_synchronized_threads==model->get_num_threads()) {
529                                 //Promise has failed
530                                 failed_promise = true;
531                                 return;
532                         }
533                 }
534         }
535 }
536
537 /**
538  * Build up an initial set of all past writes that this 'read' action may read
539  * from. This set is determined by the clock vector's "happens before"
540  * relationship.
541  * @param curr is the current ModelAction that we are exploring; it must be a
542  * 'read' operation.
543  */
544 void ModelChecker::build_reads_from_past(ModelAction *curr)
545 {
546         std::vector<action_list_t> *thrd_lists = obj_thrd_map->ensureptr(curr->get_location());
547         unsigned int i;
548         ASSERT(curr->is_read());
549
550         ModelAction *last_seq_cst = NULL;
551
552         /* Track whether this object has been initialized */
553         bool initialized = false;
554
555         if (curr->is_seqcst()) {
556                 last_seq_cst = get_last_seq_cst(curr->get_location());
557                 /* We have to at least see the last sequentially consistent write,
558                          so we are initialized. */
559                 if (last_seq_cst != NULL)
560                         initialized = true;
561         }
562
563         /* Iterate over all threads */
564         for (i = 0; i < thrd_lists->size(); i++) {
565                 /* Iterate over actions in thread, starting from most recent */
566                 action_list_t *list = &(*thrd_lists)[i];
567                 action_list_t::reverse_iterator rit;
568                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
569                         ModelAction *act = *rit;
570
571                         /* Only consider 'write' actions */
572                         if (!act->is_write())
573                                 continue;
574
575                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
576                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
577                                 DEBUG("Adding action to may_read_from:\n");
578                                 if (DBG_ENABLED()) {
579                                         act->print();
580                                         curr->print();
581                                 }
582                                 curr->get_node()->add_read_from(act);
583                         }
584
585                         /* Include at most one act per-thread that "happens before" curr */
586                         if (act->happens_before(curr)) {
587                                 initialized = true;
588                                 break;
589                         }
590                 }
591         }
592
593         if (!initialized) {
594                 /** @todo Need a more informative way of reporting errors. */
595                 printf("ERROR: may read from uninitialized atomic\n");
596         }
597
598         if (DBG_ENABLED() || !initialized) {
599                 printf("Reached read action:\n");
600                 curr->print();
601                 printf("Printing may_read_from\n");
602                 curr->get_node()->print_may_read_from();
603                 printf("End printing may_read_from\n");
604         }
605
606         ASSERT(initialized);
607 }
608
609 static void print_list(action_list_t *list)
610 {
611         action_list_t::iterator it;
612
613         printf("---------------------------------------------------------------------\n");
614         printf("Trace:\n");
615
616         for (it = list->begin(); it != list->end(); it++) {
617                 (*it)->print();
618         }
619         printf("---------------------------------------------------------------------\n");
620 }
621
622 void ModelChecker::print_summary(void)
623 {
624         printf("\n");
625         printf("Number of executions: %d\n", num_executions);
626         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
627
628         scheduler->print();
629
630         if (!isfeasible())
631                 printf("INFEASIBLE EXECUTION!\n");
632         print_list(action_trace);
633         printf("\n");
634 }
635
636 int ModelChecker::add_thread(Thread *t)
637 {
638         thread_map->put(id_to_int(t->get_id()), t);
639         scheduler->add_thread(t);
640         return 0;
641 }
642
643 void ModelChecker::remove_thread(Thread *t)
644 {
645         scheduler->remove_thread(t);
646 }
647
648 /**
649  * Switch from a user-context to the "master thread" context (a.k.a. system
650  * context). This switch is made with the intention of exploring a particular
651  * model-checking action (described by a ModelAction object). Must be called
652  * from a user-thread context.
653  * @param act The current action that will be explored. May be NULL, although
654  * there is little reason to switch to the model-checker without an action to
655  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
656  * yield control without performing any progress; see thrd_join()).
657  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
658  */
659 int ModelChecker::switch_to_master(ModelAction *act)
660 {
661         DBG();
662         Thread * old = thread_current();
663         set_current_action(act);
664         old->set_state(THREAD_READY);
665         return Thread::swap(old, get_system_context());
666 }