fix merge bug
[c11tester.git] / model.cc
1 #include <stdio.h>
2 #include <algorithm>
3
4 #include "model.h"
5 #include "action.h"
6 #include "nodestack.h"
7 #include "schedule.h"
8 #include "snapshot-interface.h"
9 #include "common.h"
10 #include "clockvector.h"
11 #include "cyclegraph.h"
12 #include "promise.h"
13 #include "datarace.h"
14
15 #define INITIAL_THREAD_ID       0
16
17 ModelChecker *model;
18
19 /** @brief Constructor */
20 ModelChecker::ModelChecker(struct model_params params) :
21         /* Initialize default scheduler */
22         scheduler(new Scheduler()),
23         num_executions(0),
24         num_feasible_executions(0),
25         params(params),
26         diverge(NULL),
27         action_trace(new action_list_t()),
28         thread_map(new HashTable<int, Thread *, int>()),
29         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
30         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
31         promises(new std::vector<Promise *>()),
32         futurevalues(new std::vector<struct PendingFutureValue>()),
33         lazy_sync_with_release(new HashTable<void *, action_list_t, uintptr_t, 4>()),
34         thrd_last_action(new std::vector<ModelAction *>(1)),
35         node_stack(new NodeStack()),
36         mo_graph(new CycleGraph()),
37         failed_promise(false),
38         too_many_reads(false),
39         asserted(false)
40 {
41         /* Allocate this "size" on the snapshotting heap */
42         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
43         /* First thread created will have id INITIAL_THREAD_ID */
44         priv->next_thread_id = INITIAL_THREAD_ID;
45
46         lazy_sync_size = &priv->lazy_sync_size;
47 }
48
49 /** @brief Destructor */
50 ModelChecker::~ModelChecker()
51 {
52         for (int i = 0; i < get_num_threads(); i++)
53                 delete thread_map->get(i);
54         delete thread_map;
55
56         delete obj_thrd_map;
57         delete obj_map;
58         delete action_trace;
59
60         for (unsigned int i = 0; i < promises->size(); i++)
61                 delete (*promises)[i];
62         delete promises;
63
64         delete lazy_sync_with_release;
65
66         delete thrd_last_action;
67         delete node_stack;
68         delete scheduler;
69         delete mo_graph;
70 }
71
72 /**
73  * Restores user program to initial state and resets all model-checker data
74  * structures.
75  */
76 void ModelChecker::reset_to_initial_state()
77 {
78         DEBUG("+++ Resetting to initial state +++\n");
79         node_stack->reset_execution();
80         failed_promise = false;
81         too_many_reads = false;
82         reset_asserted();
83         snapshotObject->backTrackBeforeStep(0);
84 }
85
86 /** @returns a thread ID for a new Thread */
87 thread_id_t ModelChecker::get_next_id()
88 {
89         return priv->next_thread_id++;
90 }
91
92 /** @returns the number of user threads created during this execution */
93 int ModelChecker::get_num_threads()
94 {
95         return priv->next_thread_id;
96 }
97
98 /** @returns a sequence number for a new ModelAction */
99 modelclock_t ModelChecker::get_next_seq_num()
100 {
101         return ++priv->used_sequence_numbers;
102 }
103
104 /**
105  * @brief Choose the next thread to execute.
106  *
107  * This function chooses the next thread that should execute. It can force the
108  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
109  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
110  * The model-checker may have no preference regarding the next thread (i.e.,
111  * when exploring a new execution ordering), in which case this will return
112  * NULL.
113  * @param curr The current ModelAction. This action might guide the choice of
114  * next thread.
115  * @return The next thread to run. If the model-checker has no preference, NULL.
116  */
117 Thread * ModelChecker::get_next_thread(ModelAction *curr)
118 {
119         thread_id_t tid;
120
121         /* Do not split atomic actions. */
122         if (curr->is_rmwr())
123                 return thread_current();
124         /* The THREAD_CREATE action points to the created Thread */
125         else if (curr->get_type() == THREAD_CREATE)
126                 return (Thread *)curr->get_location();
127
128         /* Have we completed exploring the preselected path? */
129         if (diverge == NULL)
130                 return NULL;
131
132         /* Else, we are trying to replay an execution */
133         ModelAction *next = node_stack->get_next()->get_action();
134
135         if (next == diverge) {
136                 Node *nextnode = next->get_node();
137                 /* Reached divergence point */
138                 if (nextnode->increment_promise()) {
139                         /* The next node will try to satisfy a different set of promises. */
140                         tid = next->get_tid();
141                         node_stack->pop_restofstack(2);
142                 } else if (nextnode->increment_read_from()) {
143                         /* The next node will read from a different value. */
144                         tid = next->get_tid();
145                         node_stack->pop_restofstack(2);
146                 } else if (nextnode->increment_future_value()) {
147                         /* The next node will try to read from a different future value. */
148                         tid = next->get_tid();
149                         node_stack->pop_restofstack(2);
150                 } else {
151                         /* Make a different thread execute for next step */
152                         Node *node = nextnode->get_parent();
153                         tid = node->get_next_backtrack();
154                         node_stack->pop_restofstack(1);
155                 }
156                 DEBUG("*** Divergence point ***\n");
157                 diverge = NULL;
158         } else {
159                 tid = next->get_tid();
160         }
161         DEBUG("*** ModelChecker chose next thread = %d ***\n", tid);
162         ASSERT(tid != THREAD_ID_T_NONE);
163         return thread_map->get(id_to_int(tid));
164 }
165
166 /**
167  * Queries the model-checker for more executions to explore and, if one
168  * exists, resets the model-checker state to execute a new execution.
169  *
170  * @return If there are more executions to explore, return true. Otherwise,
171  * return false.
172  */
173 bool ModelChecker::next_execution()
174 {
175         DBG();
176
177         num_executions++;
178         if (isfinalfeasible())
179                 num_feasible_executions++;
180
181         if (isfinalfeasible() || DBG_ENABLED())
182                 print_summary();
183
184         if ((diverge = get_next_backtrack()) == NULL)
185                 return false;
186
187         if (DBG_ENABLED()) {
188                 printf("Next execution will diverge at:\n");
189                 diverge->print();
190         }
191
192         reset_to_initial_state();
193         return true;
194 }
195
196 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
197 {
198         action_type type = act->get_type();
199
200         if (type==ATOMIC_READ||type==ATOMIC_WRITE||type==ATOMIC_RMW) {
201                 /* linear search: from most recent to oldest */
202                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
203                 action_list_t::reverse_iterator rit;
204                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
205                         ModelAction *prev = *rit;
206                         if (act->is_synchronizing(prev))
207                                 return prev;
208                 }
209         } else if (type==ATOMIC_LOCK||type==ATOMIC_TRYLOCK) {
210                 /* linear search: from most recent to oldest */
211                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
212                 action_list_t::reverse_iterator rit;
213                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
214                         ModelAction *prev = *rit;
215                         if (prev->is_success_lock())
216                                 return prev;
217                 }
218         } else if (type==ATOMIC_UNLOCK) {
219                 /* linear search: from most recent to oldest */
220                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
221                 action_list_t::reverse_iterator rit;
222                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
223                         ModelAction *prev = *rit;
224                         if (prev->is_failed_trylock())
225                                 return prev;
226                 }
227         }
228         return NULL;
229 }
230
231 void ModelChecker::set_backtracking(ModelAction *act)
232 {
233         ModelAction *prev;
234         Node *node;
235         Thread *t = get_thread(act);
236
237         prev = get_last_conflict(act);
238         if (prev == NULL)
239                 return;
240
241         node = prev->get_node()->get_parent();
242
243         while (!node->is_enabled(t))
244                 t = t->get_parent();
245
246         /* Check if this has been explored already */
247         if (node->has_been_explored(t->get_id()))
248                 return;
249
250         /* Cache the latest backtracking point */
251         if (!priv->next_backtrack || *prev > *priv->next_backtrack)
252                 priv->next_backtrack = prev;
253
254         /* If this is a new backtracking point, mark the tree */
255         if (!node->set_backtrack(t->get_id()))
256                 return;
257         DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
258                         prev->get_tid(), t->get_id());
259         if (DBG_ENABLED()) {
260                 prev->print();
261                 act->print();
262         }
263 }
264
265 /**
266  * Returns last backtracking point. The model checker will explore a different
267  * path for this point in the next execution.
268  * @return The ModelAction at which the next execution should diverge.
269  */
270 ModelAction * ModelChecker::get_next_backtrack()
271 {
272         ModelAction *next = priv->next_backtrack;
273         priv->next_backtrack = NULL;
274         return next;
275 }
276
277 /**
278  * Processes a read or rmw model action.
279  * @param curr is the read model action to process.
280  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
281  * @return True if processing this read updates the mo_graph.
282  */
283 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
284 {
285         uint64_t value;
286         bool updated = false;
287         while (true) {
288                 const ModelAction *reads_from = curr->get_node()->get_read_from();
289                 if (reads_from != NULL) {
290                         mo_graph->startChanges();
291
292                         value = reads_from->get_value();
293                         bool r_status = false;
294
295                         if (!second_part_of_rmw) {
296                                 check_recency(curr);
297                                 r_status = r_modification_order(curr, reads_from);
298                         }
299
300
301                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
302                                 mo_graph->rollbackChanges();
303                                 too_many_reads = false;
304                                 continue;
305                         }
306
307                         curr->read_from(reads_from);
308                         mo_graph->commitChanges();
309                         updated |= r_status;
310                 } else if (!second_part_of_rmw) {
311                         /* Read from future value */
312                         value = curr->get_node()->get_future_value();
313                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
314                         curr->read_from(NULL);
315                         Promise *valuepromise = new Promise(curr, value, expiration);
316                         promises->push_back(valuepromise);
317                 }
318                 get_thread(curr)->set_return_value(value);
319                 return updated;
320         }
321 }
322
323 /**
324  * Process a write ModelAction
325  * @param curr The ModelAction to process
326  * @return True if the mo_graph was updated or promises were resolved
327  */
328 bool ModelChecker::process_write(ModelAction *curr)
329 {
330         bool updated_mod_order = w_modification_order(curr);
331         bool updated_promises = resolve_promises(curr);
332
333         if (promises->size() == 0) {
334                 for (unsigned int i = 0; i<futurevalues->size(); i++) {
335                         struct PendingFutureValue pfv = (*futurevalues)[i];
336                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
337                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
338                                 priv->next_backtrack = pfv.act;
339                 }
340                 futurevalues->resize(0);
341         }
342
343         mo_graph->commitChanges();
344         get_thread(curr)->set_return_value(VALUE_NONE);
345         return updated_mod_order || updated_promises;
346 }
347
348 /**
349  * Initialize the current action by performing one or more of the following
350  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
351  * in the NodeStack, manipulating backtracking sets, allocating and
352  * initializing clock vectors, and computing the promises to fulfill.
353  *
354  * @param curr The current action, as passed from the user context; may be
355  * freed/invalidated after the execution of this function
356  * @return The current action, as processed by the ModelChecker. Is only the
357  * same as the parameter @a curr if this is a newly-explored action.
358  */
359 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
360 {
361         ModelAction *newcurr;
362
363         if (curr->is_rmwc() || curr->is_rmw()) {
364                 newcurr = process_rmw(curr);
365                 delete curr;
366                 compute_promises(newcurr);
367                 return newcurr;
368         }
369
370         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
371         if (newcurr) {
372                 /* First restore type and order in case of RMW operation */
373                 if (curr->is_rmwr())
374                         newcurr->copy_typeandorder(curr);
375
376                 ASSERT(curr->get_location()==newcurr->get_location());
377                 /* Discard duplicate ModelAction; use action from NodeStack */
378                 delete curr;
379
380                 /* If we have diverged, we need to reset the clock vector. */
381                 if (diverge == NULL)
382                         newcurr->create_cv(get_parent_action(newcurr->get_tid()));
383         } else {
384                 newcurr = curr;
385                 /*
386                  * Perform one-time actions when pushing new ModelAction onto
387                  * NodeStack
388                  */
389                 curr->create_cv(get_parent_action(curr->get_tid()));
390                 if (curr->is_write())
391                         compute_promises(curr);
392         }
393         return newcurr;
394 }
395
396 /**
397  * This is the heart of the model checker routine. It performs model-checking
398  * actions corresponding to a given "current action." Among other processes, it
399  * calculates reads-from relationships, updates synchronization clock vectors,
400  * forms a memory_order constraints graph, and handles replay/backtrack
401  * execution when running permutations of previously-observed executions.
402  *
403  * @param curr The current action to process
404  * @return The next Thread that must be executed. May be NULL if ModelChecker
405  * makes no choice (e.g., according to replay execution, combining RMW actions,
406  * etc.)
407  */
408 Thread * ModelChecker::check_current_action(ModelAction *curr)
409 {
410         ASSERT(curr);
411
412         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
413
414         ModelAction *newcurr = initialize_curr_action(curr);
415
416         /* Add the action to lists before any other model-checking tasks */
417         if (!second_part_of_rmw)
418                 add_action_to_lists(newcurr);
419
420         /* Build may_read_from set for newly-created actions */
421         if (curr == newcurr && curr->is_read())
422                 build_reads_from_past(curr);
423         curr = newcurr;
424
425         /* Thread specific actions */
426         switch (curr->get_type()) {
427         case THREAD_CREATE: {
428                 Thread *th = (Thread *)curr->get_location();
429                 th->set_creation(curr);
430                 break;
431         }
432         case THREAD_JOIN: {
433                 Thread *waiting, *blocking;
434                 waiting = get_thread(curr);
435                 blocking = (Thread *)curr->get_location();
436                 if (!blocking->is_complete()) {
437                         blocking->push_wait_list(curr);
438                         scheduler->sleep(waiting);
439                 } else {
440                         do_complete_join(curr);
441                 }
442                 break;
443         }
444         case THREAD_FINISH: {
445                 Thread *th = get_thread(curr);
446                 while (!th->wait_list_empty()) {
447                         ModelAction *act = th->pop_wait_list();
448                         Thread *wake = get_thread(act);
449                         scheduler->wake(wake);
450                         do_complete_join(act);
451                 }
452                 th->complete();
453                 break;
454         }
455         case THREAD_START: {
456                 check_promises(NULL, curr->get_cv());
457                 break;
458         }
459         default:
460                 break;
461         }
462
463         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
464
465         while (!work_queue.empty()) {
466                 WorkQueueEntry work = work_queue.front();
467                 work_queue.pop_front();
468
469                 switch (work.type) {
470                 case WORK_CHECK_CURR_ACTION: {
471                         ModelAction *act = work.action;
472                         bool updated = false;
473                         if (act->is_read() && process_read(act, second_part_of_rmw))
474                                 updated = true;
475
476                         if (act->is_write() && process_write(act))
477                                 updated = true;
478
479                         if (updated)
480                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
481                         break;
482                 }
483                 case WORK_CHECK_RELEASE_SEQ:
484                         resolve_release_sequences(work.location, &work_queue);
485                         break;
486                 case WORK_CHECK_MO_EDGES: {
487                         /** @todo Complete verification of work_queue */
488                         ModelAction *act = work.action;
489                         bool updated = false;
490
491                         if (act->is_read()) {
492                                 if (r_modification_order(act, act->get_reads_from()))
493                                         updated = true;
494                         }
495                         if (act->is_write()) {
496                                 if (w_modification_order(act))
497                                         updated = true;
498                         }
499
500                         if (updated)
501                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
502                         break;
503                 }
504                 default:
505                         ASSERT(false);
506                         break;
507                 }
508         }
509
510         check_curr_backtracking(curr);
511
512         set_backtracking(curr);
513
514         return get_next_thread(curr);
515 }
516
517 /**
518  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
519  * operation from the Thread it is joining with. Must be called after the
520  * completion of the Thread in question.
521  * @param join The THREAD_JOIN action
522  */
523 void ModelChecker::do_complete_join(ModelAction *join)
524 {
525         Thread *blocking = (Thread *)join->get_location();
526         ModelAction *act = get_last_action(blocking->get_id());
527         join->synchronize_with(act);
528 }
529
530 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
531         Node *currnode = curr->get_node();
532         Node *parnode = currnode->get_parent();
533
534         if ((!parnode->backtrack_empty() ||
535                          !currnode->read_from_empty() ||
536                          !currnode->future_value_empty() ||
537                          !currnode->promise_empty())
538                         && (!priv->next_backtrack ||
539                                         *curr > *priv->next_backtrack)) {
540                 priv->next_backtrack = curr;
541         }
542 }
543
544 bool ModelChecker::promises_expired() {
545         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
546                 Promise *promise = (*promises)[promise_index];
547                 if (promise->get_expiration()<priv->used_sequence_numbers) {
548                         return true;
549                 }
550         }
551         return false;
552 }
553
554 /** @returns whether the current partial trace must be a prefix of a
555  * feasible trace. */
556 bool ModelChecker::isfeasibleprefix() {
557         return promises->size() == 0 && *lazy_sync_size == 0;
558 }
559
560 /** @returns whether the current partial trace is feasible. */
561 bool ModelChecker::isfeasible() {
562         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
563 }
564
565 /** @returns whether the current partial trace is feasible other than
566  * multiple RMW reading from the same store. */
567 bool ModelChecker::isfeasibleotherthanRMW() {
568         if (DBG_ENABLED()) {
569                 if (mo_graph->checkForCycles())
570                         DEBUG("Infeasible: modification order cycles\n");
571                 if (failed_promise)
572                         DEBUG("Infeasible: failed promise\n");
573                 if (too_many_reads)
574                         DEBUG("Infeasible: too many reads\n");
575                 if (promises_expired())
576                         DEBUG("Infeasible: promises expired\n");
577         }
578         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !promises_expired();
579 }
580
581 /** Returns whether the current completed trace is feasible. */
582 bool ModelChecker::isfinalfeasible() {
583         if (DBG_ENABLED() && promises->size() != 0)
584                 DEBUG("Infeasible: unrevolved promises\n");
585
586         return isfeasible() && promises->size() == 0;
587 }
588
589 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
590 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
591         int tid = id_to_int(act->get_tid());
592         ModelAction *lastread = get_last_action(tid);
593         lastread->process_rmw(act);
594         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
595                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
596                 mo_graph->commitChanges();
597         }
598         return lastread;
599 }
600
601 /**
602  * Checks whether a thread has read from the same write for too many times
603  * without seeing the effects of a later write.
604  *
605  * Basic idea:
606  * 1) there must a different write that we could read from that would satisfy the modification order,
607  * 2) we must have read from the same value in excess of maxreads times, and
608  * 3) that other write must have been in the reads_from set for maxreads times.
609  *
610  * If so, we decide that the execution is no longer feasible.
611  */
612 void ModelChecker::check_recency(ModelAction *curr) {
613         if (params.maxreads != 0) {
614                 if (curr->get_node()->get_read_from_size() <= 1)
615                         return;
616
617                 //Must make sure that execution is currently feasible...  We could
618                 //accidentally clear by rolling back
619                 if (!isfeasible())
620                         return;
621
622                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
623                 int tid = id_to_int(curr->get_tid());
624
625                 /* Skip checks */
626                 if ((int)thrd_lists->size() <= tid)
627                         return;
628
629                 action_list_t *list = &(*thrd_lists)[tid];
630
631                 action_list_t::reverse_iterator rit = list->rbegin();
632                 /* Skip past curr */
633                 for (; (*rit) != curr; rit++)
634                         ;
635                 /* go past curr now */
636                 rit++;
637
638                 action_list_t::reverse_iterator ritcopy = rit;
639                 //See if we have enough reads from the same value
640                 int count = 0;
641                 for (; count < params.maxreads; rit++,count++) {
642                         if (rit==list->rend())
643                                 return;
644                         ModelAction *act = *rit;
645                         if (!act->is_read())
646                                 return;
647                         if (act->get_reads_from() != curr->get_reads_from())
648                                 return;
649                         if (act->get_node()->get_read_from_size() <= 1)
650                                 return;
651                 }
652
653                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
654                         //Get write
655                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
656                         //Need a different write
657                         if (write==curr->get_reads_from())
658                                 continue;
659
660                         /* Test to see whether this is a feasible write to read from*/
661                         mo_graph->startChanges();
662                         r_modification_order(curr, write);
663                         bool feasiblereadfrom = isfeasible();
664                         mo_graph->rollbackChanges();
665
666                         if (!feasiblereadfrom)
667                                 continue;
668                         rit = ritcopy;
669
670                         bool feasiblewrite = true;
671                         //new we need to see if this write works for everyone
672
673                         for (int loop = count; loop>0; loop--,rit++) {
674                                 ModelAction *act=*rit;
675                                 bool foundvalue = false;
676                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
677                                         if (act->get_node()->get_read_from_at(i)==write) {
678                                                 foundvalue = true;
679                                                 break;
680                                         }
681                                 }
682                                 if (!foundvalue) {
683                                         feasiblewrite = false;
684                                         break;
685                                 }
686                         }
687                         if (feasiblewrite) {
688                                 too_many_reads = true;
689                                 return;
690                         }
691                 }
692         }
693 }
694
695 /**
696  * Updates the mo_graph with the constraints imposed from the current
697  * read.  
698  *
699  * Basic idea is the following: Go through each other thread and find
700  * the lastest action that happened before our read.  Two cases:
701  *
702  * (1) The action is a write => that write must either occur before
703  * the write we read from or be the write we read from.
704  *
705  * (2) The action is a read => the write that that action read from
706  * must occur before the write we read from or be the same write.
707  *
708  * @param curr The current action. Must be a read.
709  * @param rf The action that curr reads from. Must be a write.
710  * @return True if modification order edges were added; false otherwise
711  */
712 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
713 {
714         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
715         unsigned int i;
716         bool added = false;
717         ASSERT(curr->is_read());
718
719         /* Iterate over all threads */
720         for (i = 0; i < thrd_lists->size(); i++) {
721                 /* Iterate over actions in thread, starting from most recent */
722                 action_list_t *list = &(*thrd_lists)[i];
723                 action_list_t::reverse_iterator rit;
724                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
725                         ModelAction *act = *rit;
726
727                         /*
728                          * Include at most one act per-thread that "happens
729                          * before" curr. Don't consider reflexively.
730                          */
731                         if (act->happens_before(curr) && act != curr) {
732                                 if (act->is_write()) {
733                                         if (rf != act) {
734                                                 mo_graph->addEdge(act, rf);
735                                                 added = true;
736                                         }
737                                 } else {
738                                         const ModelAction *prevreadfrom = act->get_reads_from();
739                                         if (prevreadfrom != NULL && rf != prevreadfrom) {
740                                                 mo_graph->addEdge(prevreadfrom, rf);
741                                                 added = true;
742                                         }
743                                 }
744                                 break;
745                         }
746                 }
747         }
748
749         return added;
750 }
751
752 /** This method fixes up the modification order when we resolve a
753  *  promises.  The basic problem is that actions that occur after the
754  *  read curr could not property add items to the modification order
755  *  for our read.
756  *  
757  *  So for each thread, we find the earliest item that happens after
758  *  the read curr.  This is the item we have to fix up with additional
759  *  constraints.  If that action is write, we add a MO edge between
760  *  the Action rf and that action.  If the action is a read, we add a
761  *  MO edge between the Action rf, and whatever the read accessed.
762  *
763  * @param curr is the read ModelAction that we are fixing up MO edges for.
764  * @param rf is the write ModelAction that curr reads from.
765  *
766  */
767
768 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
769 {
770         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
771         unsigned int i;
772         ASSERT(curr->is_read());
773
774         /* Iterate over all threads */
775         for (i = 0; i < thrd_lists->size(); i++) {
776                 /* Iterate over actions in thread, starting from most recent */
777                 action_list_t *list = &(*thrd_lists)[i];
778                 action_list_t::reverse_iterator rit;
779                 ModelAction *lastact = NULL;
780
781                 /* Find last action that happens after curr */
782                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
783                         ModelAction *act = *rit;
784                         if (curr->happens_before(act)) {
785                                 lastact = act;
786                         } else
787                                 break;
788                 }
789
790                         /* Include at most one act per-thread that "happens before" curr */
791                 if (lastact != NULL) {
792                         if (lastact->is_read()) {
793                                 const ModelAction *postreadfrom = lastact->get_reads_from();
794                                 if (postreadfrom != NULL&&rf != postreadfrom)
795                                         mo_graph->addEdge(rf, postreadfrom);
796                         } else if (rf != lastact) {
797                                 mo_graph->addEdge(rf, lastact);
798                         }
799                         break;
800                 }
801         }
802 }
803
804 /**
805  * Updates the mo_graph with the constraints imposed from the current write.
806  *
807  * Basic idea is the following: Go through each other thread and find
808  * the lastest action that happened before our write.  Two cases:
809  *
810  * (1) The action is a write => that write must occur before
811  * the current write
812  *
813  * (2) The action is a read => the write that that action read from
814  * must occur before the current write.
815  *
816  * This method also handles two other issues:
817  *
818  * (I) Sequential Consistency: Making sure that if the current write is
819  * seq_cst, that it occurs after the previous seq_cst write.
820  *
821  * (II) Sending the write back to non-synchronizing reads.
822  *
823  * @param curr The current action. Must be a write.
824  * @return True if modification order edges were added; false otherwise
825  */
826 bool ModelChecker::w_modification_order(ModelAction *curr)
827 {
828         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
829         unsigned int i;
830         bool added = false;
831         ASSERT(curr->is_write());
832
833         if (curr->is_seqcst()) {
834                 /* We have to at least see the last sequentially consistent write,
835                          so we are initialized. */
836                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
837                 if (last_seq_cst != NULL) {
838                         mo_graph->addEdge(last_seq_cst, curr);
839                         added = true;
840                 }
841         }
842
843         /* Iterate over all threads */
844         for (i = 0; i < thrd_lists->size(); i++) {
845                 /* Iterate over actions in thread, starting from most recent */
846                 action_list_t *list = &(*thrd_lists)[i];
847                 action_list_t::reverse_iterator rit;
848                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
849                         ModelAction *act = *rit;
850                         if (act == curr) {
851                                 /*
852                                  * If RMW, we already have all relevant edges,
853                                  * so just skip to next thread.
854                                  * If normal write, we need to look at earlier
855                                  * actions, so continue processing list.
856                                  */
857                                 if (curr->is_rmw())
858                                         break;
859                                 else
860                                         continue;
861                         }
862
863                         /*
864                          * Include at most one act per-thread that "happens
865                          * before" curr
866                          */
867                         if (act->happens_before(curr)) {
868                                 /*
869                                  * Note: if act is RMW, just add edge:
870                                  *   act --mo--> curr
871                                  * The following edge should be handled elsewhere:
872                                  *   readfrom(act) --mo--> act
873                                  */
874                                 if (act->is_write())
875                                         mo_graph->addEdge(act, curr);
876                                 else if (act->is_read() && act->get_reads_from() != NULL)
877                                         mo_graph->addEdge(act->get_reads_from(), curr);
878                                 added = true;
879                                 break;
880                         } else if (act->is_read() && !act->is_synchronizing(curr) &&
881                                                      !act->same_thread(curr)) {
882                                 /* We have an action that:
883                                    (1) did not happen before us
884                                    (2) is a read and we are a write
885                                    (3) cannot synchronize with us
886                                    (4) is in a different thread
887                                    =>
888                                    that read could potentially read from our write.
889                                  */
890                                 if (thin_air_constraint_may_allow(curr, act)) {
891                                         if (isfeasible() ||
892                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from()==act->get_reads_from() && isfeasibleotherthanRMW())) {
893                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
894                                                 futurevalues->push_back(pfv);
895                                         }
896                                 }
897                         }
898                 }
899         }
900
901         return added;
902 }
903
904 /** Arbitrary reads from the future are not allowed.  Section 29.3
905  * part 9 places some constraints.  This method checks one result of constraint
906  * constraint.  Others require compiler support. */
907
908 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
909         if (!writer->is_rmw())
910                 return true;
911
912         if (!reader->is_rmw())
913                 return true;
914
915         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
916                 if (search==reader)
917                         return false;
918                 if (search->get_tid() == reader->get_tid() &&
919                                 search->happens_before(reader))
920                         break;
921         }
922
923         return true;
924 }
925
926 /**
927  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
928  * The ModelAction under consideration is expected to be taking part in
929  * release/acquire synchronization as an object of the "reads from" relation.
930  * Note that this can only provide release sequence support for RMW chains
931  * which do not read from the future, as those actions cannot be traced until
932  * their "promise" is fulfilled. Similarly, we may not even establish the
933  * presence of a release sequence with certainty, as some modification order
934  * constraints may be decided further in the future. Thus, this function
935  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
936  * and a boolean representing certainty.
937  *
938  * @todo Finish lazy updating, when promises are fulfilled in the future
939  * @param rf The action that might be part of a release sequence. Must be a
940  * write.
941  * @param release_heads A pass-by-reference style return parameter.  After
942  * execution of this function, release_heads will contain the heads of all the
943  * relevant release sequences, if any exists
944  * @return true, if the ModelChecker is certain that release_heads is complete;
945  * false otherwise
946  */
947 bool ModelChecker::release_seq_head(const ModelAction *rf, rel_heads_list_t *release_heads) const
948 {
949         if (!rf) {
950                 /* read from future: need to settle this later */
951                 return false; /* incomplete */
952         }
953
954         ASSERT(rf->is_write());
955
956         if (rf->is_release())
957                 release_heads->push_back(rf);
958         if (rf->is_rmw()) {
959                 /* We need a RMW action that is both an acquire and release to stop */
960                 /** @todo Need to be smarter here...  In the linux lock
961                  * example, this will run to the beginning of the program for
962                  * every acquire. */
963                 if (rf->is_acquire() && rf->is_release())
964                         return true; /* complete */
965                 return release_seq_head(rf->get_reads_from(), release_heads);
966         }
967         if (rf->is_release())
968                 return true; /* complete */
969
970         /* else relaxed write; check modification order for contiguous subsequence
971          * -> rf must be same thread as release */
972         int tid = id_to_int(rf->get_tid());
973         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
974         action_list_t *list = &(*thrd_lists)[tid];
975         action_list_t::const_reverse_iterator rit;
976
977         /* Find rf in the thread list */
978         rit = std::find(list->rbegin(), list->rend(), rf);
979         ASSERT(rit != list->rend());
980
981         /* Find the last write/release */
982         for (; rit != list->rend(); rit++)
983                 if ((*rit)->is_release())
984                         break;
985         if (rit == list->rend()) {
986                 /* No write-release in this thread */
987                 return true; /* complete */
988         }
989         ModelAction *release = *rit;
990
991         ASSERT(rf->same_thread(release));
992
993         bool certain = true;
994         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
995                 if (id_to_int(rf->get_tid()) == (int)i)
996                         continue;
997                 list = &(*thrd_lists)[i];
998
999                 /* Can we ensure no future writes from this thread may break
1000                  * the release seq? */
1001                 bool future_ordered = false;
1002
1003                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1004                         const ModelAction *act = *rit;
1005                         if (!act->is_write())
1006                                 continue;
1007                         /* Reach synchronization -> this thread is complete */
1008                         if (act->happens_before(release))
1009                                 break;
1010                         if (rf->happens_before(act)) {
1011                                 future_ordered = true;
1012                                 continue;
1013                         }
1014
1015                         /* Check modification order */
1016                         if (mo_graph->checkReachable(rf, act)) {
1017                                 /* rf --mo--> act */
1018                                 future_ordered = true;
1019                                 continue;
1020                         }
1021                         if (mo_graph->checkReachable(act, release))
1022                                 /* act --mo--> release */
1023                                 break;
1024                         if (mo_graph->checkReachable(release, act) &&
1025                                       mo_graph->checkReachable(act, rf)) {
1026                                 /* release --mo-> act --mo--> rf */
1027                                 return true; /* complete */
1028                         }
1029                         certain = false;
1030                 }
1031                 if (!future_ordered)
1032                         return false; /* This thread is uncertain */
1033         }
1034
1035         if (certain)
1036                 release_heads->push_back(release);
1037         return certain;
1038 }
1039
1040 /**
1041  * A public interface for getting the release sequence head(s) with which a
1042  * given ModelAction must synchronize. This function only returns a non-empty
1043  * result when it can locate a release sequence head with certainty. Otherwise,
1044  * it may mark the internal state of the ModelChecker so that it will handle
1045  * the release sequence at a later time, causing @a act to update its
1046  * synchronization at some later point in execution.
1047  * @param act The 'acquire' action that may read from a release sequence
1048  * @param release_heads A pass-by-reference return parameter. Will be filled
1049  * with the head(s) of the release sequence(s), if they exists with certainty.
1050  * @see ModelChecker::release_seq_head
1051  */
1052 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1053 {
1054         const ModelAction *rf = act->get_reads_from();
1055         bool complete;
1056         complete = release_seq_head(rf, release_heads);
1057         if (!complete) {
1058                 /* add act to 'lazy checking' list */
1059                 action_list_t *list;
1060                 list = lazy_sync_with_release->get_safe_ptr(act->get_location());
1061                 list->push_back(act);
1062                 (*lazy_sync_size)++;
1063         }
1064 }
1065
1066 /**
1067  * Attempt to resolve all stashed operations that might synchronize with a
1068  * release sequence for a given location. This implements the "lazy" portion of
1069  * determining whether or not a release sequence was contiguous, since not all
1070  * modification order information is present at the time an action occurs.
1071  *
1072  * @param location The location/object that should be checked for release
1073  * sequence resolutions
1074  * @param work_queue The work queue to which to add work items as they are
1075  * generated
1076  * @return True if any updates occurred (new synchronization, new mo_graph
1077  * edges)
1078  */
1079 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1080 {
1081         action_list_t *list;
1082         list = lazy_sync_with_release->getptr(location);
1083         if (!list)
1084                 return false;
1085
1086         bool updated = false;
1087         action_list_t::iterator it = list->begin();
1088         while (it != list->end()) {
1089                 ModelAction *act = *it;
1090                 const ModelAction *rf = act->get_reads_from();
1091                 rel_heads_list_t release_heads;
1092                 bool complete;
1093                 complete = release_seq_head(rf, &release_heads);
1094                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1095                         if (!act->has_synchronized_with(release_heads[i])) {
1096                                 updated = true;
1097                                 act->synchronize_with(release_heads[i]);
1098                         }
1099                 }
1100
1101                 if (updated) {
1102                         /* Re-check act for mo_graph edges */
1103                         work_queue->push_back(MOEdgeWorkEntry(act));
1104
1105                         /* propagate synchronization to later actions */
1106                         action_list_t::reverse_iterator it = action_trace->rbegin();
1107                         while ((*it) != act) {
1108                                 ModelAction *propagate = *it;
1109                                 if (act->happens_before(propagate)) {
1110                                         propagate->synchronize_with(act);
1111                                         /* Re-check 'propagate' for mo_graph edges */
1112                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1113                                 }
1114                         }
1115                 }
1116                 if (complete) {
1117                         it = list->erase(it);
1118                         (*lazy_sync_size)--;
1119                 } else
1120                         it++;
1121         }
1122
1123         // If we resolved promises or data races, see if we have realized a data race.
1124         if (checkDataRaces()) {
1125                 set_assert();
1126         }
1127
1128         return updated;
1129 }
1130
1131 /**
1132  * Performs various bookkeeping operations for the current ModelAction. For
1133  * instance, adds action to the per-object, per-thread action vector and to the
1134  * action trace list of all thread actions.
1135  *
1136  * @param act is the ModelAction to add.
1137  */
1138 void ModelChecker::add_action_to_lists(ModelAction *act)
1139 {
1140         int tid = id_to_int(act->get_tid());
1141         action_trace->push_back(act);
1142
1143         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1144
1145         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1146         if (tid >= (int)vec->size())
1147                 vec->resize(priv->next_thread_id);
1148         (*vec)[tid].push_back(act);
1149
1150         if ((int)thrd_last_action->size() <= tid)
1151                 thrd_last_action->resize(get_num_threads());
1152         (*thrd_last_action)[tid] = act;
1153 }
1154
1155 ModelAction * ModelChecker::get_last_action(thread_id_t tid)
1156 {
1157         int threadid=id_to_int(tid);
1158         if (threadid<(int)thrd_last_action->size())
1159                 return (*thrd_last_action)[id_to_int(tid)];
1160         else
1161                 return NULL;
1162 }
1163
1164 /**
1165  * Gets the last memory_order_seq_cst write (in the total global sequence)
1166  * performed on a particular object (i.e., memory location), not including the
1167  * current action.
1168  * @param curr The current ModelAction; also denotes the object location to
1169  * check
1170  * @return The last seq_cst write
1171  */
1172 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr)
1173 {
1174         void *location = curr->get_location();
1175         action_list_t *list = obj_map->get_safe_ptr(location);
1176         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1177         action_list_t::reverse_iterator rit;
1178         for (rit = list->rbegin(); rit != list->rend(); rit++)
1179                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1180                         return *rit;
1181         return NULL;
1182 }
1183
1184 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1185 {
1186         ModelAction *parent = get_last_action(tid);
1187         if (!parent)
1188                 parent = get_thread(tid)->get_creation();
1189         return parent;
1190 }
1191
1192 /**
1193  * Returns the clock vector for a given thread.
1194  * @param tid The thread whose clock vector we want
1195  * @return Desired clock vector
1196  */
1197 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1198 {
1199         return get_parent_action(tid)->get_cv();
1200 }
1201
1202 /**
1203  * Resolve a set of Promises with a current write. The set is provided in the
1204  * Node corresponding to @a write.
1205  * @param write The ModelAction that is fulfilling Promises
1206  * @return True if promises were resolved; false otherwise
1207  */
1208 bool ModelChecker::resolve_promises(ModelAction *write)
1209 {
1210         bool resolved = false;
1211
1212         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1213                 Promise *promise = (*promises)[promise_index];
1214                 if (write->get_node()->get_promise(i)) {
1215                         ModelAction *read = promise->get_action();
1216                         read->read_from(write);
1217                         if (read->is_rmw()) {
1218                                 mo_graph->addRMWEdge(write, read);
1219                         }
1220                         //First fix up the modification order for actions that happened
1221                         //before the read
1222                         r_modification_order(read, write);
1223                         //Next fix up the modification order for actions that happened
1224                         //after the read.
1225                         post_r_modification_order(read, write);
1226                         promises->erase(promises->begin() + promise_index);
1227                         resolved = true;
1228                 } else
1229                         promise_index++;
1230         }
1231         return resolved;
1232 }
1233
1234 /**
1235  * Compute the set of promises that could potentially be satisfied by this
1236  * action. Note that the set computation actually appears in the Node, not in
1237  * ModelChecker.
1238  * @param curr The ModelAction that may satisfy promises
1239  */
1240 void ModelChecker::compute_promises(ModelAction *curr)
1241 {
1242         for (unsigned int i = 0; i < promises->size(); i++) {
1243                 Promise *promise = (*promises)[i];
1244                 const ModelAction *act = promise->get_action();
1245                 if (!act->happens_before(curr) &&
1246                                 act->is_read() &&
1247                                 !act->is_synchronizing(curr) &&
1248                                 !act->same_thread(curr) &&
1249                                 promise->get_value() == curr->get_value()) {
1250                         curr->get_node()->set_promise(i);
1251                 }
1252         }
1253 }
1254
1255 /** Checks promises in response to change in ClockVector Threads. */
1256 void ModelChecker::check_promises(ClockVector *old_cv, ClockVector *merge_cv)
1257 {
1258         for (unsigned int i = 0; i < promises->size(); i++) {
1259                 Promise *promise = (*promises)[i];
1260                 const ModelAction *act = promise->get_action();
1261                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1262                                 merge_cv->synchronized_since(act)) {
1263                         //This thread is no longer able to send values back to satisfy the promise
1264                         int num_synchronized_threads = promise->increment_threads();
1265                         if (num_synchronized_threads == get_num_threads()) {
1266                                 //Promise has failed
1267                                 failed_promise = true;
1268                                 return;
1269                         }
1270                 }
1271         }
1272 }
1273
1274 /**
1275  * Build up an initial set of all past writes that this 'read' action may read
1276  * from. This set is determined by the clock vector's "happens before"
1277  * relationship.
1278  * @param curr is the current ModelAction that we are exploring; it must be a
1279  * 'read' operation.
1280  */
1281 void ModelChecker::build_reads_from_past(ModelAction *curr)
1282 {
1283         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1284         unsigned int i;
1285         ASSERT(curr->is_read());
1286
1287         ModelAction *last_seq_cst = NULL;
1288
1289         /* Track whether this object has been initialized */
1290         bool initialized = false;
1291
1292         if (curr->is_seqcst()) {
1293                 last_seq_cst = get_last_seq_cst(curr);
1294                 /* We have to at least see the last sequentially consistent write,
1295                          so we are initialized. */
1296                 if (last_seq_cst != NULL)
1297                         initialized = true;
1298         }
1299
1300         /* Iterate over all threads */
1301         for (i = 0; i < thrd_lists->size(); i++) {
1302                 /* Iterate over actions in thread, starting from most recent */
1303                 action_list_t *list = &(*thrd_lists)[i];
1304                 action_list_t::reverse_iterator rit;
1305                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1306                         ModelAction *act = *rit;
1307
1308                         /* Only consider 'write' actions */
1309                         if (!act->is_write() || act == curr)
1310                                 continue;
1311
1312                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1313                         if (!curr->is_seqcst()|| (!act->is_seqcst() && (last_seq_cst==NULL||!act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1314                                 DEBUG("Adding action to may_read_from:\n");
1315                                 if (DBG_ENABLED()) {
1316                                         act->print();
1317                                         curr->print();
1318                                 }
1319                                 curr->get_node()->add_read_from(act);
1320                         }
1321
1322                         /* Include at most one act per-thread that "happens before" curr */
1323                         if (act->happens_before(curr)) {
1324                                 initialized = true;
1325                                 break;
1326                         }
1327                 }
1328         }
1329
1330         if (!initialized) {
1331                 /** @todo Need a more informative way of reporting errors. */
1332                 printf("ERROR: may read from uninitialized atomic\n");
1333         }
1334
1335         if (DBG_ENABLED() || !initialized) {
1336                 printf("Reached read action:\n");
1337                 curr->print();
1338                 printf("Printing may_read_from\n");
1339                 curr->get_node()->print_may_read_from();
1340                 printf("End printing may_read_from\n");
1341         }
1342
1343         ASSERT(initialized);
1344 }
1345
1346 static void print_list(action_list_t *list)
1347 {
1348         action_list_t::iterator it;
1349
1350         printf("---------------------------------------------------------------------\n");
1351         printf("Trace:\n");
1352
1353         for (it = list->begin(); it != list->end(); it++) {
1354                 (*it)->print();
1355         }
1356         printf("---------------------------------------------------------------------\n");
1357 }
1358
1359 void ModelChecker::print_summary()
1360 {
1361         printf("\n");
1362         printf("Number of executions: %d\n", num_executions);
1363         printf("Number of feasible executions: %d\n", num_feasible_executions);
1364         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1365
1366 #if SUPPORT_MOD_ORDER_DUMP
1367         scheduler->print();
1368         char buffername[100];
1369         sprintf(buffername, "exec%u",num_executions);
1370         mo_graph->dumpGraphToFile(buffername);
1371 #endif
1372
1373         if (!isfinalfeasible())
1374                 printf("INFEASIBLE EXECUTION!\n");
1375         print_list(action_trace);
1376         printf("\n");
1377 }
1378
1379 /**
1380  * Add a Thread to the system for the first time. Should only be called once
1381  * per thread.
1382  * @param t The Thread to add
1383  */
1384 void ModelChecker::add_thread(Thread *t)
1385 {
1386         thread_map->put(id_to_int(t->get_id()), t);
1387         scheduler->add_thread(t);
1388 }
1389
1390 void ModelChecker::remove_thread(Thread *t)
1391 {
1392         scheduler->remove_thread(t);
1393 }
1394
1395 /**
1396  * Switch from a user-context to the "master thread" context (a.k.a. system
1397  * context). This switch is made with the intention of exploring a particular
1398  * model-checking action (described by a ModelAction object). Must be called
1399  * from a user-thread context.
1400  * @param act The current action that will be explored. Must not be NULL.
1401  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1402  */
1403 int ModelChecker::switch_to_master(ModelAction *act)
1404 {
1405         DBG();
1406         Thread *old = thread_current();
1407         set_current_action(act);
1408         old->set_state(THREAD_READY);
1409         return Thread::swap(old, &system_context);
1410 }
1411
1412 /**
1413  * Takes the next step in the execution, if possible.
1414  * @return Returns true (success) if a step was taken and false otherwise.
1415  */
1416 bool ModelChecker::take_step() {
1417         if (has_asserted())
1418                 return false;
1419
1420         Thread * curr = thread_current();
1421         if (curr) {
1422                 if (curr->get_state() == THREAD_READY) {
1423                         ASSERT(priv->current_action);
1424
1425                         priv->nextThread = check_current_action(priv->current_action);
1426                         priv->current_action = NULL;
1427                         if (curr->is_blocked() || curr->is_complete())
1428                                 scheduler->remove_thread(curr);
1429                 } else {
1430                         ASSERT(false);
1431                 }
1432         }
1433         Thread * next = scheduler->next_thread(priv->nextThread);
1434
1435         /* Infeasible -> don't take any more steps */
1436         if (!isfeasible())
1437                 return false;
1438
1439         if (next)
1440                 next->set_state(THREAD_RUNNING);
1441         DEBUG("(%d, %d)\n", curr ? curr->get_id() : -1, next ? next->get_id() : -1);
1442
1443         /* next == NULL -> don't take any more steps */
1444         if (!next)
1445                 return false;
1446         /* Return false only if swap fails with an error */
1447         return (Thread::swap(&system_context, next) == 0);
1448 }
1449
1450 /** Runs the current execution until threre are no more steps to take. */
1451 void ModelChecker::finish_execution() {
1452         DBG();
1453
1454         while (take_step());
1455 }