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