utilize SnapshotAlloc STL allocator
[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 #include "mutex.h"
15 #include "threads.h"
16
17 #define INITIAL_THREAD_ID       0
18
19 ModelChecker *model;
20
21 /** @brief Constructor */
22 ModelChecker::ModelChecker(struct model_params params) :
23         /* Initialize default scheduler */
24         params(params),
25         scheduler(new Scheduler()),
26         num_executions(0),
27         num_feasible_executions(0),
28         diverge(NULL),
29         earliest_diverge(NULL),
30         action_trace(new action_list_t()),
31         thread_map(new HashTable<int, Thread *, int>()),
32         obj_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
33         lock_waiters_map(new HashTable<const void *, action_list_t, uintptr_t, 4>()),
34         obj_thrd_map(new HashTable<void *, std::vector<action_list_t>, uintptr_t, 4 >()),
35         promises(new std::vector< Promise *, SnapshotAlloc<Promise *> >()),
36         futurevalues(new std::vector< struct PendingFutureValue, SnapshotAlloc<struct PendingFutureValue> >()),
37         pending_rel_seqs(new std::vector< struct release_seq *, SnapshotAlloc<struct release_seq *> >()),
38         thrd_last_action(new std::vector< ModelAction *, SnapshotAlloc<ModelAction *> >(1)),
39         node_stack(new NodeStack()),
40         mo_graph(new CycleGraph()),
41         failed_promise(false),
42         too_many_reads(false),
43         asserted(false),
44         bad_synchronization(false)
45 {
46         /* Allocate this "size" on the snapshotting heap */
47         priv = (struct model_snapshot_members *)calloc(1, sizeof(*priv));
48         /* First thread created will have id INITIAL_THREAD_ID */
49         priv->next_thread_id = INITIAL_THREAD_ID;
50
51         /* Initialize a model-checker thread, for special ModelActions */
52         model_thread = new Thread(get_next_id());
53         thread_map->put(id_to_int(model_thread->get_id()), model_thread);
54 }
55
56 /** @brief Destructor */
57 ModelChecker::~ModelChecker()
58 {
59         for (unsigned int i = 0; i < get_num_threads(); i++)
60                 delete thread_map->get(i);
61         delete thread_map;
62
63         delete obj_thrd_map;
64         delete obj_map;
65         delete lock_waiters_map;
66         delete action_trace;
67
68         for (unsigned int i = 0; i < promises->size(); i++)
69                 delete (*promises)[i];
70         delete promises;
71
72         delete pending_rel_seqs;
73
74         delete thrd_last_action;
75         delete node_stack;
76         delete scheduler;
77         delete mo_graph;
78 }
79
80 /**
81  * Restores user program to initial state and resets all model-checker data
82  * structures.
83  */
84 void ModelChecker::reset_to_initial_state()
85 {
86         DEBUG("+++ Resetting to initial state +++\n");
87         node_stack->reset_execution();
88         failed_promise = false;
89         too_many_reads = false;
90         bad_synchronization = false;
91         reset_asserted();
92         snapshotObject->backTrackBeforeStep(0);
93 }
94
95 /** @return a thread ID for a new Thread */
96 thread_id_t ModelChecker::get_next_id()
97 {
98         return priv->next_thread_id++;
99 }
100
101 /** @return the number of user threads created during this execution */
102 unsigned int ModelChecker::get_num_threads()
103 {
104         return priv->next_thread_id;
105 }
106
107 /** @return The currently executing Thread. */
108 Thread * ModelChecker::get_current_thread()
109 {
110         return scheduler->get_current_thread();
111 }
112
113 /** @return a sequence number for a new ModelAction */
114 modelclock_t ModelChecker::get_next_seq_num()
115 {
116         return ++priv->used_sequence_numbers;
117 }
118
119 /**
120  * @brief Choose the next thread to execute.
121  *
122  * This function chooses the next thread that should execute. It can force the
123  * adjacency of read/write portions of a RMW action, force THREAD_CREATE to be
124  * followed by a THREAD_START, or it can enforce execution replay/backtracking.
125  * The model-checker may have no preference regarding the next thread (i.e.,
126  * when exploring a new execution ordering), in which case this will return
127  * NULL.
128  * @param curr The current ModelAction. This action might guide the choice of
129  * next thread.
130  * @return The next thread to run. If the model-checker has no preference, NULL.
131  */
132 Thread * ModelChecker::get_next_thread(ModelAction *curr)
133 {
134         thread_id_t tid;
135
136         if (curr!=NULL) {
137                 /* Do not split atomic actions. */
138                 if (curr->is_rmwr())
139                         return thread_current();
140                 /* The THREAD_CREATE action points to the created Thread */
141                 else if (curr->get_type() == THREAD_CREATE)
142                         return (Thread *)curr->get_location();
143         }
144
145         /* Have we completed exploring the preselected path? */
146         if (diverge == NULL)
147                 return NULL;
148
149         /* Else, we are trying to replay an execution */
150         ModelAction *next = node_stack->get_next()->get_action();
151
152         if (next == diverge) {
153                 if (earliest_diverge == NULL || *diverge < *earliest_diverge)
154                         earliest_diverge=diverge;
155
156                 Node *nextnode = next->get_node();
157                 Node *prevnode = nextnode->get_parent();
158                 scheduler->update_sleep_set(prevnode);
159
160                 /* Reached divergence point */
161                 if (nextnode->increment_promise()) {
162                         /* The next node will try to satisfy a different set of promises. */
163                         tid = next->get_tid();
164                         node_stack->pop_restofstack(2);
165                 } else if (nextnode->increment_read_from()) {
166                         /* The next node will read from a different value. */
167                         tid = next->get_tid();
168                         node_stack->pop_restofstack(2);
169                 } else if (nextnode->increment_future_value()) {
170                         /* The next node will try to read from a different future value. */
171                         tid = next->get_tid();
172                         node_stack->pop_restofstack(2);
173                 } else if (nextnode->increment_relseq_break()) {
174                         /* The next node will try to resolve a release sequence differently */
175                         tid = next->get_tid();
176                         node_stack->pop_restofstack(2);
177                 } else {
178                         /* Make a different thread execute for next step */
179                         scheduler->add_sleep(thread_map->get(id_to_int(next->get_tid())));
180                         tid = prevnode->get_next_backtrack();
181                         /* Make sure the backtracked thread isn't sleeping. */
182                         scheduler->remove_sleep(thread_map->get(id_to_int(tid)));
183                         node_stack->pop_restofstack(1);
184                         if (diverge==earliest_diverge) {
185                                 earliest_diverge=prevnode->get_action();
186                         }
187                 }
188                 /* The correct sleep set is in the parent node. */
189                 execute_sleep_set();
190
191                 DEBUG("*** Divergence point ***\n");
192
193                 diverge = NULL;
194         } else {
195                 tid = next->get_tid();
196         }
197         DEBUG("*** ModelChecker chose next thread = %d ***\n", id_to_int(tid));
198         ASSERT(tid != THREAD_ID_T_NONE);
199         return thread_map->get(id_to_int(tid));
200 }
201
202 /** 
203  * We need to know what the next actions of all threads in the sleep
204  * set will be.  This method computes them and stores the actions at
205  * the corresponding thread object's pending action.
206  */
207
208 void ModelChecker::execute_sleep_set() {
209         for(unsigned int i=0;i<get_num_threads();i++) {
210                 thread_id_t tid=int_to_id(i);
211                 Thread *thr=get_thread(tid);
212                 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
213                         thr->set_state(THREAD_RUNNING);
214                         scheduler->next_thread(thr);
215                         Thread::swap(&system_context, thr);
216                         thr->set_pending(priv->current_action);
217                 }
218         }
219         priv->current_action = NULL;
220 }
221
222 void ModelChecker::wake_up_sleeping_actions(ModelAction * curr) {
223         for(unsigned int i=0;i<get_num_threads();i++) {
224                 thread_id_t tid=int_to_id(i);
225                 Thread *thr=get_thread(tid);
226                 if ( scheduler->get_enabled(thr) == THREAD_SLEEP_SET ) {
227                         ModelAction *pending_act=thr->get_pending();
228                         if (pending_act->could_synchronize_with(curr)) {
229                                 //Remove this thread from sleep set
230                                 scheduler->remove_sleep(thr);
231                         }
232                 }
233         }       
234 }
235
236 /**
237  * Queries the model-checker for more executions to explore and, if one
238  * exists, resets the model-checker state to execute a new execution.
239  *
240  * @return If there are more executions to explore, return true. Otherwise,
241  * return false.
242  */
243 bool ModelChecker::next_execution()
244 {
245         DBG();
246
247         num_executions++;
248
249         if (isfinalfeasible()) {
250                 printf("Earliest divergence point since last feasible execution:\n");
251                 if (earliest_diverge)
252                         earliest_diverge->print();
253                 else
254                         printf("(Not set)\n");
255
256                 earliest_diverge = NULL;
257                 num_feasible_executions++;
258         }
259
260         DEBUG("Number of acquires waiting on pending release sequences: %zu\n",
261                         pending_rel_seqs->size());
262
263         if (isfinalfeasible() || DBG_ENABLED())
264                 print_summary();
265
266         if ((diverge = get_next_backtrack()) == NULL)
267                 return false;
268
269         if (DBG_ENABLED()) {
270                 printf("Next execution will diverge at:\n");
271                 diverge->print();
272         }
273
274         reset_to_initial_state();
275         return true;
276 }
277
278 ModelAction * ModelChecker::get_last_conflict(ModelAction *act)
279 {
280         switch (act->get_type()) {
281         case ATOMIC_READ:
282         case ATOMIC_WRITE:
283         case ATOMIC_RMW: {
284                 /* linear search: from most recent to oldest */
285                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
286                 action_list_t::reverse_iterator rit;
287                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
288                         ModelAction *prev = *rit;
289                         if (prev->could_synchronize_with(act))
290                                 return prev;
291                 }
292                 break;
293         }
294         case ATOMIC_LOCK:
295         case ATOMIC_TRYLOCK: {
296                 /* linear search: from most recent to oldest */
297                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
298                 action_list_t::reverse_iterator rit;
299                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
300                         ModelAction *prev = *rit;
301                         if (act->is_conflicting_lock(prev))
302                                 return prev;
303                 }
304                 break;
305         }
306         case ATOMIC_UNLOCK: {
307                 /* linear search: from most recent to oldest */
308                 action_list_t *list = obj_map->get_safe_ptr(act->get_location());
309                 action_list_t::reverse_iterator rit;
310                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
311                         ModelAction *prev = *rit;
312                         if (!act->same_thread(prev)&&prev->is_failed_trylock())
313                                 return prev;
314                 }
315                 break;
316         }
317         default:
318                 break;
319         }
320         return NULL;
321 }
322
323 /** This method finds backtracking points where we should try to
324  * reorder the parameter ModelAction against.
325  *
326  * @param the ModelAction to find backtracking points for.
327  */
328 void ModelChecker::set_backtracking(ModelAction *act)
329 {
330         Thread *t = get_thread(act);
331         ModelAction * prev = get_last_conflict(act);
332         if (prev == NULL)
333                 return;
334
335         Node * node = prev->get_node()->get_parent();
336
337         int low_tid, high_tid;
338         if (node->is_enabled(t)) {
339                 low_tid = id_to_int(act->get_tid());
340                 high_tid = low_tid+1;
341         } else {
342                 low_tid = 0;
343                 high_tid = get_num_threads();
344         }
345
346         for(int i = low_tid; i < high_tid; i++) {
347                 thread_id_t tid = int_to_id(i);
348
349                 if (!node->is_enabled(tid))
350                         continue;
351         
352                 /* Check if this has been explored already */
353                 if (node->has_been_explored(tid))
354                         continue;
355
356                 /* See if fairness allows */
357                 if (model->params.fairwindow != 0 && !node->has_priority(tid)) {
358                         bool unfair=false;
359                         for(int t=0;t<node->get_num_threads();t++) {
360                                 thread_id_t tother=int_to_id(t);
361                                 if (node->is_enabled(tother) && node->has_priority(tother)) {
362                                         unfair=true;
363                                         break;
364                                 }
365                         }
366                         if (unfair)
367                                 continue;
368                 }
369                 /* Cache the latest backtracking point */
370                 if (!priv->next_backtrack || *prev > *priv->next_backtrack)
371                         priv->next_backtrack = prev;
372
373                 /* If this is a new backtracking point, mark the tree */
374                 if (!node->set_backtrack(tid))
375                         continue;
376                 DEBUG("Setting backtrack: conflict = %d, instead tid = %d\n",
377                                         id_to_int(prev->get_tid()),
378                                         id_to_int(t->get_id()));
379                 if (DBG_ENABLED()) {
380                         prev->print();
381                         act->print();
382                 }
383         }
384 }
385
386 /**
387  * Returns last backtracking point. The model checker will explore a different
388  * path for this point in the next execution.
389  * @return The ModelAction at which the next execution should diverge.
390  */
391 ModelAction * ModelChecker::get_next_backtrack()
392 {
393         ModelAction *next = priv->next_backtrack;
394         priv->next_backtrack = NULL;
395         return next;
396 }
397
398 /**
399  * Processes a read or rmw model action.
400  * @param curr is the read model action to process.
401  * @param second_part_of_rmw is boolean that is true is this is the second action of a rmw.
402  * @return True if processing this read updates the mo_graph.
403  */
404 bool ModelChecker::process_read(ModelAction *curr, bool second_part_of_rmw)
405 {
406         uint64_t value;
407         bool updated = false;
408         while (true) {
409                 const ModelAction *reads_from = curr->get_node()->get_read_from();
410                 if (reads_from != NULL) {
411                         mo_graph->startChanges();
412
413                         value = reads_from->get_value();
414                         bool r_status = false;
415
416                         if (!second_part_of_rmw) {
417                                 check_recency(curr, reads_from);
418                                 r_status = r_modification_order(curr, reads_from);
419                         }
420
421
422                         if (!second_part_of_rmw&&!isfeasible()&&(curr->get_node()->increment_read_from()||curr->get_node()->increment_future_value())) {
423                                 mo_graph->rollbackChanges();
424                                 too_many_reads = false;
425                                 continue;
426                         }
427
428                         curr->read_from(reads_from);
429                         mo_graph->commitChanges();
430                         mo_check_promises(curr->get_tid(), reads_from);
431
432                         updated |= r_status;
433                 } else if (!second_part_of_rmw) {
434                         /* Read from future value */
435                         value = curr->get_node()->get_future_value();
436                         modelclock_t expiration = curr->get_node()->get_future_value_expiration();
437                         curr->read_from(NULL);
438                         Promise *valuepromise = new Promise(curr, value, expiration);
439                         promises->push_back(valuepromise);
440                 }
441                 get_thread(curr)->set_return_value(value);
442                 return updated;
443         }
444 }
445
446 /**
447  * Processes a lock, trylock, or unlock model action.  @param curr is
448  * the read model action to process.
449  *
450  * The try lock operation checks whether the lock is taken.  If not,
451  * it falls to the normal lock operation case.  If so, it returns
452  * fail.
453  *
454  * The lock operation has already been checked that it is enabled, so
455  * it just grabs the lock and synchronizes with the previous unlock.
456  *
457  * The unlock operation has to re-enable all of the threads that are
458  * waiting on the lock.
459  *
460  * @return True if synchronization was updated; false otherwise
461  */
462 bool ModelChecker::process_mutex(ModelAction *curr) {
463         std::mutex *mutex = (std::mutex *)curr->get_location();
464         struct std::mutex_state *state = mutex->get_state();
465         switch (curr->get_type()) {
466         case ATOMIC_TRYLOCK: {
467                 bool success = !state->islocked;
468                 curr->set_try_lock(success);
469                 if (!success) {
470                         get_thread(curr)->set_return_value(0);
471                         break;
472                 }
473                 get_thread(curr)->set_return_value(1);
474         }
475                 //otherwise fall into the lock case
476         case ATOMIC_LOCK: {
477                 if (curr->get_cv()->getClock(state->alloc_tid) <= state->alloc_clock) {
478                         printf("Lock access before initialization\n");
479                         set_assert();
480                 }
481                 state->islocked = true;
482                 ModelAction *unlock = get_last_unlock(curr);
483                 //synchronize with the previous unlock statement
484                 if (unlock != NULL) {
485                         curr->synchronize_with(unlock);
486                         return true;
487                 }
488                 break;
489         }
490         case ATOMIC_UNLOCK: {
491                 //unlock the lock
492                 state->islocked = false;
493                 //wake up the other threads
494                 action_list_t *waiters = lock_waiters_map->get_safe_ptr(curr->get_location());
495                 //activate all the waiting threads
496                 for (action_list_t::iterator rit = waiters->begin(); rit != waiters->end(); rit++) {
497                         scheduler->wake(get_thread(*rit));
498                 }
499                 waiters->clear();
500                 break;
501         }
502         default:
503                 ASSERT(0);
504         }
505         return false;
506 }
507
508 /**
509  * Process a write ModelAction
510  * @param curr The ModelAction to process
511  * @return True if the mo_graph was updated or promises were resolved
512  */
513 bool ModelChecker::process_write(ModelAction *curr)
514 {
515         bool updated_mod_order = w_modification_order(curr);
516         bool updated_promises = resolve_promises(curr);
517
518         if (promises->size() == 0) {
519                 for (unsigned int i = 0; i < futurevalues->size(); i++) {
520                         struct PendingFutureValue pfv = (*futurevalues)[i];
521                         if (pfv.act->get_node()->add_future_value(pfv.value, pfv.expiration) &&
522                                         (!priv->next_backtrack || *pfv.act > *priv->next_backtrack))
523                                 priv->next_backtrack = pfv.act;
524                 }
525                 futurevalues->resize(0);
526         }
527
528         mo_graph->commitChanges();
529         mo_check_promises(curr->get_tid(), curr);
530
531         get_thread(curr)->set_return_value(VALUE_NONE);
532         return updated_mod_order || updated_promises;
533 }
534
535 /**
536  * @brief Process the current action for thread-related activity
537  *
538  * Performs current-action processing for a THREAD_* ModelAction. Proccesses
539  * may include setting Thread status, completing THREAD_FINISH/THREAD_JOIN
540  * synchronization, etc.  This function is a no-op for non-THREAD actions
541  * (e.g., ATOMIC_{READ,WRITE,RMW,LOCK}, etc.)
542  *
543  * @param curr The current action
544  * @return True if synchronization was updated or a thread completed
545  */
546 bool ModelChecker::process_thread_action(ModelAction *curr)
547 {
548         bool updated = false;
549
550         switch (curr->get_type()) {
551         case THREAD_CREATE: {
552                 Thread *th = (Thread *)curr->get_location();
553                 th->set_creation(curr);
554                 break;
555         }
556         case THREAD_JOIN: {
557                 Thread *waiting, *blocking;
558                 waiting = get_thread(curr);
559                 blocking = (Thread *)curr->get_location();
560                 if (!blocking->is_complete()) {
561                         blocking->push_wait_list(curr);
562                         scheduler->sleep(waiting);
563                 } else {
564                         do_complete_join(curr);
565                         updated = true; /* trigger rel-seq checks */
566                 }
567                 break;
568         }
569         case THREAD_FINISH: {
570                 Thread *th = get_thread(curr);
571                 while (!th->wait_list_empty()) {
572                         ModelAction *act = th->pop_wait_list();
573                         Thread *wake = get_thread(act);
574                         scheduler->wake(wake);
575                         do_complete_join(act);
576                         updated = true; /* trigger rel-seq checks */
577                 }
578                 th->complete();
579                 updated = true; /* trigger rel-seq checks */
580                 break;
581         }
582         case THREAD_START: {
583                 check_promises(curr->get_tid(), NULL, curr->get_cv());
584                 break;
585         }
586         default:
587                 break;
588         }
589
590         return updated;
591 }
592
593 /**
594  * @brief Process the current action for release sequence fixup activity
595  *
596  * Performs model-checker release sequence fixups for the current action,
597  * forcing a single pending release sequence to break (with a given, potential
598  * "loose" write) or to complete (i.e., synchronize). If a pending release
599  * sequence forms a complete release sequence, then we must perform the fixup
600  * synchronization, mo_graph additions, etc.
601  *
602  * @param curr The current action; must be a release sequence fixup action
603  * @param work_queue The work queue to which to add work items as they are
604  * generated
605  */
606 void ModelChecker::process_relseq_fixup(ModelAction *curr, work_queue_t *work_queue)
607 {
608         const ModelAction *write = curr->get_node()->get_relseq_break();
609         struct release_seq *sequence = pending_rel_seqs->back();
610         pending_rel_seqs->pop_back();
611         ASSERT(sequence);
612         ModelAction *acquire = sequence->acquire;
613         const ModelAction *rf = sequence->rf;
614         const ModelAction *release = sequence->release;
615         ASSERT(acquire);
616         ASSERT(release);
617         ASSERT(rf);
618         ASSERT(release->same_thread(rf));
619
620         if (write == NULL) {
621                 /**
622                  * @todo Forcing a synchronization requires that we set
623                  * modification order constraints. For instance, we can't allow
624                  * a fixup sequence in which two separate read-acquire
625                  * operations read from the same sequence, where the first one
626                  * synchronizes and the other doesn't. Essentially, we can't
627                  * allow any writes to insert themselves between 'release' and
628                  * 'rf'
629                  */
630
631                 /* Must synchronize */
632                 if (!acquire->synchronize_with(release)) {
633                         set_bad_synchronization();
634                         return;
635                 }
636                 /* Re-check all pending release sequences */
637                 work_queue->push_back(CheckRelSeqWorkEntry(NULL));
638                 /* Re-check act for mo_graph edges */
639                 work_queue->push_back(MOEdgeWorkEntry(acquire));
640
641                 /* propagate synchronization to later actions */
642                 action_list_t::reverse_iterator rit = action_trace->rbegin();
643                 for (; (*rit) != acquire; rit++) {
644                         ModelAction *propagate = *rit;
645                         if (acquire->happens_before(propagate)) {
646                                 propagate->synchronize_with(acquire);
647                                 /* Re-check 'propagate' for mo_graph edges */
648                                 work_queue->push_back(MOEdgeWorkEntry(propagate));
649                         }
650                 }
651         } else {
652                 /* Break release sequence with new edges:
653                  *   release --mo--> write --mo--> rf */
654                 mo_graph->addEdge(release, write);
655                 mo_graph->addEdge(write, rf);
656         }
657
658         /* See if we have realized a data race */
659         if (checkDataRaces())
660                 set_assert();
661 }
662
663 /**
664  * Initialize the current action by performing one or more of the following
665  * actions, as appropriate: merging RMWR and RMWC/RMW actions, stepping forward
666  * in the NodeStack, manipulating backtracking sets, allocating and
667  * initializing clock vectors, and computing the promises to fulfill.
668  *
669  * @param curr The current action, as passed from the user context; may be
670  * freed/invalidated after the execution of this function
671  * @return The current action, as processed by the ModelChecker. Is only the
672  * same as the parameter @a curr if this is a newly-explored action.
673  */
674 ModelAction * ModelChecker::initialize_curr_action(ModelAction *curr)
675 {
676         ModelAction *newcurr;
677
678         if (curr->is_rmwc() || curr->is_rmw()) {
679                 newcurr = process_rmw(curr);
680                 delete curr;
681
682                 if (newcurr->is_rmw())
683                         compute_promises(newcurr);
684                 return newcurr;
685         }
686
687         curr->set_seq_number(get_next_seq_num());
688
689         newcurr = node_stack->explore_action(curr, scheduler->get_enabled());
690         if (newcurr) {
691                 /* First restore type and order in case of RMW operation */
692                 if (curr->is_rmwr())
693                         newcurr->copy_typeandorder(curr);
694
695                 ASSERT(curr->get_location() == newcurr->get_location());
696                 newcurr->copy_from_new(curr);
697
698                 /* Discard duplicate ModelAction; use action from NodeStack */
699                 delete curr;
700
701                 /* Always compute new clock vector */
702                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
703         } else {
704                 newcurr = curr;
705
706                 /* Always compute new clock vector */
707                 newcurr->create_cv(get_parent_action(newcurr->get_tid()));
708                 /*
709                  * Perform one-time actions when pushing new ModelAction onto
710                  * NodeStack
711                  */
712                 if (newcurr->is_write())
713                         compute_promises(newcurr);
714                 else if (newcurr->is_relseq_fixup())
715                         compute_relseq_breakwrites(newcurr);
716         }
717         return newcurr;
718 }
719
720 /**
721  * This method checks whether a model action is enabled at the given point.
722  * At this point, it checks whether a lock operation would be successful at this point.
723  * If not, it puts the thread in a waiter list.
724  * @param curr is the ModelAction to check whether it is enabled.
725  * @return a bool that indicates whether the action is enabled.
726  */
727 bool ModelChecker::check_action_enabled(ModelAction *curr) {
728         if (curr->is_lock()) {
729                 std::mutex * lock = (std::mutex *)curr->get_location();
730                 struct std::mutex_state * state = lock->get_state();
731                 if (state->islocked) {
732                         //Stick the action in the appropriate waiting queue
733                         lock_waiters_map->get_safe_ptr(curr->get_location())->push_back(curr);
734                         return false;
735                 }
736         }
737
738         return true;
739 }
740
741 /**
742  * This is the heart of the model checker routine. It performs model-checking
743  * actions corresponding to a given "current action." Among other processes, it
744  * calculates reads-from relationships, updates synchronization clock vectors,
745  * forms a memory_order constraints graph, and handles replay/backtrack
746  * execution when running permutations of previously-observed executions.
747  *
748  * @param curr The current action to process
749  * @return The next Thread that must be executed. May be NULL if ModelChecker
750  * makes no choice (e.g., according to replay execution, combining RMW actions,
751  * etc.)
752  */
753 Thread * ModelChecker::check_current_action(ModelAction *curr)
754 {
755         ASSERT(curr);
756         bool second_part_of_rmw = curr->is_rmwc() || curr->is_rmw();
757
758         if (!check_action_enabled(curr)) {
759                 /* Make the execution look like we chose to run this action
760                  * much later, when a lock is actually available to release */
761                 get_current_thread()->set_pending(curr);
762                 scheduler->sleep(get_current_thread());
763                 return get_next_thread(NULL);
764         }
765
766         wake_up_sleeping_actions(curr);
767
768         ModelAction *newcurr = initialize_curr_action(curr);
769
770
771         /* Add the action to lists before any other model-checking tasks */
772         if (!second_part_of_rmw)
773                 add_action_to_lists(newcurr);
774
775         /* Build may_read_from set for newly-created actions */
776         if (curr == newcurr && curr->is_read())
777                 build_reads_from_past(curr);
778         curr = newcurr;
779
780         /* Initialize work_queue with the "current action" work */
781         work_queue_t work_queue(1, CheckCurrWorkEntry(curr));
782         while (!work_queue.empty()) {
783                 WorkQueueEntry work = work_queue.front();
784                 work_queue.pop_front();
785
786                 switch (work.type) {
787                 case WORK_CHECK_CURR_ACTION: {
788                         ModelAction *act = work.action;
789                         bool update = false; /* update this location's release seq's */
790                         bool update_all = false; /* update all release seq's */
791
792                         if (process_thread_action(curr))
793                                 update_all = true;
794
795                         if (act->is_read() && process_read(act, second_part_of_rmw))
796                                 update = true;
797
798                         if (act->is_write() && process_write(act))
799                                 update = true;
800
801                         if (act->is_mutex_op() && process_mutex(act))
802                                 update_all = true;
803
804                         if (act->is_relseq_fixup())
805                                 process_relseq_fixup(curr, &work_queue);
806
807                         if (update_all)
808                                 work_queue.push_back(CheckRelSeqWorkEntry(NULL));
809                         else if (update)
810                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
811                         break;
812                 }
813                 case WORK_CHECK_RELEASE_SEQ:
814                         resolve_release_sequences(work.location, &work_queue);
815                         break;
816                 case WORK_CHECK_MO_EDGES: {
817                         /** @todo Complete verification of work_queue */
818                         ModelAction *act = work.action;
819                         bool updated = false;
820
821                         if (act->is_read()) {
822                                 const ModelAction *rf = act->get_reads_from();
823                                 if (rf != NULL && r_modification_order(act, rf))
824                                         updated = true;
825                         }
826                         if (act->is_write()) {
827                                 if (w_modification_order(act))
828                                         updated = true;
829                         }
830                         mo_graph->commitChanges();
831
832                         if (updated)
833                                 work_queue.push_back(CheckRelSeqWorkEntry(act->get_location()));
834                         break;
835                 }
836                 default:
837                         ASSERT(false);
838                         break;
839                 }
840         }
841
842         check_curr_backtracking(curr);
843         set_backtracking(curr);
844         return get_next_thread(curr);
845 }
846
847 /**
848  * Complete a THREAD_JOIN operation, by synchronizing with the THREAD_FINISH
849  * operation from the Thread it is joining with. Must be called after the
850  * completion of the Thread in question.
851  * @param join The THREAD_JOIN action
852  */
853 void ModelChecker::do_complete_join(ModelAction *join)
854 {
855         Thread *blocking = (Thread *)join->get_location();
856         ModelAction *act = get_last_action(blocking->get_id());
857         join->synchronize_with(act);
858 }
859
860 void ModelChecker::check_curr_backtracking(ModelAction * curr) {
861         Node *currnode = curr->get_node();
862         Node *parnode = currnode->get_parent();
863
864         if ((!parnode->backtrack_empty() ||
865                          !currnode->read_from_empty() ||
866                          !currnode->future_value_empty() ||
867                          !currnode->promise_empty() ||
868                          !currnode->relseq_break_empty())
869                         && (!priv->next_backtrack ||
870                                         *curr > *priv->next_backtrack)) {
871                 priv->next_backtrack = curr;
872         }
873 }
874
875 bool ModelChecker::promises_expired() {
876         for (unsigned int promise_index = 0; promise_index < promises->size(); promise_index++) {
877                 Promise *promise = (*promises)[promise_index];
878                 if (promise->get_expiration()<priv->used_sequence_numbers) {
879                         return true;
880                 }
881         }
882         return false;
883 }
884
885 /** @return whether the current partial trace must be a prefix of a
886  * feasible trace. */
887 bool ModelChecker::isfeasibleprefix() {
888         return promises->size() == 0 && pending_rel_seqs->size() == 0;
889 }
890
891 /** @return whether the current partial trace is feasible. */
892 bool ModelChecker::isfeasible() {
893         if (DBG_ENABLED() && mo_graph->checkForRMWViolation())
894                 DEBUG("Infeasible: RMW violation\n");
895
896         return !mo_graph->checkForRMWViolation() && isfeasibleotherthanRMW();
897 }
898
899 /** @return whether the current partial trace is feasible other than
900  * multiple RMW reading from the same store. */
901 bool ModelChecker::isfeasibleotherthanRMW() {
902         if (DBG_ENABLED()) {
903                 if (mo_graph->checkForCycles())
904                         DEBUG("Infeasible: modification order cycles\n");
905                 if (failed_promise)
906                         DEBUG("Infeasible: failed promise\n");
907                 if (too_many_reads)
908                         DEBUG("Infeasible: too many reads\n");
909                 if (bad_synchronization)
910                         DEBUG("Infeasible: bad synchronization ordering\n");
911                 if (promises_expired())
912                         DEBUG("Infeasible: promises expired\n");
913         }
914         return !mo_graph->checkForCycles() && !failed_promise && !too_many_reads && !bad_synchronization && !promises_expired();
915 }
916
917 /** Returns whether the current completed trace is feasible. */
918 bool ModelChecker::isfinalfeasible() {
919         if (DBG_ENABLED() && promises->size() != 0)
920                 DEBUG("Infeasible: unrevolved promises\n");
921
922         return isfeasible() && promises->size() == 0;
923 }
924
925 /** Close out a RMWR by converting previous RMWR into a RMW or READ. */
926 ModelAction * ModelChecker::process_rmw(ModelAction *act) {
927         ModelAction *lastread = get_last_action(act->get_tid());
928         lastread->process_rmw(act);
929         if (act->is_rmw() && lastread->get_reads_from()!=NULL) {
930                 mo_graph->addRMWEdge(lastread->get_reads_from(), lastread);
931                 mo_graph->commitChanges();
932         }
933         return lastread;
934 }
935
936 /**
937  * Checks whether a thread has read from the same write for too many times
938  * without seeing the effects of a later write.
939  *
940  * Basic idea:
941  * 1) there must a different write that we could read from that would satisfy the modification order,
942  * 2) we must have read from the same value in excess of maxreads times, and
943  * 3) that other write must have been in the reads_from set for maxreads times.
944  *
945  * If so, we decide that the execution is no longer feasible.
946  */
947 void ModelChecker::check_recency(ModelAction *curr, const ModelAction *rf) {
948         if (params.maxreads != 0) {
949
950                 if (curr->get_node()->get_read_from_size() <= 1)
951                         return;
952                 //Must make sure that execution is currently feasible...  We could
953                 //accidentally clear by rolling back
954                 if (!isfeasible())
955                         return;
956                 std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
957                 int tid = id_to_int(curr->get_tid());
958
959                 /* Skip checks */
960                 if ((int)thrd_lists->size() <= tid)
961                         return;
962                 action_list_t *list = &(*thrd_lists)[tid];
963
964                 action_list_t::reverse_iterator rit = list->rbegin();
965                 /* Skip past curr */
966                 for (; (*rit) != curr; rit++)
967                         ;
968                 /* go past curr now */
969                 rit++;
970
971                 action_list_t::reverse_iterator ritcopy = rit;
972                 //See if we have enough reads from the same value
973                 int count = 0;
974                 for (; count < params.maxreads; rit++,count++) {
975                         if (rit==list->rend())
976                                 return;
977                         ModelAction *act = *rit;
978                         if (!act->is_read())
979                                 return;
980                         
981                         if (act->get_reads_from() != rf)
982                                 return;
983                         if (act->get_node()->get_read_from_size() <= 1)
984                                 return;
985                 }
986                 for (int i = 0; i<curr->get_node()->get_read_from_size(); i++) {
987                         //Get write
988                         const ModelAction * write = curr->get_node()->get_read_from_at(i);
989
990                         //Need a different write
991                         if (write==rf)
992                                 continue;
993
994                         /* Test to see whether this is a feasible write to read from*/
995                         mo_graph->startChanges();
996                         r_modification_order(curr, write);
997                         bool feasiblereadfrom = isfeasible();
998                         mo_graph->rollbackChanges();
999
1000                         if (!feasiblereadfrom)
1001                                 continue;
1002                         rit = ritcopy;
1003
1004                         bool feasiblewrite = true;
1005                         //new we need to see if this write works for everyone
1006
1007                         for (int loop = count; loop>0; loop--,rit++) {
1008                                 ModelAction *act=*rit;
1009                                 bool foundvalue = false;
1010                                 for (int j = 0; j<act->get_node()->get_read_from_size(); j++) {
1011                                         if (act->get_node()->get_read_from_at(i)==write) {
1012                                                 foundvalue = true;
1013                                                 break;
1014                                         }
1015                                 }
1016                                 if (!foundvalue) {
1017                                         feasiblewrite = false;
1018                                         break;
1019                                 }
1020                         }
1021                         if (feasiblewrite) {
1022                                 too_many_reads = true;
1023                                 return;
1024                         }
1025                 }
1026         }
1027 }
1028
1029 /**
1030  * Updates the mo_graph with the constraints imposed from the current
1031  * read.
1032  *
1033  * Basic idea is the following: Go through each other thread and find
1034  * the lastest action that happened before our read.  Two cases:
1035  *
1036  * (1) The action is a write => that write must either occur before
1037  * the write we read from or be the write we read from.
1038  *
1039  * (2) The action is a read => the write that that action read from
1040  * must occur before the write we read from or be the same write.
1041  *
1042  * @param curr The current action. Must be a read.
1043  * @param rf The action that curr reads from. Must be a write.
1044  * @return True if modification order edges were added; false otherwise
1045  */
1046 bool ModelChecker::r_modification_order(ModelAction *curr, const ModelAction *rf)
1047 {
1048         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1049         unsigned int i;
1050         bool added = false;
1051         ASSERT(curr->is_read());
1052
1053         /* Iterate over all threads */
1054         for (i = 0; i < thrd_lists->size(); i++) {
1055                 /* Iterate over actions in thread, starting from most recent */
1056                 action_list_t *list = &(*thrd_lists)[i];
1057                 action_list_t::reverse_iterator rit;
1058                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1059                         ModelAction *act = *rit;
1060
1061                         /*
1062                          * Include at most one act per-thread that "happens
1063                          * before" curr. Don't consider reflexively.
1064                          */
1065                         if (act->happens_before(curr) && act != curr) {
1066                                 if (act->is_write()) {
1067                                         if (rf != act) {
1068                                                 mo_graph->addEdge(act, rf);
1069                                                 added = true;
1070                                         }
1071                                 } else {
1072                                         const ModelAction *prevreadfrom = act->get_reads_from();
1073                                         //if the previous read is unresolved, keep going...
1074                                         if (prevreadfrom == NULL)
1075                                                 continue;
1076
1077                                         if (rf != prevreadfrom) {
1078                                                 mo_graph->addEdge(prevreadfrom, rf);
1079                                                 added = true;
1080                                         }
1081                                 }
1082                                 break;
1083                         }
1084                 }
1085         }
1086
1087         return added;
1088 }
1089
1090 /** This method fixes up the modification order when we resolve a
1091  *  promises.  The basic problem is that actions that occur after the
1092  *  read curr could not property add items to the modification order
1093  *  for our read.
1094  *
1095  *  So for each thread, we find the earliest item that happens after
1096  *  the read curr.  This is the item we have to fix up with additional
1097  *  constraints.  If that action is write, we add a MO edge between
1098  *  the Action rf and that action.  If the action is a read, we add a
1099  *  MO edge between the Action rf, and whatever the read accessed.
1100  *
1101  * @param curr is the read ModelAction that we are fixing up MO edges for.
1102  * @param rf is the write ModelAction that curr reads from.
1103  *
1104  */
1105 void ModelChecker::post_r_modification_order(ModelAction *curr, const ModelAction *rf)
1106 {
1107         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1108         unsigned int i;
1109         ASSERT(curr->is_read());
1110
1111         /* Iterate over all threads */
1112         for (i = 0; i < thrd_lists->size(); i++) {
1113                 /* Iterate over actions in thread, starting from most recent */
1114                 action_list_t *list = &(*thrd_lists)[i];
1115                 action_list_t::reverse_iterator rit;
1116                 ModelAction *lastact = NULL;
1117
1118                 /* Find last action that happens after curr that is either not curr or a rmw */
1119                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1120                         ModelAction *act = *rit;
1121                         if (curr->happens_before(act) && (curr != act || curr->is_rmw())) {
1122                                 lastact = act;
1123                         } else
1124                                 break;
1125                 }
1126
1127                         /* Include at most one act per-thread that "happens before" curr */
1128                 if (lastact != NULL) {
1129                         if (lastact==curr) {
1130                                 //Case 1: The resolved read is a RMW, and we need to make sure
1131                                 //that the write portion of the RMW mod order after rf
1132
1133                                 mo_graph->addEdge(rf, lastact);
1134                         } else if (lastact->is_read()) {
1135                                 //Case 2: The resolved read is a normal read and the next
1136                                 //operation is a read, and we need to make sure the value read
1137                                 //is mod ordered after rf
1138
1139                                 const ModelAction *postreadfrom = lastact->get_reads_from();
1140                                 if (postreadfrom != NULL&&rf != postreadfrom)
1141                                         mo_graph->addEdge(rf, postreadfrom);
1142                         } else {
1143                                 //Case 3: The resolved read is a normal read and the next
1144                                 //operation is a write, and we need to make sure that the
1145                                 //write is mod ordered after rf
1146                                 if (lastact!=rf)
1147                                         mo_graph->addEdge(rf, lastact);
1148                         }
1149                         break;
1150                 }
1151         }
1152 }
1153
1154 /**
1155  * Updates the mo_graph with the constraints imposed from the current write.
1156  *
1157  * Basic idea is the following: Go through each other thread and find
1158  * the lastest action that happened before our write.  Two cases:
1159  *
1160  * (1) The action is a write => that write must occur before
1161  * the current write
1162  *
1163  * (2) The action is a read => the write that that action read from
1164  * must occur before the current write.
1165  *
1166  * This method also handles two other issues:
1167  *
1168  * (I) Sequential Consistency: Making sure that if the current write is
1169  * seq_cst, that it occurs after the previous seq_cst write.
1170  *
1171  * (II) Sending the write back to non-synchronizing reads.
1172  *
1173  * @param curr The current action. Must be a write.
1174  * @return True if modification order edges were added; false otherwise
1175  */
1176 bool ModelChecker::w_modification_order(ModelAction *curr)
1177 {
1178         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1179         unsigned int i;
1180         bool added = false;
1181         ASSERT(curr->is_write());
1182
1183         if (curr->is_seqcst()) {
1184                 /* We have to at least see the last sequentially consistent write,
1185                          so we are initialized. */
1186                 ModelAction *last_seq_cst = get_last_seq_cst(curr);
1187                 if (last_seq_cst != NULL) {
1188                         mo_graph->addEdge(last_seq_cst, curr);
1189                         added = true;
1190                 }
1191         }
1192
1193         /* Iterate over all threads */
1194         for (i = 0; i < thrd_lists->size(); i++) {
1195                 /* Iterate over actions in thread, starting from most recent */
1196                 action_list_t *list = &(*thrd_lists)[i];
1197                 action_list_t::reverse_iterator rit;
1198                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1199                         ModelAction *act = *rit;
1200                         if (act == curr) {
1201                                 /*
1202                                  * 1) If RMW and it actually read from something, then we
1203                                  * already have all relevant edges, so just skip to next
1204                                  * thread.
1205                                  * 
1206                                  * 2) If RMW and it didn't read from anything, we should
1207                                  * whatever edge we can get to speed up convergence.
1208                                  *
1209                                  * 3) If normal write, we need to look at earlier actions, so
1210                                  * continue processing list.
1211                                  */
1212                                 if (curr->is_rmw()) {
1213                                         if (curr->get_reads_from()!=NULL)
1214                                                 break;
1215                                         else 
1216                                                 continue;
1217                                 } else
1218                                         continue;
1219                         }
1220
1221                         /*
1222                          * Include at most one act per-thread that "happens
1223                          * before" curr
1224                          */
1225                         if (act->happens_before(curr)) {
1226                                 /*
1227                                  * Note: if act is RMW, just add edge:
1228                                  *   act --mo--> curr
1229                                  * The following edge should be handled elsewhere:
1230                                  *   readfrom(act) --mo--> act
1231                                  */
1232                                 if (act->is_write())
1233                                         mo_graph->addEdge(act, curr);
1234                                 else if (act->is_read()) { 
1235                                         //if previous read accessed a null, just keep going
1236                                         if (act->get_reads_from() == NULL)
1237                                                 continue;
1238                                         mo_graph->addEdge(act->get_reads_from(), curr);
1239                                 }
1240                                 added = true;
1241                                 break;
1242                         } else if (act->is_read() && !act->could_synchronize_with(curr) &&
1243                                                      !act->same_thread(curr)) {
1244                                 /* We have an action that:
1245                                    (1) did not happen before us
1246                                    (2) is a read and we are a write
1247                                    (3) cannot synchronize with us
1248                                    (4) is in a different thread
1249                                    =>
1250                                    that read could potentially read from our write.
1251                                  */
1252                                 if (thin_air_constraint_may_allow(curr, act)) {
1253                                         if (isfeasible() ||
1254                                                         (curr->is_rmw() && act->is_rmw() && curr->get_reads_from() == act->get_reads_from() && isfeasibleotherthanRMW())) {
1255                                                 struct PendingFutureValue pfv = {curr->get_value(),curr->get_seq_number()+params.maxfuturedelay,act};
1256                                                 futurevalues->push_back(pfv);
1257                                         }
1258                                 }
1259                         }
1260                 }
1261         }
1262
1263         return added;
1264 }
1265
1266 /** Arbitrary reads from the future are not allowed.  Section 29.3
1267  * part 9 places some constraints.  This method checks one result of constraint
1268  * constraint.  Others require compiler support. */
1269 bool ModelChecker::thin_air_constraint_may_allow(const ModelAction * writer, const ModelAction *reader) {
1270         if (!writer->is_rmw())
1271                 return true;
1272
1273         if (!reader->is_rmw())
1274                 return true;
1275
1276         for (const ModelAction *search = writer->get_reads_from(); search != NULL; search = search->get_reads_from()) {
1277                 if (search == reader)
1278                         return false;
1279                 if (search->get_tid() == reader->get_tid() &&
1280                                 search->happens_before(reader))
1281                         break;
1282         }
1283
1284         return true;
1285 }
1286
1287 /**
1288  * Finds the head(s) of the release sequence(s) containing a given ModelAction.
1289  * The ModelAction under consideration is expected to be taking part in
1290  * release/acquire synchronization as an object of the "reads from" relation.
1291  * Note that this can only provide release sequence support for RMW chains
1292  * which do not read from the future, as those actions cannot be traced until
1293  * their "promise" is fulfilled. Similarly, we may not even establish the
1294  * presence of a release sequence with certainty, as some modification order
1295  * constraints may be decided further in the future. Thus, this function
1296  * "returns" two pieces of data: a pass-by-reference vector of @a release_heads
1297  * and a boolean representing certainty.
1298  *
1299  * @param rf The action that might be part of a release sequence. Must be a
1300  * write.
1301  * @param release_heads A pass-by-reference style return parameter. After
1302  * execution of this function, release_heads will contain the heads of all the
1303  * relevant release sequences, if any exists with certainty
1304  * @param pending A pass-by-reference style return parameter which is only used
1305  * when returning false (i.e., uncertain). Returns most information regarding
1306  * an uncertain release sequence, including any write operations that might
1307  * break the sequence.
1308  * @return true, if the ModelChecker is certain that release_heads is complete;
1309  * false otherwise
1310  */
1311 bool ModelChecker::release_seq_heads(const ModelAction *rf,
1312                 rel_heads_list_t *release_heads,
1313                 struct release_seq *pending) const
1314 {
1315         /* Only check for release sequences if there are no cycles */
1316         if (mo_graph->checkForCycles())
1317                 return false;
1318
1319         while (rf) {
1320                 ASSERT(rf->is_write());
1321
1322                 if (rf->is_release())
1323                         release_heads->push_back(rf);
1324                 if (!rf->is_rmw())
1325                         break; /* End of RMW chain */
1326
1327                 /** @todo Need to be smarter here...  In the linux lock
1328                  * example, this will run to the beginning of the program for
1329                  * every acquire. */
1330                 /** @todo The way to be smarter here is to keep going until 1
1331                  * thread has a release preceded by an acquire and you've seen
1332                  *       both. */
1333
1334                 /* acq_rel RMW is a sufficient stopping condition */
1335                 if (rf->is_acquire() && rf->is_release())
1336                         return true; /* complete */
1337
1338                 rf = rf->get_reads_from();
1339         };
1340         if (!rf) {
1341                 /* read from future: need to settle this later */
1342                 pending->rf = NULL;
1343                 return false; /* incomplete */
1344         }
1345
1346         if (rf->is_release())
1347                 return true; /* complete */
1348
1349         /* else relaxed write; check modification order for contiguous subsequence
1350          * -> rf must be same thread as release */
1351         int tid = id_to_int(rf->get_tid());
1352         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(rf->get_location());
1353         action_list_t *list = &(*thrd_lists)[tid];
1354         action_list_t::const_reverse_iterator rit;
1355
1356         /* Find rf in the thread list */
1357         rit = std::find(list->rbegin(), list->rend(), rf);
1358         ASSERT(rit != list->rend());
1359
1360         /* Find the last write/release */
1361         for (; rit != list->rend(); rit++)
1362                 if ((*rit)->is_release())
1363                         break;
1364         if (rit == list->rend()) {
1365                 /* No write-release in this thread */
1366                 return true; /* complete */
1367         }
1368         ModelAction *release = *rit;
1369
1370         ASSERT(rf->same_thread(release));
1371
1372         pending->writes.clear();
1373
1374         bool certain = true;
1375         for (unsigned int i = 0; i < thrd_lists->size(); i++) {
1376                 if (id_to_int(rf->get_tid()) == (int)i)
1377                         continue;
1378                 list = &(*thrd_lists)[i];
1379
1380                 /* Can we ensure no future writes from this thread may break
1381                  * the release seq? */
1382                 bool future_ordered = false;
1383
1384                 ModelAction *last = get_last_action(int_to_id(i));
1385                 Thread *th = get_thread(int_to_id(i));
1386                 if ((last && rf->happens_before(last)) ||
1387                                 !scheduler->is_enabled(th) ||
1388                                 th->is_complete())
1389                         future_ordered = true;
1390
1391                 ASSERT(!th->is_model_thread() || future_ordered);
1392
1393                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1394                         const ModelAction *act = *rit;
1395                         /* Reach synchronization -> this thread is complete */
1396                         if (act->happens_before(release))
1397                                 break;
1398                         if (rf->happens_before(act)) {
1399                                 future_ordered = true;
1400                                 continue;
1401                         }
1402
1403                         /* Only writes can break release sequences */
1404                         if (!act->is_write())
1405                                 continue;
1406
1407                         /* Check modification order */
1408                         if (mo_graph->checkReachable(rf, act)) {
1409                                 /* rf --mo--> act */
1410                                 future_ordered = true;
1411                                 continue;
1412                         }
1413                         if (mo_graph->checkReachable(act, release))
1414                                 /* act --mo--> release */
1415                                 break;
1416                         if (mo_graph->checkReachable(release, act) &&
1417                                       mo_graph->checkReachable(act, rf)) {
1418                                 /* release --mo-> act --mo--> rf */
1419                                 return true; /* complete */
1420                         }
1421                         /* act may break release sequence */
1422                         pending->writes.push_back(act);
1423                         certain = false;
1424                 }
1425                 if (!future_ordered)
1426                         certain = false; /* This thread is uncertain */
1427         }
1428
1429         if (certain) {
1430                 release_heads->push_back(release);
1431                 pending->writes.clear();
1432         } else {
1433                 pending->release = release;
1434                 pending->rf = rf;
1435         }
1436         return certain;
1437 }
1438
1439 /**
1440  * A public interface for getting the release sequence head(s) with which a
1441  * given ModelAction must synchronize. This function only returns a non-empty
1442  * result when it can locate a release sequence head with certainty. Otherwise,
1443  * it may mark the internal state of the ModelChecker so that it will handle
1444  * the release sequence at a later time, causing @a act to update its
1445  * synchronization at some later point in execution.
1446  * @param act The 'acquire' action that may read from a release sequence
1447  * @param release_heads A pass-by-reference return parameter. Will be filled
1448  * with the head(s) of the release sequence(s), if they exists with certainty.
1449  * @see ModelChecker::release_seq_heads
1450  */
1451 void ModelChecker::get_release_seq_heads(ModelAction *act, rel_heads_list_t *release_heads)
1452 {
1453         const ModelAction *rf = act->get_reads_from();
1454         struct release_seq *sequence = (struct release_seq *)snapshot_calloc(1, sizeof(struct release_seq));
1455         sequence->acquire = act;
1456
1457         if (!release_seq_heads(rf, release_heads, sequence)) {
1458                 /* add act to 'lazy checking' list */
1459                 pending_rel_seqs->push_back(sequence);
1460         } else {
1461                 snapshot_free(sequence);
1462         }
1463 }
1464
1465 /**
1466  * Attempt to resolve all stashed operations that might synchronize with a
1467  * release sequence for a given location. This implements the "lazy" portion of
1468  * determining whether or not a release sequence was contiguous, since not all
1469  * modification order information is present at the time an action occurs.
1470  *
1471  * @param location The location/object that should be checked for release
1472  * sequence resolutions. A NULL value means to check all locations.
1473  * @param work_queue The work queue to which to add work items as they are
1474  * generated
1475  * @return True if any updates occurred (new synchronization, new mo_graph
1476  * edges)
1477  */
1478 bool ModelChecker::resolve_release_sequences(void *location, work_queue_t *work_queue)
1479 {
1480         bool updated = false;
1481         std::vector< struct release_seq *, SnapshotAlloc<struct release_seq *> >::iterator it = pending_rel_seqs->begin();
1482         while (it != pending_rel_seqs->end()) {
1483                 struct release_seq *pending = *it;
1484                 ModelAction *act = pending->acquire;
1485
1486                 /* Only resolve sequences on the given location, if provided */
1487                 if (location && act->get_location() != location) {
1488                         it++;
1489                         continue;
1490                 }
1491
1492                 const ModelAction *rf = act->get_reads_from();
1493                 rel_heads_list_t release_heads;
1494                 bool complete;
1495                 complete = release_seq_heads(rf, &release_heads, pending);
1496                 for (unsigned int i = 0; i < release_heads.size(); i++) {
1497                         if (!act->has_synchronized_with(release_heads[i])) {
1498                                 if (act->synchronize_with(release_heads[i]))
1499                                         updated = true;
1500                                 else
1501                                         set_bad_synchronization();
1502                         }
1503                 }
1504
1505                 if (updated) {
1506                         /* Re-check all pending release sequences */
1507                         work_queue->push_back(CheckRelSeqWorkEntry(NULL));
1508                         /* Re-check act for mo_graph edges */
1509                         work_queue->push_back(MOEdgeWorkEntry(act));
1510
1511                         /* propagate synchronization to later actions */
1512                         action_list_t::reverse_iterator rit = action_trace->rbegin();
1513                         for (; (*rit) != act; rit++) {
1514                                 ModelAction *propagate = *rit;
1515                                 if (act->happens_before(propagate)) {
1516                                         propagate->synchronize_with(act);
1517                                         /* Re-check 'propagate' for mo_graph edges */
1518                                         work_queue->push_back(MOEdgeWorkEntry(propagate));
1519                                 }
1520                         }
1521                 }
1522                 if (complete) {
1523                         it = pending_rel_seqs->erase(it);
1524                         snapshot_free(pending);
1525                 } else {
1526                         it++;
1527                 }
1528         }
1529
1530         // If we resolved promises or data races, see if we have realized a data race.
1531         if (checkDataRaces()) {
1532                 set_assert();
1533         }
1534
1535         return updated;
1536 }
1537
1538 /**
1539  * Performs various bookkeeping operations for the current ModelAction. For
1540  * instance, adds action to the per-object, per-thread action vector and to the
1541  * action trace list of all thread actions.
1542  *
1543  * @param act is the ModelAction to add.
1544  */
1545 void ModelChecker::add_action_to_lists(ModelAction *act)
1546 {
1547         int tid = id_to_int(act->get_tid());
1548         action_trace->push_back(act);
1549
1550         obj_map->get_safe_ptr(act->get_location())->push_back(act);
1551
1552         std::vector<action_list_t> *vec = obj_thrd_map->get_safe_ptr(act->get_location());
1553         if (tid >= (int)vec->size())
1554                 vec->resize(priv->next_thread_id);
1555         (*vec)[tid].push_back(act);
1556
1557         if ((int)thrd_last_action->size() <= tid)
1558                 thrd_last_action->resize(get_num_threads());
1559         (*thrd_last_action)[tid] = act;
1560 }
1561
1562 /**
1563  * @brief Get the last action performed by a particular Thread
1564  * @param tid The thread ID of the Thread in question
1565  * @return The last action in the thread
1566  */
1567 ModelAction * ModelChecker::get_last_action(thread_id_t tid) const
1568 {
1569         int threadid = id_to_int(tid);
1570         if (threadid < (int)thrd_last_action->size())
1571                 return (*thrd_last_action)[id_to_int(tid)];
1572         else
1573                 return NULL;
1574 }
1575
1576 /**
1577  * Gets the last memory_order_seq_cst write (in the total global sequence)
1578  * performed on a particular object (i.e., memory location), not including the
1579  * current action.
1580  * @param curr The current ModelAction; also denotes the object location to
1581  * check
1582  * @return The last seq_cst write
1583  */
1584 ModelAction * ModelChecker::get_last_seq_cst(ModelAction *curr) const
1585 {
1586         void *location = curr->get_location();
1587         action_list_t *list = obj_map->get_safe_ptr(location);
1588         /* Find: max({i in dom(S) | seq_cst(t_i) && isWrite(t_i) && samevar(t_i, t)}) */
1589         action_list_t::reverse_iterator rit;
1590         for (rit = list->rbegin(); rit != list->rend(); rit++)
1591                 if ((*rit)->is_write() && (*rit)->is_seqcst() && (*rit) != curr)
1592                         return *rit;
1593         return NULL;
1594 }
1595
1596 /**
1597  * Gets the last unlock operation performed on a particular mutex (i.e., memory
1598  * location). This function identifies the mutex according to the current
1599  * action, which is presumed to perform on the same mutex.
1600  * @param curr The current ModelAction; also denotes the object location to
1601  * check
1602  * @return The last unlock operation
1603  */
1604 ModelAction * ModelChecker::get_last_unlock(ModelAction *curr) const
1605 {
1606         void *location = curr->get_location();
1607         action_list_t *list = obj_map->get_safe_ptr(location);
1608         /* Find: max({i in dom(S) | isUnlock(t_i) && samevar(t_i, t)}) */
1609         action_list_t::reverse_iterator rit;
1610         for (rit = list->rbegin(); rit != list->rend(); rit++)
1611                 if ((*rit)->is_unlock())
1612                         return *rit;
1613         return NULL;
1614 }
1615
1616 ModelAction * ModelChecker::get_parent_action(thread_id_t tid)
1617 {
1618         ModelAction *parent = get_last_action(tid);
1619         if (!parent)
1620                 parent = get_thread(tid)->get_creation();
1621         return parent;
1622 }
1623
1624 /**
1625  * Returns the clock vector for a given thread.
1626  * @param tid The thread whose clock vector we want
1627  * @return Desired clock vector
1628  */
1629 ClockVector * ModelChecker::get_cv(thread_id_t tid)
1630 {
1631         return get_parent_action(tid)->get_cv();
1632 }
1633
1634 /**
1635  * Resolve a set of Promises with a current write. The set is provided in the
1636  * Node corresponding to @a write.
1637  * @param write The ModelAction that is fulfilling Promises
1638  * @return True if promises were resolved; false otherwise
1639  */
1640 bool ModelChecker::resolve_promises(ModelAction *write)
1641 {
1642         bool resolved = false;
1643   std::vector<thread_id_t> threads_to_check;
1644
1645         for (unsigned int i = 0, promise_index = 0; promise_index < promises->size(); i++) {
1646                 Promise *promise = (*promises)[promise_index];
1647                 if (write->get_node()->get_promise(i)) {
1648                         ModelAction *read = promise->get_action();
1649                         if (read->is_rmw()) {
1650                                 mo_graph->addRMWEdge(write, read);
1651                         }
1652                         read->read_from(write);
1653                         //First fix up the modification order for actions that happened
1654                         //before the read
1655                         r_modification_order(read, write);
1656                         //Next fix up the modification order for actions that happened
1657                         //after the read.
1658                         post_r_modification_order(read, write);
1659                         //Make sure the promise's value matches the write's value
1660                         ASSERT(promise->get_value() == write->get_value());
1661                         delete(promise);
1662                         
1663                         promises->erase(promises->begin() + promise_index);
1664                         threads_to_check.push_back(read->get_tid());
1665
1666                         resolved = true;
1667                 } else
1668                         promise_index++;
1669         }
1670
1671         //Check whether reading these writes has made threads unable to
1672         //resolve promises
1673
1674         for(unsigned int i=0;i<threads_to_check.size();i++)
1675                 mo_check_promises(threads_to_check[i], write);
1676
1677         return resolved;
1678 }
1679
1680 /**
1681  * Compute the set of promises that could potentially be satisfied by this
1682  * action. Note that the set computation actually appears in the Node, not in
1683  * ModelChecker.
1684  * @param curr The ModelAction that may satisfy promises
1685  */
1686 void ModelChecker::compute_promises(ModelAction *curr)
1687 {
1688         for (unsigned int i = 0; i < promises->size(); i++) {
1689                 Promise *promise = (*promises)[i];
1690                 const ModelAction *act = promise->get_action();
1691                 if (!act->happens_before(curr) &&
1692                                 act->is_read() &&
1693                                 !act->could_synchronize_with(curr) &&
1694                                 !act->same_thread(curr) &&
1695                                 promise->get_value() == curr->get_value()) {
1696                         curr->get_node()->set_promise(i);
1697                 }
1698         }
1699 }
1700
1701 /** Checks promises in response to change in ClockVector Threads. */
1702 void ModelChecker::check_promises(thread_id_t tid, ClockVector *old_cv, ClockVector *merge_cv)
1703 {
1704         for (unsigned int i = 0; i < promises->size(); i++) {
1705                 Promise *promise = (*promises)[i];
1706                 const ModelAction *act = promise->get_action();
1707                 if ((old_cv == NULL || !old_cv->synchronized_since(act)) &&
1708                                 merge_cv->synchronized_since(act)) {
1709                         if (promise->increment_threads(tid)) {
1710                                 //Promise has failed
1711                                 failed_promise = true;
1712                                 return;
1713                         }
1714                 }
1715         }
1716 }
1717
1718 /** Checks promises in response to addition to modification order for threads.
1719  * Definitions:
1720  * pthread is the thread that performed the read that created the promise
1721  * 
1722  * pread is the read that created the promise
1723  *
1724  * pwrite is either the first write to same location as pread by
1725  * pthread that is sequenced after pread or the value read by the
1726  * first read to the same lcoation as pread by pthread that is
1727  * sequenced after pread..
1728  *
1729  *      1. If tid=pthread, then we check what other threads are reachable
1730  * through the mode order starting with pwrite.  Those threads cannot
1731  * perform a write that will resolve the promise due to modification
1732  * order constraints.
1733  *
1734  * 2. If the tid is not pthread, we check whether pwrite can reach the
1735  * action write through the modification order.  If so, that thread
1736  * cannot perform a future write that will resolve the promise due to
1737  * modificatin order constraints.
1738  *
1739  *      @parem tid The thread that either read from the model action
1740  *      write, or actually did the model action write.
1741  *
1742  *      @parem write The ModelAction representing the relevant write.
1743  */
1744
1745 void ModelChecker::mo_check_promises(thread_id_t tid, const ModelAction *write) {
1746         void * location = write->get_location();
1747         for (unsigned int i = 0; i < promises->size(); i++) {
1748                 Promise *promise = (*promises)[i];
1749                 const ModelAction *act = promise->get_action();
1750                 
1751                 //Is this promise on the same location?
1752                 if ( act->get_location() != location )
1753                         continue;
1754
1755                 //same thread as the promise
1756                 if ( act->get_tid()==tid ) {
1757
1758                         //do we have a pwrite for the promise, if not, set it
1759                         if (promise->get_write() == NULL ) {
1760                                 promise->set_write(write);
1761                         }
1762                         if (mo_graph->checkPromise(write, promise)) {
1763                                 failed_promise = true;
1764                                 return;
1765                         }
1766                 }
1767                 
1768                 //Don't do any lookups twice for the same thread
1769                 if (promise->has_sync_thread(tid))
1770                         continue;
1771                 
1772                 if (mo_graph->checkReachable(promise->get_write(), write)) {
1773                         if (promise->increment_threads(tid)) {
1774                                 failed_promise = true;
1775                                 return;
1776                         }
1777                 }
1778         }
1779 }
1780
1781 /**
1782  * Compute the set of writes that may break the current pending release
1783  * sequence. This information is extracted from previou release sequence
1784  * calculations.
1785  *
1786  * @param curr The current ModelAction. Must be a release sequence fixup
1787  * action.
1788  */
1789 void ModelChecker::compute_relseq_breakwrites(ModelAction *curr)
1790 {
1791         if (pending_rel_seqs->empty())
1792                 return;
1793
1794         struct release_seq *pending = pending_rel_seqs->back();
1795         for (unsigned int i = 0; i < pending->writes.size(); i++) {
1796                 const ModelAction *write = pending->writes[i];
1797                 curr->get_node()->add_relseq_break(write);
1798         }
1799
1800         /* NULL means don't break the sequence; just synchronize */
1801         curr->get_node()->add_relseq_break(NULL);
1802 }
1803
1804 /**
1805  * Build up an initial set of all past writes that this 'read' action may read
1806  * from. This set is determined by the clock vector's "happens before"
1807  * relationship.
1808  * @param curr is the current ModelAction that we are exploring; it must be a
1809  * 'read' operation.
1810  */
1811 void ModelChecker::build_reads_from_past(ModelAction *curr)
1812 {
1813         std::vector<action_list_t> *thrd_lists = obj_thrd_map->get_safe_ptr(curr->get_location());
1814         unsigned int i;
1815         ASSERT(curr->is_read());
1816
1817         ModelAction *last_seq_cst = NULL;
1818
1819         /* Track whether this object has been initialized */
1820         bool initialized = false;
1821
1822         if (curr->is_seqcst()) {
1823                 last_seq_cst = get_last_seq_cst(curr);
1824                 /* We have to at least see the last sequentially consistent write,
1825                          so we are initialized. */
1826                 if (last_seq_cst != NULL)
1827                         initialized = true;
1828         }
1829
1830         /* Iterate over all threads */
1831         for (i = 0; i < thrd_lists->size(); i++) {
1832                 /* Iterate over actions in thread, starting from most recent */
1833                 action_list_t *list = &(*thrd_lists)[i];
1834                 action_list_t::reverse_iterator rit;
1835                 for (rit = list->rbegin(); rit != list->rend(); rit++) {
1836                         ModelAction *act = *rit;
1837
1838                         /* Only consider 'write' actions */
1839                         if (!act->is_write() || act == curr)
1840                                 continue;
1841
1842                         /* Don't consider more than one seq_cst write if we are a seq_cst read. */
1843                         if (!curr->is_seqcst() || (!act->is_seqcst() && (last_seq_cst == NULL || !act->happens_before(last_seq_cst))) || act == last_seq_cst) {
1844                                 DEBUG("Adding action to may_read_from:\n");
1845                                 if (DBG_ENABLED()) {
1846                                         act->print();
1847                                         curr->print();
1848                                 }
1849                                 curr->get_node()->add_read_from(act);
1850                         }
1851
1852                         /* Include at most one act per-thread that "happens before" curr */
1853                         if (act->happens_before(curr)) {
1854                                 initialized = true;
1855                                 break;
1856                         }
1857                 }
1858         }
1859
1860         if (!initialized) {
1861                 /** @todo Need a more informative way of reporting errors. */
1862                 printf("ERROR: may read from uninitialized atomic\n");
1863         }
1864
1865         if (DBG_ENABLED() || !initialized) {
1866                 printf("Reached read action:\n");
1867                 curr->print();
1868                 printf("Printing may_read_from\n");
1869                 curr->get_node()->print_may_read_from();
1870                 printf("End printing may_read_from\n");
1871         }
1872
1873         ASSERT(initialized);
1874 }
1875
1876 static void print_list(action_list_t *list)
1877 {
1878         action_list_t::iterator it;
1879
1880         printf("---------------------------------------------------------------------\n");
1881         printf("Trace:\n");
1882
1883         for (it = list->begin(); it != list->end(); it++) {
1884                 (*it)->print();
1885         }
1886         printf("---------------------------------------------------------------------\n");
1887 }
1888
1889 #if SUPPORT_MOD_ORDER_DUMP
1890 void ModelChecker::dumpGraph(char *filename) {
1891         char buffer[200];
1892   sprintf(buffer, "%s.dot",filename);
1893   FILE *file=fopen(buffer, "w");
1894   fprintf(file, "digraph %s {\n",filename);
1895         mo_graph->dumpNodes(file);
1896         ModelAction ** thread_array=(ModelAction **)model_calloc(1, sizeof(ModelAction *)*get_num_threads());
1897         
1898         for (action_list_t::iterator it = action_trace->begin(); it != action_trace->end(); it++) {
1899                 ModelAction *action=*it;
1900                 if (action->is_read()) {
1901                         fprintf(file, "N%u [label=\"%u, T%u\"];\n", action->get_seq_number(),action->get_seq_number(), action->get_tid());
1902                         if (action->get_reads_from()!=NULL)
1903                                 fprintf(file, "N%u -> N%u[label=\"rf\", color=red];\n", action->get_seq_number(), action->get_reads_from()->get_seq_number());
1904                 }
1905                 if (thread_array[action->get_tid()] != NULL) {
1906                         fprintf(file, "N%u -> N%u[label=\"sb\", color=blue];\n", thread_array[action->get_tid()]->get_seq_number(), action->get_seq_number());
1907                 }
1908                 
1909                 thread_array[action->get_tid()]=action;
1910         }
1911   fprintf(file,"}\n");
1912         model_free(thread_array);
1913   fclose(file); 
1914 }
1915 #endif
1916
1917 void ModelChecker::print_summary()
1918 {
1919         printf("\n");
1920         printf("Number of executions: %d\n", num_executions);
1921         printf("Number of feasible executions: %d\n", num_feasible_executions);
1922         printf("Total nodes created: %d\n", node_stack->get_total_nodes());
1923
1924 #if SUPPORT_MOD_ORDER_DUMP
1925         scheduler->print();
1926         char buffername[100];
1927         sprintf(buffername, "exec%04u", num_executions);
1928         mo_graph->dumpGraphToFile(buffername);
1929         sprintf(buffername, "graph%04u", num_executions);
1930   dumpGraph(buffername);
1931 #endif
1932
1933         if (!isfinalfeasible())
1934                 printf("INFEASIBLE EXECUTION!\n");
1935         print_list(action_trace);
1936         printf("\n");
1937 }
1938
1939 /**
1940  * Add a Thread to the system for the first time. Should only be called once
1941  * per thread.
1942  * @param t The Thread to add
1943  */
1944 void ModelChecker::add_thread(Thread *t)
1945 {
1946         thread_map->put(id_to_int(t->get_id()), t);
1947         scheduler->add_thread(t);
1948 }
1949
1950 /**
1951  * Removes a thread from the scheduler. 
1952  * @param the thread to remove.
1953  */
1954 void ModelChecker::remove_thread(Thread *t)
1955 {
1956         scheduler->remove_thread(t);
1957 }
1958
1959 /**
1960  * @brief Get a Thread reference by its ID
1961  * @param tid The Thread's ID
1962  * @return A Thread reference
1963  */
1964 Thread * ModelChecker::get_thread(thread_id_t tid) const
1965 {
1966         return thread_map->get(id_to_int(tid));
1967 }
1968
1969 /**
1970  * @brief Get a reference to the Thread in which a ModelAction was executed
1971  * @param act The ModelAction
1972  * @return A Thread reference
1973  */
1974 Thread * ModelChecker::get_thread(ModelAction *act) const
1975 {
1976         return get_thread(act->get_tid());
1977 }
1978
1979 /**
1980  * Switch from a user-context to the "master thread" context (a.k.a. system
1981  * context). This switch is made with the intention of exploring a particular
1982  * model-checking action (described by a ModelAction object). Must be called
1983  * from a user-thread context.
1984  *
1985  * @param act The current action that will be explored. May be NULL only if
1986  * trace is exiting via an assertion (see ModelChecker::set_assert and
1987  * ModelChecker::has_asserted).
1988  * @return Return status from the 'swap' call (i.e., success/fail, 0/-1)
1989  */
1990 int ModelChecker::switch_to_master(ModelAction *act)
1991 {
1992         DBG();
1993         Thread *old = thread_current();
1994         set_current_action(act);
1995         old->set_state(THREAD_READY);
1996         return Thread::swap(old, &system_context);
1997 }
1998
1999 /**
2000  * Takes the next step in the execution, if possible.
2001  * @return Returns true (success) if a step was taken and false otherwise.
2002  */
2003 bool ModelChecker::take_step() {
2004         if (has_asserted())
2005                 return false;
2006
2007         Thread *curr = priv->current_action ? get_thread(priv->current_action) : NULL;
2008         if (curr) {
2009                 if (curr->get_state() == THREAD_READY) {
2010                         ASSERT(priv->current_action);
2011
2012                         priv->nextThread = check_current_action(priv->current_action);
2013                         priv->current_action = NULL;
2014
2015                         if (curr->is_blocked() || curr->is_complete())
2016                                 scheduler->remove_thread(curr);
2017                 } else {
2018                         ASSERT(false);
2019                 }
2020         }
2021         Thread *next = scheduler->next_thread(priv->nextThread);
2022
2023         /* Infeasible -> don't take any more steps */
2024         if (!isfeasible())
2025                 return false;
2026
2027         DEBUG("(%d, %d)\n", curr ? id_to_int(curr->get_id()) : -1,
2028                         next ? id_to_int(next->get_id()) : -1);
2029
2030         /*
2031          * Launch end-of-execution release sequence fixups only when there are:
2032          *
2033          * (1) no more user threads to run (or when execution replay chooses
2034          *     the 'model_thread')
2035          * (2) pending release sequences
2036          * (3) pending assertions (i.e., data races)
2037          * (4) no pending promises
2038          */
2039         if (!pending_rel_seqs->empty() && (!next || next->is_model_thread()) &&
2040                         isfinalfeasible() && !unrealizedraces.empty()) {
2041                 printf("*** WARNING: release sequence fixup action (%zu pending release seuqences) ***\n",
2042                                 pending_rel_seqs->size());
2043                 ModelAction *fixup = new ModelAction(MODEL_FIXUP_RELSEQ,
2044                                 std::memory_order_seq_cst, NULL, VALUE_NONE,
2045                                 model_thread);
2046                 set_current_action(fixup);
2047                 return true;
2048         }
2049
2050         /* next == NULL -> don't take any more steps */
2051         if (!next)
2052                 return false;
2053
2054         next->set_state(THREAD_RUNNING);
2055
2056         if (next->get_pending() != NULL) {
2057                 /* restart a pending action */
2058                 set_current_action(next->get_pending());
2059                 next->set_pending(NULL);
2060                 next->set_state(THREAD_READY);
2061                 return true;
2062         }
2063
2064         /* Return false only if swap fails with an error */
2065         return (Thread::swap(&system_context, next) == 0);
2066 }
2067
2068 /** Runs the current execution until threre are no more steps to take. */
2069 void ModelChecker::finish_execution() {
2070         DBG();
2071
2072         while (take_step());
2073 }