e9d1f1df069cb5f0f1b79c9683143b59c4b39ffe
[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
11 #define INITIAL_THREAD_ID       0
12
13 ModelChecker *model;
14
15 /** @brief Constructor */
16 ModelChecker::ModelChecker()
17         :
18         /* Initialize default scheduler */
19         scheduler(new Scheduler()),
20         /* First thread created will have id INITIAL_THREAD_ID */
21         next_thread_id(INITIAL_THREAD_ID),
22         used_sequence_numbers(0),
23
24         num_executions(0),
25         current_action(NULL),
26         diverge(NULL),
27         nextThread(THREAD_ID_T_NONE),
28         action_trace(new action_list_t()),
29         thread_map(new std::map<int, Thread *>),
30         obj_map(new std::map<const void *, action_list_t>()),
31         obj_thrd_map(new std::map<void *, std::vector<action_list_t> >()),
32         thrd_last_action(new std::vector<ModelAction *>(1)),
33         node_stack(new NodeStack()),
34         next_backtrack(NULL)
35 {
36 }
37
38 /** @brief Destructor */
39 ModelChecker::~ModelChecker()
40 {
41         std::map<int, Thread *>::iterator it;
42         for (it = thread_map->begin(); it != thread_map->end(); it++)
43                 delete (*it).second;
44         delete thread_map;
45
46         delete obj_thrd_map;
47         delete obj_map;
48         delete action_trace;
49         delete thrd_last_action;
50         delete node_stack;
51         delete scheduler;
52 }
53
54 /**
55  * Restores user program to initial state and resets all model-checker data
56  * structures.
57  */
58 void ModelChecker::reset_to_initial_state()
59 {
60         DEBUG("+++ Resetting to initial state +++\n");
61         node_stack->reset_execution();
62         current_action = NULL;
63         next_thread_id = INITIAL_THREAD_ID;
64         used_sequence_numbers = 0;
65         nextThread = 0;
66         next_backtrack = NULL;
67         snapshotObject->backTrackBeforeStep(0);
68 }
69
70 /** @returns a thread ID for a new Thread */
71 thread_id_t ModelChecker::get_next_id()
72 {
73         return next_thread_id++;
74 }
75
76 /** @returns the number of user threads created during this execution */
77 int ModelChecker::get_num_threads()
78 {
79         return next_thread_id;
80 }
81
82 /** @returns a sequence number for a new ModelAction */
83 modelclock_t ModelChecker::get_next_seq_num()
84 {
85         return ++used_sequence_numbers;
86 }
87
88 /**
89  * Performs the "scheduling" for the model-checker. That is, it checks if the
90  * model-checker has selected a "next thread to run" and returns it, if
91  * available. This function should be called from the Scheduler routine, where
92  * the Scheduler falls back to a default scheduling routine if needed.
93  *
94  * @return The next thread chosen by the model-checker. If the model-checker
95  * makes no selection, retuns NULL.
96  */
97 Thread * ModelChecker::schedule_next_thread()
98 {
99         Thread *t;
100         if (nextThread == THREAD_ID_T_NONE)
101                 return NULL;
102         t = (*thread_map)[id_to_int(nextThread)];
103
104         ASSERT(t != NULL);
105
106         return t;
107 }
108
109 /**
110  * Choose the next thread in the replay sequence.
111  *
112  * If the replay sequence has reached the 'diverge' point, returns a thread
113  * from the backtracking set. Otherwise, simply returns the next thread in the
114  * sequence that is being replayed.
115  */
116 thread_id_t ModelChecker::get_next_replay_thread()
117 {
118         ModelAction *next;
119         thread_id_t tid;
120
121         /* Have we completed exploring the preselected path? */
122         if (diverge == NULL)
123                 return THREAD_ID_T_NONE;
124
125         /* Else, we are trying to replay an execution */
126         next = node_stack->get_next()->get_action();
127
128         if (next == diverge) {
129                 Node *nextnode = next->get_node();
130                 /* Reached divergence point */
131                 if (nextnode->increment_read_from()) {
132                         /* The next node will read from a different value */
133                         tid = next->get_tid();
134                         node_stack->pop_restofstack(2);
135                 } else {
136                         /* Make a different thread execute for next step */
137                         Node *node = nextnode->get_parent();
138                         tid = node->get_next_backtrack();
139                         node_stack->pop_restofstack(1);
140                 }
141                 DEBUG("*** Divergence point ***\n");
142                 diverge = NULL;
143         } else {
144                 tid = next->get_tid();
145         }
146         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
147         return tid;
148 }
149
150 /**
151  * Queries the model-checker for more executions to explore and, if one
152  * exists, resets the model-checker state to execute a new execution.
153  *
154  * @return If there are more executions to explore, return true. Otherwise,
155  * return false.
156  */
157 bool ModelChecker::next_execution()
158 {
159         DBG();
160
161         num_executions++;
162         print_summary();
163         if ((diverge = model->get_next_backtrack()) == NULL)
164                 return false;
165
166         if (DBG_ENABLED()) {
167                 printf("Next execution will diverge at:\n");
168                 diverge->print();
169         }
170
171         model->reset_to_initial_state();
172         return true;
173 }
174
175 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
176 {
177         action_type type = act->get_type();
178
179         switch (type) {
180                 case ATOMIC_READ:
181                 case ATOMIC_WRITE:
182                 case ATOMIC_RMW:
183                         break;
184                 default:
185                         return NULL;
186         }
187         /* linear search: from most recent to oldest */
188         action_list_t *list = &(*obj_map)[act->get_location()];
189         action_list_t::reverse_iterator rit;
190         for (rit = list->rbegin(); rit != list->rend(); rit++) {
191                 ModelAction *prev = *rit;
192                 if (act->is_synchronizing(prev))
193                         return prev;
194         }
195         return NULL;
196 }
197
198 void ModelChecker::set_backtracking(ModelAction *act)
199 {
200         ModelAction *prev;
201         Node *node;
202         Thread *t = get_thread(act->get_tid());
203
204         prev = get_last_conflict(act);
205         if (prev == NULL)
206                 return;
207
208         node = prev->get_node()->get_parent();
209
210         while (!node->is_enabled(t))
211                 t = t->get_parent();
212
213         /* Check if this has been explored already */
214         if (node->has_been_explored(t->get_id()))
215                 return;
216
217         /* Cache the latest backtracking point */
218         if (!next_backtrack || *prev > *next_backtrack)
219                 next_backtrack = prev;
220
221         /* If this is a new backtracking point, mark the tree */
222         if (!node->set_backtrack(t->get_id()))
223                 return;
224         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
225                         prev->get_tid(), t->get_id());
226         if (DBG_ENABLED()) {
227                 prev->print();
228                 act->print();
229         }
230 }
231
232 ModelAction * ModelChecker::get_next_backtrack()
233 {
234         ModelAction *next = next_backtrack;
235         next_backtrack = NULL;
236         return next;
237 }
238
239 void ModelChecker::check_current_action(void)
240 {
241         ModelAction *curr = this->current_action;
242         ModelAction *tmp;
243         current_action = NULL;
244         if (!curr) {
245                 DEBUG("trying to push NULL action...\n");
246                 return;
247         }
248
249         tmp = node_stack->explore_action(curr);
250         if (tmp) {
251                 /* Discard duplicate ModelAction; use action from NodeStack */
252                 delete curr;
253                 curr = tmp;
254         } else {
255                 /*
256                  * Perform one-time actions when pushing new ModelAction onto
257                  * NodeStack
258                  */
259                 curr->create_cv(get_parent_action(curr->get_tid()));
260                 /* Build may_read_from set */
261                 if (curr->is_read())
262                         build_reads_from_past(curr);
263         }
264
265         /* Assign 'creation' parent */
266         if (curr->get_type() == THREAD_CREATE) {
267                 Thread *th = (Thread *)curr->get_location();
268                 th->set_creation(curr);
269         }
270
271         nextThread = get_next_replay_thread();
272
273         Node *currnode = curr->get_node();
274         Node *parnode = currnode->get_parent();
275
276         if (!parnode->backtrack_empty()||!currnode->readsfrom_empty())
277                 if (!next_backtrack || *curr > *next_backtrack)
278                         next_backtrack = curr;
279
280         set_backtracking(curr);
281
282         add_action_to_lists(curr);
283
284         /* Assign reads_from values */
285         /* TODO: perform release/acquire synchronization here; include
286          * reads_from as ModelAction member? */
287         Thread *th = get_thread(curr->get_tid());
288         uint64_t value = VALUE_NONE;
289         if (curr->is_read()) {
290                 const ModelAction *reads_from = curr->get_node()->get_read_from();
291                 value = reads_from->get_value();
292                 /* Assign reads_from, perform release/acquire synchronization */
293                 curr->read_from(reads_from);
294         }
295         th->set_return_value(value);
296 }
297
298 /**
299  * Performs various bookkeeping operations for the current ModelAction. For
300  * instance, adds action to the per-object, per-thread action vector and to the
301  * action trace list of all thread actions.
302  *
303  * @param act is the ModelAction to add.
304  */
305 void ModelChecker::add_action_to_lists(ModelAction *act)
306 {
307         int tid = id_to_int(act->get_tid());
308         action_trace->push_back(act);
309
310         (*obj_map)[act->get_location()].push_back(act);
311
312         std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
313         if (tid >= (int)vec->size())
314                 vec->resize(next_thread_id);
315         (*vec)[tid].push_back(act);
316
317         if ((int)thrd_last_action->size() <= tid)
318                 thrd_last_action->resize(get_num_threads());
319         (*thrd_last_action)[tid] = act;
320 }
321
322 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
323 {
324         int nthreads = get_num_threads();
325         if ((int)thrd_last_action->size() < nthreads)
326                 thrd_last_action->resize(nthreads);
327         return (*thrd_last_action)[id_to_int(tid)];
328 }
329
330 /**
331  * Gets the last memory_order_seq_cst action (in the total global sequence)
332  * performed on a particular object (i.e., memory location).
333  * @param location The object location to check
334  * @return The last seq_cst action performed
335  */
336 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
337 {
338         action_list_t *list = &(*obj_map)[location];
339         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
340         action_list_t::reverse_iterator rit;
341         for (rit = list->rbegin(); rit != list->rend(); rit++)
342                 if ((*rit)->is_write() && (*rit)->is_seqcst())
343                         return *rit;
344         return NULL;
345 }
346
347 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
348 {
349         ModelAction *parent = get_last_action(tid);
350         if (!parent)
351                 parent = get_thread(tid)->get_creation();
352         return parent;
353 }
354
355 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
356         return get_parent_action(tid)->get_cv();
357 }
358
359 /**
360  * Build up an initial set of all past writes that this 'read' action may read
361  * from. This set is determined by the clock vector's "happens before"
362  * relationship.
363  * @param curr is the current ModelAction that we are exploring; it must be a
364  * 'read' operation.
365  */
366 void ModelChecker::build_reads_from_past(ModelAction *curr)
367 {
368         std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
369         unsigned int i;
370         ASSERT(curr->is_read());
371
372         ModelAction *last_seq_cst = NULL;
373
374         /* Track whether this object has been initialized */
375         bool initialized = false;
376
377         if (curr->is_seqcst()) {
378                 last_seq_cst = get_last_seq_cst(curr->get_location());
379                 /* We have to at least see the last sequentially consistent write,
380                          so we are initialized. */
381                 if (last_seq_cst != NULL)
382                         initialized = true;
383         }
384
385         /* Iterate over all threads */
386         for (i = 0; i < thrd_lists->size(); i++) {
387                 /* Iterate over actions in thread, starting from most recent */
388                 action_list_t *list = &(*thrd_lists)[i];
389                 action_list_t::reverse_iterator rit;
390                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
391                         ModelAction *act = *rit;
392
393                         /* Only consider 'write' actions */
394                         if (!act->is_write())
395                                 continue;
396
397                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
398                         if (!act->is_seqcst() || !curr->is_seqcst() || act == last_seq_cst) {
399                                 DEBUG("Adding action to may_read_from:\n");
400                                 if (DBG_ENABLED()) {
401                                         act->print();
402                                         curr->print();
403                                 }
404                                 curr->get_node()->add_read_from(act);
405                         }
406
407                         /* Include at most one act per-thread that "happens before" curr */
408                         if (act->happens_before(curr)) {
409                                 initialized = true;
410                                 break;
411                         }
412                 }
413         }
414
415         if (!initialized) {
416                 /* TODO: need a more informative way of reporting errors */
417                 printf("ERROR: may read from uninitialized atomic\n");
418         }
419         
420         if (DBG_ENABLED() || !initialized) {
421                 printf("Reached read action:\n");
422                 curr->print();
423                 printf("Printing may_read_from\n");
424                 curr->get_node()->print_may_read_from();
425                 printf("End printing may_read_from\n");
426         }
427         
428         ASSERT(initialized);
429 }
430
431 static void print_list(action_list_t *list)
432 {
433         action_list_t::iterator it;
434
435         printf("---------------------------------------------------------------------\n");
436         printf("Trace:\n");
437
438         for (it = list->begin(); it != list->end(); it++) {
439                 (*it)->print();
440         }
441         printf("---------------------------------------------------------------------\n");
442 }
443
444 void ModelChecker::print_summary(void)
445 {
446         printf("\n");
447         printf("Number of executions: %d\n", num_executions);
448         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
449
450         scheduler->print();
451
452         print_list(action_trace);
453         printf("\n");
454 }
455
456 int ModelChecker::add_thread(Thread *t)
457 {
458         (*thread_map)[id_to_int(t->get_id())] = t;
459         scheduler->add_thread(t);
460         return 0;
461 }
462
463 void ModelChecker::remove_thread(Thread *t)
464 {
465         scheduler->remove_thread(t);
466 }
467
468 /**
469  * Switch from a user-context to the "master thread" context (a.k.a. system
470  * context). This switch is made with the intention of exploring a particular
471  * model-checking action (described by a ModelAction object). Must be called
472  * from a user-thread context.
473  * @param act The current action that will be explored. May be NULL, although
474  * there is little reason to switch to the model-checker without an action to
475  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
476  * yield control without performing any progress; see thrd_join()).
477  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
478  */
479 int ModelChecker::switch_to_master(ModelAction *act)
480 {
481         Thread *old;
482
483         DBG();
484         old = thread_current();
485         set_current_action(act);
486         old->set_state(THREAD_READY);
487         return Thread::swap(old, get_system_context());
488 }