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