move thread stack to thread allocator
[model-checker.git] / action.cc
1 #include <stdio.h>
2 #define __STDC_FORMAT_MACROS
3 #include <inttypes.h>
4 #include <stdlib.h>
5
6 #include "model.h"
7 #include "action.h"
8 #include "clockvector.h"
9 #include "common.h"
10 #include "threads-model.h"
11 #include "nodestack.h"
12
13 #define ACTION_INITIAL_CLOCK 0
14
15 /** @brief A special value to represent a successful trylock */
16 #define VALUE_TRYSUCCESS 1
17
18 /** @brief A special value to represent a failed trylock */
19 #define VALUE_TRYFAILED 0
20
21 /**
22  * @brief Construct a new ModelAction
23  *
24  * @param type The type of action
25  * @param order The memory order of this action. A "don't care" for non-ATOMIC
26  * actions (e.g., THREAD_* or MODEL_* actions).
27  * @param loc The location that this action acts upon
28  * @param value (optional) A value associated with the action (e.g., the value
29  * read or written). Defaults to a given macro constant, for debugging purposes.
30  * @param thread (optional) The Thread in which this action occurred. If NULL
31  * (default), then a Thread is assigned according to the scheduler.
32  */
33 ModelAction::ModelAction(action_type_t type, memory_order order, void *loc,
34                 uint64_t value, Thread *thread) :
35         type(type),
36         order(order),
37         location(loc),
38         value(value),
39         reads_from(NULL),
40         reads_from_promise(NULL),
41         last_fence_release(NULL),
42         node(NULL),
43         seq_number(ACTION_INITIAL_CLOCK),
44         cv(NULL),
45         sleep_flag(false)
46 {
47         /* References to NULL atomic variables can end up here */
48         ASSERT(loc || type == ATOMIC_FENCE || type == MODEL_FIXUP_RELSEQ);
49
50         Thread *t = thread ? thread : thread_current();
51         this->tid = t->get_id();
52 }
53
54 /** @brief ModelAction destructor */
55 ModelAction::~ModelAction()
56 {
57         /**
58          * We can't free the clock vector:
59          * Clock vectors are snapshotting state. When we delete model actions,
60          * they are at the end of the node list and have invalid old clock
61          * vectors which have already been rolled back to an unallocated state.
62          */
63
64         /*
65          if (cv)
66                 delete cv; */
67 }
68
69 void ModelAction::copy_from_new(ModelAction *newaction)
70 {
71         seq_number = newaction->seq_number;
72 }
73
74 void ModelAction::set_seq_number(modelclock_t num)
75 {
76         /* ATOMIC_UNINIT actions should never have non-zero clock */
77         ASSERT(!is_uninitialized());
78         ASSERT(seq_number == ACTION_INITIAL_CLOCK);
79         seq_number = num;
80 }
81
82 bool ModelAction::is_thread_start() const
83 {
84         return type == THREAD_START;
85 }
86
87 bool ModelAction::is_thread_join() const
88 {
89         return type == THREAD_JOIN;
90 }
91
92 bool ModelAction::is_relseq_fixup() const
93 {
94         return type == MODEL_FIXUP_RELSEQ;
95 }
96
97 bool ModelAction::is_mutex_op() const
98 {
99         return type == ATOMIC_LOCK || type == ATOMIC_TRYLOCK || type == ATOMIC_UNLOCK || type == ATOMIC_WAIT || type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
100 }
101
102 bool ModelAction::is_lock() const
103 {
104         return type == ATOMIC_LOCK;
105 }
106
107 bool ModelAction::is_wait() const {
108         return type == ATOMIC_WAIT;
109 }
110
111 bool ModelAction::is_notify() const {
112         return type == ATOMIC_NOTIFY_ONE || type == ATOMIC_NOTIFY_ALL;
113 }
114
115 bool ModelAction::is_notify_one() const {
116         return type == ATOMIC_NOTIFY_ONE;
117 }
118
119 bool ModelAction::is_unlock() const
120 {
121         return type == ATOMIC_UNLOCK;
122 }
123
124 bool ModelAction::is_trylock() const
125 {
126         return type == ATOMIC_TRYLOCK;
127 }
128
129 bool ModelAction::is_success_lock() const
130 {
131         return type == ATOMIC_LOCK || (type == ATOMIC_TRYLOCK && value == VALUE_TRYSUCCESS);
132 }
133
134 bool ModelAction::is_failed_trylock() const
135 {
136         return (type == ATOMIC_TRYLOCK && value == VALUE_TRYFAILED);
137 }
138
139 /** @return True if this operation is performed on a C/C++ atomic variable */
140 bool ModelAction::is_atomic_var() const
141 {
142         return is_read() || could_be_write();
143 }
144
145 bool ModelAction::is_uninitialized() const
146 {
147         return type == ATOMIC_UNINIT;
148 }
149
150 bool ModelAction::is_read() const
151 {
152         return type == ATOMIC_READ || type == ATOMIC_RMWR || type == ATOMIC_RMW;
153 }
154
155 bool ModelAction::is_write() const
156 {
157         return type == ATOMIC_WRITE || type == ATOMIC_RMW || type == ATOMIC_INIT || type == ATOMIC_UNINIT;
158 }
159
160 bool ModelAction::could_be_write() const
161 {
162         return is_write() || is_rmwr();
163 }
164
165 bool ModelAction::is_yield() const
166 {
167         return type == THREAD_YIELD;
168 }
169
170 bool ModelAction::is_rmwr() const
171 {
172         return type == ATOMIC_RMWR;
173 }
174
175 bool ModelAction::is_rmw() const
176 {
177         return type == ATOMIC_RMW;
178 }
179
180 bool ModelAction::is_rmwc() const
181 {
182         return type == ATOMIC_RMWC;
183 }
184
185 bool ModelAction::is_fence() const
186 {
187         return type == ATOMIC_FENCE;
188 }
189
190 bool ModelAction::is_initialization() const
191 {
192         return type == ATOMIC_INIT;
193 }
194
195 bool ModelAction::is_annotation() const
196 {
197         return type == ATOMIC_ANNOTATION;
198 }
199
200 bool ModelAction::is_relaxed() const
201 {
202         return order == std::memory_order_relaxed;
203 }
204
205 bool ModelAction::is_acquire() const
206 {
207         switch (order) {
208         case std::memory_order_acquire:
209         case std::memory_order_acq_rel:
210         case std::memory_order_seq_cst:
211                 return true;
212         default:
213                 return false;
214         }
215 }
216
217 bool ModelAction::is_release() const
218 {
219         switch (order) {
220         case std::memory_order_release:
221         case std::memory_order_acq_rel:
222         case std::memory_order_seq_cst:
223                 return true;
224         default:
225                 return false;
226         }
227 }
228
229 bool ModelAction::is_seqcst() const
230 {
231         return order == std::memory_order_seq_cst;
232 }
233
234 bool ModelAction::same_var(const ModelAction *act) const
235 {
236         if (act->is_wait() || is_wait()) {
237                 if (act->is_wait() && is_wait()) {
238                         if (((void *)value) == ((void *)act->value))
239                                 return true;
240                 } else if (is_wait()) {
241                         if (((void *)value) == act->location)
242                                 return true;
243                 } else if (act->is_wait()) {
244                         if (location == ((void *)act->value))
245                                 return true;
246                 }
247         }
248
249         return location == act->location;
250 }
251
252 bool ModelAction::same_thread(const ModelAction *act) const
253 {
254         return tid == act->tid;
255 }
256
257 void ModelAction::copy_typeandorder(ModelAction * act)
258 {
259         this->type = act->type;
260         this->order = act->order;
261 }
262
263 /**
264  * Get the Thread which is the operand of this action. This is only valid for
265  * THREAD_* operations (currently only for THREAD_CREATE and THREAD_JOIN). Note
266  * that this provides a central place for determining the conventions of Thread
267  * storage in ModelAction, where we generally aren't very type-safe (e.g., we
268  * store object references in a (void *) address.
269  *
270  * For THREAD_CREATE, this yields the Thread which is created.
271  * For THREAD_JOIN, this yields the Thread we are joining with.
272  *
273  * @return The Thread which this action acts on, if exists; otherwise NULL
274  */
275 Thread * ModelAction::get_thread_operand() const
276 {
277         if (type == THREAD_CREATE) {
278                 /* THREAD_CREATE stores its (Thread *) in a thrd_t::priv */
279                 thrd_t *thrd = (thrd_t *)get_location();
280                 return thrd->priv;
281         } else if (type == THREAD_JOIN)
282                 /* THREAD_JOIN uses (Thread *) for location */
283                 return (Thread *)get_location();
284         else
285                 return NULL;
286 }
287
288 /**
289  * @brief Convert the read portion of an RMW
290  *
291  * Changes an existing read part of an RMW action into either:
292  *  -# a full RMW action in case of the completed write or
293  *  -# a READ action in case a failed action.
294  *
295  * @todo  If the memory_order changes, we may potentially need to update our
296  * clock vector.
297  *
298  * @param act The second half of the RMW (either RMWC or RMW)
299  */
300 void ModelAction::process_rmw(ModelAction *act)
301 {
302         this->order = act->order;
303         if (act->is_rmwc())
304                 this->type = ATOMIC_READ;
305         else if (act->is_rmw()) {
306                 this->type = ATOMIC_RMW;
307                 this->value = act->value;
308         }
309 }
310
311 /**
312  * @brief Check if this action should be backtracked with another, due to
313  * potential synchronization
314  *
315  * The is_synchronizing method should only explore interleavings if:
316  *  -# the operations are seq_cst and don't commute or
317  *  -# the reordering may establish or break a synchronization relation.
318  *
319  * Other memory operations will be dealt with by using the reads_from relation.
320  *
321  * @param act The action to consider exploring a reordering
322  * @return True, if we have to explore a reordering; otherwise false
323  */
324 bool ModelAction::could_synchronize_with(const ModelAction *act) const
325 {
326         // Same thread can't be reordered
327         if (same_thread(act))
328                 return false;
329
330         // Different locations commute
331         if (!same_var(act))
332                 return false;
333
334         // Explore interleavings of seqcst writes/fences to guarantee total
335         // order of seq_cst operations that don't commute
336         if ((could_be_write() || act->could_be_write() || is_fence() || act->is_fence()) && is_seqcst() && act->is_seqcst())
337                 return true;
338
339         // Explore synchronizing read/write pairs
340         if (is_acquire() && act->is_release() && is_read() && act->could_be_write())
341                 return true;
342
343         // lock just released...we can grab lock
344         if ((is_lock() || is_trylock()) && (act->is_unlock() || act->is_wait()))
345                 return true;
346
347         // lock just acquired...we can fail to grab lock
348         if (is_trylock() && act->is_success_lock())
349                 return true;
350
351         // other thread stalling on lock...we can release lock
352         if (is_unlock() && (act->is_trylock() || act->is_lock()))
353                 return true;
354
355         if (is_trylock() && (act->is_unlock() || act->is_wait()))
356                 return true;
357
358         if (is_notify() && act->is_wait())
359                 return true;
360
361         if (is_wait() && act->is_notify())
362                 return true;
363
364         // Otherwise handle by reads_from relation
365         return false;
366 }
367
368 bool ModelAction::is_conflicting_lock(const ModelAction *act) const
369 {
370         // Must be different threads to reorder
371         if (same_thread(act))
372                 return false;
373
374         // Try to reorder a lock past a successful lock
375         if (act->is_success_lock())
376                 return true;
377
378         // Try to push a successful trylock past an unlock
379         if (act->is_unlock() && is_trylock() && value == VALUE_TRYSUCCESS)
380                 return true;
381
382         // Try to push a successful trylock past a wait
383         if (act->is_wait() && is_trylock() && value == VALUE_TRYSUCCESS)
384                 return true;
385
386         return false;
387 }
388
389 /**
390  * Create a new clock vector for this action. Note that this function allows a
391  * user to clobber (and leak) a ModelAction's existing clock vector. A user
392  * should ensure that the vector has already either been rolled back
393  * (effectively "freed") or freed.
394  *
395  * @param parent A ModelAction from which to inherit a ClockVector
396  */
397 void ModelAction::create_cv(const ModelAction *parent)
398 {
399         if (parent)
400                 cv = new ClockVector(parent->cv, this);
401         else
402                 cv = new ClockVector(NULL, this);
403 }
404
405 void ModelAction::set_try_lock(bool obtainedlock)
406 {
407         value = obtainedlock ? VALUE_TRYSUCCESS : VALUE_TRYFAILED;
408 }
409
410 /**
411  * @brief Get the value read by this load
412  *
413  * We differentiate this function from ModelAction::get_write_value and
414  * ModelAction::get_value for the purpose of RMW's, which may have both a
415  * 'read' and a 'write' value.
416  *
417  * Note: 'this' must be a load.
418  *
419  * @return The value read by this load
420  */
421 uint64_t ModelAction::get_reads_from_value() const
422 {
423         ASSERT(is_read());
424         if (reads_from)
425                 return reads_from->get_write_value();
426         else if (reads_from_promise)
427                 return reads_from_promise->get_value();
428         return VALUE_NONE; /* Only for new actions with no reads-from */
429 }
430
431 /**
432  * @brief Get the value written by this store
433  *
434  * We differentiate this function from ModelAction::get_reads_from_value and
435  * ModelAction::get_value for the purpose of RMW's, which may have both a
436  * 'read' and a 'write' value.
437  *
438  * Note: 'this' must be a store.
439  *
440  * @return The value written by this store
441  */
442 uint64_t ModelAction::get_write_value() const
443 {
444         ASSERT(is_write());
445         return value;
446 }
447
448 /**
449  * @brief Get the value returned by this action
450  *
451  * For atomic reads (including RMW), an operation returns the value it read.
452  * For atomic writes, an operation returns the value it wrote. For other
453  * operations, the return value varies (sometimes is a "don't care"), but the
454  * value is simply stored in the "value" field.
455  *
456  * @return This action's return value
457  */
458 uint64_t ModelAction::get_return_value() const
459 {
460         if (is_read())
461                 return get_reads_from_value();
462         else if (is_write())
463                 return get_write_value();
464         else
465                 return value;
466 }
467
468 /** @return The Node associated with this ModelAction */
469 Node * ModelAction::get_node() const
470 {
471         /* UNINIT actions do not have a Node */
472         ASSERT(!is_uninitialized());
473         return node;
474 }
475
476 /**
477  * Update the model action's read_from action
478  * @param act The action to read from; should be a write
479  */
480 void ModelAction::set_read_from(const ModelAction *act)
481 {
482         ASSERT(act);
483         reads_from = act;
484         reads_from_promise = NULL;
485         if (act->is_uninitialized())
486                 model->assert_bug("May read from uninitialized atomic:\n"
487                                 "    action %d, thread %d, location %p (%s, %s)",
488                                 seq_number, id_to_int(tid), location,
489                                 get_type_str(), get_mo_str());
490 }
491
492 /**
493  * Set this action's read-from promise
494  * @param promise The promise to read from
495  */
496 void ModelAction::set_read_from_promise(Promise *promise)
497 {
498         ASSERT(is_read());
499         reads_from_promise = promise;
500         reads_from = NULL;
501 }
502
503 /**
504  * Synchronize the current thread with the thread corresponding to the
505  * ModelAction parameter.
506  * @param act The ModelAction to synchronize with
507  * @return True if this is a valid synchronization; false otherwise
508  */
509 bool ModelAction::synchronize_with(const ModelAction *act)
510 {
511         if (*this < *act)
512                 return false;
513         cv->merge(act->cv);
514         return true;
515 }
516
517 bool ModelAction::has_synchronized_with(const ModelAction *act) const
518 {
519         return cv->synchronized_since(act);
520 }
521
522 /**
523  * Check whether 'this' happens before act, according to the memory-model's
524  * happens before relation. This is checked via the ClockVector constructs.
525  * @return true if this action's thread has synchronized with act's thread
526  * since the execution of act, false otherwise.
527  */
528 bool ModelAction::happens_before(const ModelAction *act) const
529 {
530         return act->cv->synchronized_since(this);
531 }
532
533 const char * ModelAction::get_type_str() const
534 {
535         switch (this->type) {
536                 case MODEL_FIXUP_RELSEQ: return "relseq fixup";
537                 case THREAD_CREATE: return "thread create";
538                 case THREAD_START: return "thread start";
539                 case THREAD_YIELD: return "thread yield";
540                 case THREAD_JOIN: return "thread join";
541                 case THREAD_FINISH: return "thread finish";
542                 case ATOMIC_UNINIT: return "uninitialized";
543                 case ATOMIC_READ: return "atomic read";
544                 case ATOMIC_WRITE: return "atomic write";
545                 case ATOMIC_RMW: return "atomic rmw";
546                 case ATOMIC_FENCE: return "fence";
547                 case ATOMIC_RMWR: return "atomic rmwr";
548                 case ATOMIC_RMWC: return "atomic rmwc";
549                 case ATOMIC_INIT: return "init atomic";
550                 case ATOMIC_LOCK: return "lock";
551                 case ATOMIC_UNLOCK: return "unlock";
552                 case ATOMIC_TRYLOCK: return "trylock";
553                 case ATOMIC_WAIT: return "wait";
554                 case ATOMIC_NOTIFY_ONE: return "notify one";
555           case ATOMIC_NOTIFY_ALL: return "notify all";
556           case ATOMIC_ANNOTATION: return "atomic annotation";
557                 default: return "unknown type";
558         };
559 }
560
561 const char * ModelAction::get_mo_str() const
562 {
563         switch (this->order) {
564                 case std::memory_order_relaxed: return "relaxed";
565                 case std::memory_order_acquire: return "acquire";
566                 case std::memory_order_release: return "release";
567                 case std::memory_order_acq_rel: return "acq_rel";
568                 case std::memory_order_seq_cst: return "seq_cst";
569                 default: return "unknown";
570         }
571 }
572
573 /** @brief Print nicely-formatted info about this ModelAction */
574 void ModelAction::print() const
575 {
576         const char *type_str = get_type_str(), *mo_str = get_mo_str();
577
578         model_print("%-4d %-2d   %-13s   %7s  %14p   %-#18" PRIx64,
579                         seq_number, id_to_int(tid), type_str, mo_str, location, get_return_value());
580         if (is_read()) {
581                 if (reads_from)
582                         model_print("  %-3d", reads_from->get_seq_number());
583                 else if (reads_from_promise) {
584                         int idx = reads_from_promise->get_index();
585                         if (idx >= 0)
586                                 model_print("  P%-2d", idx);
587                         else
588                                 model_print("  P? ");
589                 } else
590                         model_print("  ?  ");
591         }
592         if (cv) {
593                 if (is_read())
594                         model_print(" ");
595                 else
596                         model_print("      ");
597                 cv->print();
598         } else
599                 model_print("\n");
600 }
601
602 /** @brief Get a (likely) unique hash for this ModelAction */
603 unsigned int ModelAction::hash() const
604 {
605         unsigned int hash = (unsigned int)this->type;
606         hash ^= ((unsigned int)this->order) << 3;
607         hash ^= seq_number << 5;
608         hash ^= id_to_int(tid) << 6;
609
610         if (is_read()) {
611                if (reads_from)
612                        hash ^= reads_from->get_seq_number();
613                else if (reads_from_promise)
614                        hash ^= reads_from_promise->get_index();
615                hash ^= get_reads_from_value();
616         }
617         return hash;
618 }
619
620 /**
621  * @brief Checks the NodeStack to see if a ModelAction is in our may-read-from set
622  * @param write The ModelAction to check for
623  * @return True if the ModelAction is found; false otherwise
624  */
625 bool ModelAction::may_read_from(const ModelAction *write) const
626 {
627         for (int i = 0; i < node->get_read_from_past_size(); i++)
628                 if (node->get_read_from_past(i) == write)
629                         return true;
630         return false;
631 }
632
633 /**
634  * @brief Checks the NodeStack to see if a Promise is in our may-read-from set
635  * @param promise The Promise to check for
636  * @return True if the Promise is found; false otherwise
637  */
638 bool ModelAction::may_read_from(const Promise *promise) const
639 {
640         for (int i = 0; i < node->get_read_from_promise_size(); i++)
641                 if (node->get_read_from_promise(i) == promise)
642                         return true;
643         return false;
644 }
645
646 /**
647  * Only valid for LOCK, TRY_LOCK, UNLOCK, and WAIT operations.
648  * @return The mutex operated on by this action, if any; otherwise NULL
649  */
650 std::mutex * ModelAction::get_mutex() const
651 {
652         if (is_trylock() || is_lock() || is_unlock())
653                 return (std::mutex *)get_location();
654         else if (is_wait())
655                 return (std::mutex *)get_value();
656         else
657                 return NULL;
658 }