Adding relevant comments for fork based implementation.
[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, class Thread *>),
30         obj_thrd_map(new std::map<void *, std::vector<action_list_t> >()),
31         thrd_last_action(new std::vector<ModelAction *>(1)),
32         node_stack(new NodeStack()),
33         next_backtrack(NULL)
34 {
35 }
36
37 /** @brief Destructor */
38 ModelChecker::~ModelChecker()
39 {
40         std::map<int, class Thread *>::iterator it;
41         for (it = thread_map->begin(); it != thread_map->end(); it++)
42                 delete (*it).second;
43         delete thread_map;
44
45         delete obj_thrd_map;
46         delete action_trace;
47         delete thrd_last_action;
48         delete node_stack;
49         delete scheduler;
50 }
51
52 /**
53  * Restores user program to initial state and resets all model-checker data
54  * structures.
55  */
56 void ModelChecker::reset_to_initial_state()
57 {
58         DEBUG("+++ Resetting to initial state +++\n");
59         node_stack->reset_execution();
60         current_action = NULL;
61         next_thread_id = INITIAL_THREAD_ID;
62         used_sequence_numbers = 0;
63         nextThread = 0;
64         next_backtrack = NULL;
65         snapshotObject->backTrackBeforeStep(0);
66 }
67
68 /** @returns a thread ID for a new Thread */
69 thread_id_t ModelChecker::get_next_id()
70 {
71         return next_thread_id++;
72 }
73
74 /** @returns the number of user threads created during this execution */
75 int ModelChecker::get_num_threads()
76 {
77         return next_thread_id;
78 }
79
80 /** @returns a sequence number for a new ModelAction */
81 int ModelChecker::get_next_seq_num()
82 {
83         return ++used_sequence_numbers;
84 }
85
86 /**
87  * Performs the "scheduling" for the model-checker. That is, it checks if the
88  * model-checker has selected a "next thread to run" and returns it, if
89  * available. This function should be called from the Scheduler routine, where
90  * the Scheduler falls back to a default scheduling routine if needed.
91  *
92  * @return The next thread chosen by the model-checker. If the model-checker
93  * makes no selection, retuns NULL.
94  */
95 Thread * ModelChecker::schedule_next_thread()
96 {
97         Thread *t;
98         if (nextThread == THREAD_ID_T_NONE)
99                 return NULL;
100         t = (*thread_map)[id_to_int(nextThread)];
101
102         ASSERT(t != NULL);
103
104         return t;
105 }
106
107 /**
108  * Choose the next thread in the replay sequence.
109  *
110  * If the replay sequence has reached the 'diverge' point, returns a thread
111  * from the backtracking set. Otherwise, simply returns the next thread in the
112  * sequence that is being replayed.
113  */
114 thread_id_t ModelChecker::get_next_replay_thread()
115 {
116         ModelAction *next;
117         thread_id_t tid;
118
119         /* Have we completed exploring the preselected path? */
120         if (diverge == NULL)
121                 return THREAD_ID_T_NONE;
122
123         /* Else, we are trying to replay an execution */
124         next = node_stack->get_next()->get_action();
125
126         if (next == diverge) {
127                 Node *node = next->get_node();
128
129                 /* Reached divergence point */
130                 DEBUG("*** Divergence point ***\n");
131                 tid = node->get_next_backtrack();
132                 diverge = NULL;
133         } else {
134                 tid = next->get_tid();
135         }
136         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
137         return tid;
138 }
139
140 /**
141  * Queries the model-checker for more executions to explore and, if one
142  * exists, resets the model-checker state to execute a new execution.
143  *
144  * @return If there are more executions to explore, return true. Otherwise,
145  * return false.
146  */
147 bool ModelChecker::next_execution()
148 {
149         DBG();
150
151         num_executions++;
152         print_summary();
153         if ((diverge = model->get_next_backtrack()) == NULL)
154                 return false;
155
156         if (DBG_ENABLED()) {
157                 printf("Next execution will diverge at:\n");
158                 diverge->print();
159         }
160
161         model->reset_to_initial_state();
162         return true;
163 }
164
165 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
166 {
167         action_type type = act->get_type();
168
169         switch (type) {
170                 case THREAD_CREATE:
171                 case THREAD_YIELD:
172                 case THREAD_JOIN:
173                         return NULL;
174                 case ATOMIC_READ:
175                 case ATOMIC_WRITE:
176                 default:
177                         break;
178         }
179         /* linear search: from most recent to oldest */
180         action_list_t::reverse_iterator rit;
181         for (rit = action_trace->rbegin(); rit != action_trace->rend(); rit++) {
182                 ModelAction *prev = *rit;
183                 if (act->is_synchronizing(prev))
184                         return prev;
185         }
186         return NULL;
187 }
188
189 void ModelChecker::set_backtracking(ModelAction *act)
190 {
191         ModelAction *prev;
192         Node *node;
193         Thread *t = get_thread(act->get_tid());
194
195         prev = get_last_conflict(act);
196         if (prev == NULL)
197                 return;
198
199         node = prev->get_node();
200
201         while (!node->is_enabled(t))
202                 t = t->get_parent();
203
204         /* Check if this has been explored already */
205         if (node->has_been_explored(t->get_id()))
206                 return;
207
208         if (!next_backtrack || *prev > *next_backtrack)
209                 next_backtrack = prev;
210
211         /* If this is a new backtracking point, mark the tree */
212         if (!node->set_backtrack(t->get_id()))
213                 return;
214         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
215                         prev->get_tid(), t->get_id());
216         if (DBG_ENABLED()) {
217                 prev->print();
218                 act->print();
219         }
220 }
221
222 ModelAction * ModelChecker::get_next_backtrack()
223 {
224         ModelAction *next = next_backtrack;
225         next_backtrack = NULL;
226         return next;
227 }
228
229 void ModelChecker::check_current_action(void)
230 {
231         Node *currnode;
232
233         ModelAction *curr = this->current_action;
234         ModelAction *tmp;
235         current_action = NULL;
236         if (!curr) {
237                 DEBUG("trying to push NULL action...\n");
238                 return;
239         }
240
241         tmp = node_stack->explore_action(curr);
242         if (tmp) {
243                 /* Discard duplicate ModelAction; use action from NodeStack */
244                 delete curr;
245                 curr = tmp;
246         } else {
247                 /*
248                  * Perform one-time actions when pushing new ModelAction onto
249                  * NodeStack
250                  */
251                 curr->create_cv(get_parent_action(curr->get_tid()));
252                 /* Build may_read_from set */
253                 if (curr->is_read())
254                         build_reads_from_past(curr);
255         }
256
257         /* Assign 'creation' parent */
258         if (curr->get_type() == THREAD_CREATE) {
259                 Thread *th = (Thread *)curr->get_location();
260                 th->set_creation(curr);
261         }
262
263         nextThread = get_next_replay_thread();
264
265         currnode = curr->get_node();
266
267         if (!currnode->backtrack_empty())
268                 if (!next_backtrack || *curr > *next_backtrack)
269                         next_backtrack = curr;
270
271         set_backtracking(curr);
272
273         add_action_to_lists(curr);
274 }
275
276
277 /**
278  * Adds an action to the per-object, per-thread action vector.
279  * @param act is the ModelAction to add.
280  */
281
282 void ModelChecker::add_action_to_lists(ModelAction *act)
283 {
284         action_trace->push_back(act);
285
286         std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
287         if (id_to_int(act->get_tid()) >= (int)vec->size())
288                 vec->resize(next_thread_id);
289         (*vec)[id_to_int(act->get_tid())].push_back(act);
290
291         (*thrd_last_action)[id_to_int(act->get_tid())] = act;
292 }
293
294 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
295 {
296         int nthreads = get_num_threads();
297         if ((int)thrd_last_action->size() < nthreads)
298                 thrd_last_action->resize(nthreads);
299         return (*thrd_last_action)[id_to_int(tid)];
300 }
301
302 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
303 {
304         ModelAction *parent = get_last_action(tid);
305         if (!parent)
306                 parent = get_thread(tid)->get_creation();
307         return parent;
308 }
309
310 /**
311  * Build up an initial set of all past writes that this 'read' action may read
312  * from. This set is determined by the clock vector's "happens before"
313  * relationship.
314  * @param curr is the current ModelAction that we are exploring; it must be a
315  * 'read' operation.
316  */
317 void ModelChecker::build_reads_from_past(ModelAction *curr)
318 {
319         std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
320         unsigned int i;
321
322         ASSERT(curr->is_read());
323
324         for (i = 0; i < thrd_lists->size(); i++) {
325                 action_list_t *list = &(*thrd_lists)[i];
326                 action_list_t::reverse_iterator rit;
327                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
328                         ModelAction *act = *rit;
329
330                         /* Only consider 'write' actions */
331                         if (!act->is_write())
332                                 continue;
333
334                         DEBUG("Adding action to may_read_from:\n");
335                         if (DBG_ENABLED()) {
336                                 act->print();
337                                 curr->print();
338                         }
339                         curr->get_node()->add_read_from(act);
340
341                         /* Include at most one act that "happens before" curr */
342                         if (act->happens_before(curr))
343                                 break;
344                 }
345         }
346 }
347
348 void ModelChecker::print_summary(void)
349 {
350         printf("\n");
351         printf("Number of executions: %d\n", num_executions);
352         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
353
354         scheduler->print();
355
356         print_list(action_trace);
357         printf("\n");
358 }
359
360 void ModelChecker::print_list(action_list_t *list)
361 {
362         action_list_t::iterator it;
363
364         printf("---------------------------------------------------------------------\n");
365         printf("Trace:\n");
366
367         for (it = list->begin(); it != list->end(); it++) {
368                 (*it)->print();
369         }
370         printf("---------------------------------------------------------------------\n");
371 }
372
373 int ModelChecker::add_thread(Thread *t)
374 {
375         (*thread_map)[id_to_int(t->get_id())] = t;
376         scheduler->add_thread(t);
377         return 0;
378 }
379
380 void ModelChecker::remove_thread(Thread *t)
381 {
382         scheduler->remove_thread(t);
383 }
384
385 int ModelChecker::switch_to_master(ModelAction *act)
386 {
387         Thread *old;
388
389         DBG();
390         old = thread_current();
391         set_current_action(act);
392         old->set_state(THREAD_READY);
393         return Thread::swap(old, get_system_context());
394 }