0bd9b61b410f7c57f2991f9446cb74847448a55e
[model-checker.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 *node = next->get_node()->get_parent();
130
131                 /* Reached divergence point */
132                 DEBUG("*** Divergence point ***\n");
133                 tid = node->get_next_backtrack();
134                 diverge = NULL;
135         } else {
136                 tid = next->get_tid();
137         }
138         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
139         return tid;
140 }
141
142 /**
143  * Queries the model-checker for more executions to explore and, if one
144  * exists, resets the model-checker state to execute a new execution.
145  *
146  * @return If there are more executions to explore, return true. Otherwise,
147  * return false.
148  */
149 bool ModelChecker::next_execution()
150 {
151         DBG();
152
153         num_executions++;
154         print_summary();
155         if ((diverge = model->get_next_backtrack()) == NULL)
156                 return false;
157
158         if (DBG_ENABLED()) {
159                 printf("Next execution will diverge at:\n");
160                 diverge->print();
161         }
162
163         model->reset_to_initial_state();
164         return true;
165 }
166
167 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
168 {
169         action_type type = act->get_type();
170
171         switch (type) {
172                 case ATOMIC_READ:
173                 case ATOMIC_WRITE:
174                 case ATOMIC_RMW:
175                         break;
176                 default:
177                         return NULL;
178         }
179         /* linear search: from most recent to oldest */
180         action_list_t *list = &(*obj_map)[act->get_location()];
181         action_list_t::reverse_iterator rit;
182         for (rit = list->rbegin(); rit != list->rend(); rit++) {
183                 ModelAction *prev = *rit;
184                 if (act->is_synchronizing(prev))
185                         return prev;
186         }
187         return NULL;
188 }
189
190 void ModelChecker::set_backtracking(ModelAction *act)
191 {
192         ModelAction *prev;
193         Node *node;
194         Thread *t = get_thread(act->get_tid());
195
196         prev = get_last_conflict(act);
197         if (prev == NULL)
198                 return;
199
200         node = prev->get_node()->get_parent();
201
202         while (!node->is_enabled(t))
203                 t = t->get_parent();
204
205         /* Check if this has been explored already */
206         if (node->has_been_explored(t->get_id()))
207                 return;
208
209         /* Cache the latest backtracking point */
210         if (!next_backtrack || *prev > *next_backtrack)
211                 next_backtrack = prev;
212
213         /* If this is a new backtracking point, mark the tree */
214         if (!node->set_backtrack(t->get_id()))
215                 return;
216         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
217                         prev->get_tid(), t->get_id());
218         if (DBG_ENABLED()) {
219                 prev->print();
220                 act->print();
221         }
222 }
223
224 ModelAction * ModelChecker::get_next_backtrack()
225 {
226         ModelAction *next = next_backtrack;
227         next_backtrack = NULL;
228         return next;
229 }
230
231 void ModelChecker::check_current_action(void)
232 {
233         Node *currnode;
234
235         ModelAction *curr = this->current_action;
236         ModelAction *tmp;
237         current_action = NULL;
238         if (!curr) {
239                 DEBUG("trying to push NULL action...\n");
240                 return;
241         }
242
243         tmp = node_stack->explore_action(curr);
244         if (tmp) {
245                 /* Discard duplicate ModelAction; use action from NodeStack */
246                 delete curr;
247                 curr = tmp;
248         } else {
249                 /*
250                  * Perform one-time actions when pushing new ModelAction onto
251                  * NodeStack
252                  */
253                 curr->create_cv(get_parent_action(curr->get_tid()));
254                 /* Build may_read_from set */
255                 if (curr->is_read())
256                         build_reads_from_past(curr);
257         }
258
259         /* Assign 'creation' parent */
260         if (curr->get_type() == THREAD_CREATE) {
261                 Thread *th = (Thread *)curr->get_location();
262                 th->set_creation(curr);
263         }
264
265         nextThread = get_next_replay_thread();
266
267         currnode = curr->get_node()->get_parent();
268
269         if (!currnode->backtrack_empty())
270                 if (!next_backtrack || *curr > *next_backtrack)
271                         next_backtrack = curr;
272
273         set_backtracking(curr);
274
275         add_action_to_lists(curr);
276
277         /* Assign reads_from values */
278         /* TODO: perform release/acquire synchronization here; include
279          * reads_from as ModelAction member? */
280         Thread *th = get_thread(curr->get_tid());
281         int value = VALUE_NONE;
282         if (curr->is_read()) {
283                 const ModelAction *reads_from = curr->get_node()->get_next_read_from();
284                 value = reads_from->get_value();
285                 /* Assign reads_from, perform release/acquire synchronization */
286                 curr->read_from(reads_from);
287         }
288         th->set_return_value(value);
289 }
290
291 /**
292  * Performs various bookkeeping operations for the current ModelAction. For
293  * instance, adds action to the per-object, per-thread action vector and to the
294  * action trace list of all thread actions.
295  *
296  * @param act is the ModelAction to add.
297  */
298 void ModelChecker::add_action_to_lists(ModelAction *act)
299 {
300         int tid = id_to_int(act->get_tid());
301         action_trace->push_back(act);
302
303         (*obj_map)[act->get_location()].push_back(act);
304
305         std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
306         if (tid >= (int)vec->size())
307                 vec->resize(next_thread_id);
308         (*vec)[tid].push_back(act);
309
310         if ((int)thrd_last_action->size() <= tid)
311                 thrd_last_action->resize(get_num_threads());
312         (*thrd_last_action)[tid] = act;
313 }
314
315 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
316 {
317         int nthreads = get_num_threads();
318         if ((int)thrd_last_action->size() < nthreads)
319                 thrd_last_action->resize(nthreads);
320         return (*thrd_last_action)[id_to_int(tid)];
321 }
322
323 /**
324  * Gets the last memory_order_seq_cst action (in the total global sequence)
325  * performed on a particular object (i.e., memory location).
326  * @param location The object location to check
327  * @return The last seq_cst action performed
328  */
329 ModelAction * ModelChecker::get_last_seq_cst(const void *location)
330 {
331         action_list_t *list = &(*obj_map)[location];
332         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
333         action_list_t::reverse_iterator rit;
334         for (rit = list->rbegin(); rit != list->rend(); rit++)
335                 if ((*rit)->is_write() && (*rit)->is_seqcst())
336                         return *rit;
337         return NULL;
338 }
339
340 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
341 {
342         ModelAction *parent = get_last_action(tid);
343         if (!parent)
344                 parent = get_thread(tid)->get_creation();
345         return parent;
346 }
347
348 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
349         return get_parent_action(tid)->get_cv();
350 }
351
352 /**
353  * Build up an initial set of all past writes that this 'read' action may read
354  * from. This set is determined by the clock vector's "happens before"
355  * relationship.
356  * @param curr is the current ModelAction that we are exploring; it must be a
357  * 'read' operation.
358  */
359 void ModelChecker::build_reads_from_past(ModelAction *curr)
360 {
361         std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
362         unsigned int i;
363
364         ASSERT(curr->is_read());
365
366         ModelAction *last_seq_cst = NULL;
367
368         /* Track whether this object has been initialized */
369         bool initialized = false;
370
371         if (curr->is_seqcst()) {
372                 last_seq_cst = get_last_seq_cst(curr->get_location());
373                 /* We have to at least see the last sequentially consistent write,
374                          so we are initialized. */
375                 if (last_seq_cst != NULL)
376                         initialized = true;
377         }
378
379         /* Iterate over all threads */
380         for (i = 0; i < thrd_lists->size(); i++) {
381                 /* Iterate over actions in thread, starting from most recent */
382                 action_list_t *list = &(*thrd_lists)[i];
383                 action_list_t::reverse_iterator rit;
384                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
385                         ModelAction *act = *rit;
386
387                         /* Only consider 'write' actions */
388                         if (!act->is_write())
389                                 continue;
390
391                         /* Don't consider more than one seq_cst write */
392                         if (!act->is_seqcst() || act == last_seq_cst) {
393                                 DEBUG("Adding action to may_read_from:\n");
394                                 if (DBG_ENABLED()) {
395                                         act->print();
396                                         curr->print();
397                                 }
398                                 curr->get_node()->add_read_from(act);
399                         }
400
401                         /* Include at most one act per-thread that "happens before" curr */
402                         if (act->happens_before(curr)) {
403                                 initialized = true;
404                                 break;
405                         }
406                 }
407         }
408
409         if (!initialized) {
410                 /* TODO: need a more informative way of reporting errors */
411                 printf("ERROR: may read from uninitialized atomic\n");
412         }
413         
414         if (DBG_ENABLED() || !initialized) {
415                 printf("Reached read action:\n");
416                 curr->print();
417                 printf("Printing may_read_from\n");
418                 curr->get_node()->print_may_read_from();
419                 printf("End printing may_read_from\n");
420         }
421         
422         ASSERT(initialized);
423 }
424
425 static void print_list(action_list_t *list)
426 {
427         action_list_t::iterator it;
428
429         printf("---------------------------------------------------------------------\n");
430         printf("Trace:\n");
431
432         for (it = list->begin(); it != list->end(); it++) {
433                 (*it)->print();
434         }
435         printf("---------------------------------------------------------------------\n");
436 }
437
438 void ModelChecker::print_summary(void)
439 {
440         printf("\n");
441         printf("Number of executions: %d\n", num_executions);
442         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
443
444         scheduler->print();
445
446         print_list(action_trace);
447         printf("\n");
448 }
449
450 int ModelChecker::add_thread(Thread *t)
451 {
452         (*thread_map)[id_to_int(t->get_id())] = t;
453         scheduler->add_thread(t);
454         return 0;
455 }
456
457 void ModelChecker::remove_thread(Thread *t)
458 {
459         scheduler->remove_thread(t);
460 }
461
462 /**
463  * Switch from a user-context to the "master thread" context (a.k.a. system
464  * context). This switch is made with the intention of exploring a particular
465  * model-checking action (described by a ModelAction object). Must be called
466  * from a user-thread context.
467  * @param act The current action that will be explored. May be NULL, although
468  * there is little reason to switch to the model-checker without an action to
469  * explore (note: act == NULL is sometimes used as a hack to allow a thread to
470  * yield control without performing any progress; see thrd_join()).
471  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
472  */
473 int ModelChecker::switch_to_master(ModelAction *act)
474 {
475         Thread *old;
476
477         DBG();
478         old = thread_current();
479         set_current_action(act);
480         old->set_state(THREAD_READY);
481         return Thread::swap(old, get_system_context());
482 }