model: add per-object action lists (obj_map)
[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 *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::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()->get_parent();
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         /* Cache the latest backtracking point */
209         if (!next_backtrack || *prev > *next_backtrack)
210                 next_backtrack = prev;
211
212         /* If this is a new backtracking point, mark the tree */
213         if (!node->set_backtrack(t->get_id()))
214                 return;
215         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
216                         prev->get_tid(), t->get_id());
217         if (DBG_ENABLED()) {
218                 prev->print();
219                 act->print();
220         }
221 }
222
223 ModelAction * ModelChecker::get_next_backtrack()
224 {
225         ModelAction *next = next_backtrack;
226         next_backtrack = NULL;
227         return next;
228 }
229
230 void ModelChecker::check_current_action(void)
231 {
232         Node *currnode;
233
234         ModelAction *curr = this->current_action;
235         ModelAction *tmp;
236         current_action = NULL;
237         if (!curr) {
238                 DEBUG("trying to push NULL action...\n");
239                 return;
240         }
241
242         tmp = node_stack->explore_action(curr);
243         if (tmp) {
244                 /* Discard duplicate ModelAction; use action from NodeStack */
245                 delete curr;
246                 curr = tmp;
247         } else {
248                 /*
249                  * Perform one-time actions when pushing new ModelAction onto
250                  * NodeStack
251                  */
252                 curr->create_cv(get_parent_action(curr->get_tid()));
253                 /* Build may_read_from set */
254                 if (curr->is_read())
255                         build_reads_from_past(curr);
256         }
257
258         /* Assign 'creation' parent */
259         if (curr->get_type() == THREAD_CREATE) {
260                 Thread *th = (Thread *)curr->get_location();
261                 th->set_creation(curr);
262         }
263
264         nextThread = get_next_replay_thread();
265
266         currnode = curr->get_node()->get_parent();
267
268         if (!currnode->backtrack_empty())
269                 if (!next_backtrack || *curr > *next_backtrack)
270                         next_backtrack = curr;
271
272         set_backtracking(curr);
273
274         add_action_to_lists(curr);
275
276         /* Assign reads_from values */
277         /* TODO: perform release/acquire synchronization here; include
278          * reads_from as ModelAction member? */
279         Thread *th = get_thread(curr->get_tid());
280         int value = VALUE_NONE;
281         if (curr->is_read()) {
282                 const ModelAction *reads_from = curr->get_node()->get_next_read_from();
283                 value = reads_from->get_value();
284                 /* Assign reads_from, perform release/acquire synchronization */
285                 curr->read_from(reads_from);
286         }
287         th->set_return_value(value);
288 }
289
290 /**
291  * Performs various bookkeeping operations for the current ModelAction. For
292  * instance, adds action to the per-object, per-thread action vector and to the
293  * action trace list of all thread actions.
294  *
295  * @param act is the ModelAction to add.
296  */
297 void ModelChecker::add_action_to_lists(ModelAction *act)
298 {
299         int tid = id_to_int(act->get_tid());
300         action_trace->push_back(act);
301
302         (*obj_map)[act->get_location()].push_back(act);
303
304         std::vector<action_list_t> *vec = &(*obj_thrd_map)[act->get_location()];
305         if (tid >= (int)vec->size())
306                 vec->resize(next_thread_id);
307         (*vec)[tid].push_back(act);
308
309         if ((int)thrd_last_action->size() <= tid)
310                 thrd_last_action->resize(get_num_threads());
311         (*thrd_last_action)[tid] = act;
312 }
313
314 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
315 {
316         int nthreads = get_num_threads();
317         if ((int)thrd_last_action->size() < nthreads)
318                 thrd_last_action->resize(nthreads);
319         return (*thrd_last_action)[id_to_int(tid)];
320 }
321
322 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
323 {
324         ModelAction *parent = get_last_action(tid);
325         if (!parent)
326                 parent = get_thread(tid)->get_creation();
327         return parent;
328 }
329
330 ClockVector * ModelChecker::get_cv(thread_id_t tid) {
331         return get_parent_action(tid)->get_cv();
332 }
333
334 /**
335  * Build up an initial set of all past writes that this 'read' action may read
336  * from. This set is determined by the clock vector's "happens before"
337  * relationship.
338  * @param curr is the current ModelAction that we are exploring; it must be a
339  * 'read' operation.
340  */
341 void ModelChecker::build_reads_from_past(ModelAction *curr)
342 {
343         std::vector<action_list_t> *thrd_lists = &(*obj_thrd_map)[curr->get_location()];
344         unsigned int i;
345
346         ASSERT(curr->is_read());
347
348         /* Track whether this object has been initialized */
349         bool initialized = false;
350
351         for (i = 0; i < thrd_lists->size(); i++) {
352                 action_list_t *list = &(*thrd_lists)[i];
353                 action_list_t::reverse_iterator rit;
354                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
355                         ModelAction *act = *rit;
356
357                         /* Only consider 'write' actions */
358                         if (!act->is_write())
359                                 continue;
360
361                         DEBUG("Adding action to may_read_from:\n");
362                         if (DBG_ENABLED()) {
363                                 act->print();
364                                 curr->print();
365                         }
366                         curr->get_node()->add_read_from(act);
367
368                         /* Include at most one act per-thread that "happens before" curr */
369                         if (act->happens_before(curr)) {
370                                 initialized = true;
371                                 break;
372                         }
373                 }
374         }
375
376         if (!initialized) {
377                 /* TODO: need a more informative way of reporting errors */
378                 printf("ERROR: may read from uninitialized atomic\n");
379         }
380
381         if (DBG_ENABLED() || !initialized) {
382                 printf("Reached read action:\n");
383                 curr->print();
384                 printf("Printing may_read_from\n");
385                 curr->get_node()->print_may_read_from();
386                 printf("End printing may_read_from\n");
387         }
388
389         ASSERT(initialized);
390 }
391
392 static void print_list(action_list_t *list)
393 {
394         action_list_t::iterator it;
395
396         printf("---------------------------------------------------------------------\n");
397         printf("Trace:\n");
398
399         for (it = list->begin(); it != list->end(); it++) {
400                 (*it)->print();
401         }
402         printf("---------------------------------------------------------------------\n");
403 }
404
405 void ModelChecker::print_summary(void)
406 {
407         printf("\n");
408         printf("Number of executions: %d\n", num_executions);
409         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
410
411         scheduler->print();
412
413         print_list(action_trace);
414         printf("\n");
415 }
416
417 int ModelChecker::add_thread(Thread *t)
418 {
419         (*thread_map)[id_to_int(t->get_id())] = t;
420         scheduler->add_thread(t);
421         return 0;
422 }
423
424 void ModelChecker::remove_thread(Thread *t)
425 {
426         scheduler->remove_thread(t);
427 }
428
429 int ModelChecker::switch_to_master(ModelAction *act)
430 {
431         Thread *old;
432
433         DBG();
434         old = thread_current();
435         set_current_action(act);
436         old->set_state(THREAD_READY);
437         return Thread::swap(old, get_system_context());
438 }