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