model: add ModelChecker::get_last_seq_cst()
[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 *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         /* Track whether this object has been initialized */
367         bool initialized = false;
368
369         for (i = 0; i < thrd_lists->size(); i++) {
370                 action_list_t *list = &(*thrd_lists)[i];
371                 action_list_t::reverse_iterator rit;
372                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
373                         ModelAction *act = *rit;
374
375                         /* Only consider 'write' actions */
376                         if (!act->is_write())
377                                 continue;
378
379                         DEBUG("Adding action to may_read_from:\n");
380                         if (DBG_ENABLED()) {
381                                 act->print();
382                                 curr->print();
383                         }
384                         curr->get_node()->add_read_from(act);
385
386                         /* Include at most one act per-thread that "happens before" curr */
387                         if (act->happens_before(curr)) {
388                                 initialized = true;
389                                 break;
390                         }
391                 }
392         }
393
394         if (!initialized) {
395                 /* TODO: need a more informative way of reporting errors */
396                 printf("ERROR: may read from uninitialized atomic\n");
397         }
398
399         if (DBG_ENABLED() || !initialized) {
400                 printf("Reached read action:\n");
401                 curr->print();
402                 printf("Printing may_read_from\n");
403                 curr->get_node()->print_may_read_from();
404                 printf("End printing may_read_from\n");
405         }
406
407         ASSERT(initialized);
408 }
409
410 static void print_list(action_list_t *list)
411 {
412         action_list_t::iterator it;
413
414         printf("---------------------------------------------------------------------\n");
415         printf("Trace:\n");
416
417         for (it = list->begin(); it != list->end(); it++) {
418                 (*it)->print();
419         }
420         printf("---------------------------------------------------------------------\n");
421 }
422
423 void ModelChecker::print_summary(void)
424 {
425         printf("\n");
426         printf("Number of executions: %d\n", num_executions);
427         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
428
429         scheduler->print();
430
431         print_list(action_trace);
432         printf("\n");
433 }
434
435 int ModelChecker::add_thread(Thread *t)
436 {
437         (*thread_map)[id_to_int(t->get_id())] = t;
438         scheduler->add_thread(t);
439         return 0;
440 }
441
442 void ModelChecker::remove_thread(Thread *t)
443 {
444         scheduler->remove_thread(t);
445 }
446
447 int ModelChecker::switch_to_master(ModelAction *act)
448 {
449         Thread *old;
450
451         DBG();
452         old = thread_current();
453         set_current_action(act);
454         old->set_state(THREAD_READY);
455         return Thread::swap(old, get_system_context());
456 }