fix mutex_trylock bug
[c11tester.git] / threads.cc
1 /** @file threads.cc
2  *  @brief Thread functions.
3  */
4
5 #include <string.h>
6
7 #include <threads.h>
8 #include "mutex.h"
9 #include "common.h"
10 #include "threads-model.h"
11 #include "action.h"
12
13 /* global "model" object */
14 #include "model.h"
15 #include "execution.h"
16 #include "schedule.h"
17 #include "clockvector.h"
18
19 #ifdef TLS
20 #include <dlfcn.h>
21 uintptr_t get_tls_addr() {
22         uintptr_t addr;
23         asm ("mov %%fs:0, %0" : "=r" (addr));
24         return addr;
25 }
26
27 #include <asm/prctl.h>
28 #include <sys/prctl.h>
29 extern "C" {
30 int arch_prctl(int code, unsigned long addr);
31 }
32 static void set_tls_addr(uintptr_t addr) {
33         arch_prctl(ARCH_SET_FS, addr);
34         asm ("mov %0, %%fs:0" : : "r" (addr) : "memory");
35 }
36 #endif
37
38 /** Allocate a stack for a new thread. */
39 static void * stack_allocate(size_t size)
40 {
41         return Thread_malloc(size);
42 }
43
44 /** Free a stack for a terminated thread. */
45 static void stack_free(void *stack)
46 {
47         Thread_free(stack);
48 }
49
50 /**
51  * @brief Get the current Thread
52  *
53  * Must be called from a user context
54  *
55  * @return The currently executing thread
56  */
57 Thread * thread_current(void)
58 {
59         ASSERT(model);
60         return model->get_current_thread();
61 }
62
63 /**
64  * @brief Get the current Thread id
65  *
66  * Must be called from a user context
67  *
68  * @return The id of the currently executing thread
69  */
70 thread_id_t thread_current_id(void)
71 {
72         ASSERT(model);
73         return model->get_current_thread_id();
74 }
75
76 void modelexit() {
77         model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
78 }
79
80 void initMainThread() {
81         atexit(modelexit);
82         Thread * curr_thread = thread_current();
83         model->switch_thread(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
84 }
85
86 /**
87  * Provides a startup wrapper for each thread, allowing some initial
88  * model-checking data to be recorded. This method also gets around makecontext
89  * not being 64-bit clean
90  */
91 void thread_startup()
92 {
93         Thread * curr_thread = thread_current();
94 #ifndef TLS
95         /* Add dummy "start" action, just to create a first clock vector */
96         model->switch_thread(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
97 #endif
98
99         /* Call the actual thread function */
100         if (curr_thread->start_routine != NULL) {
101                 curr_thread->start_routine(curr_thread->arg);
102         } else if (curr_thread->pstart_routine != NULL) {
103                 // set pthread return value
104                 void *retval = curr_thread->pstart_routine(curr_thread->arg);
105                 curr_thread->set_pthread_return(retval);
106         }
107 #ifndef TLS
108         /* Finish thread properly */
109         model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, curr_thread));
110 #endif
111 }
112
113 static int (*pthread_mutex_init_p)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) = NULL;
114
115 int real_pthread_mutex_init(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) {
116         return pthread_mutex_init_p(__mutex, __mutexattr);
117 }
118
119 static int (*pthread_mutex_lock_p) (pthread_mutex_t *__mutex) = NULL;
120
121 int real_pthread_mutex_lock (pthread_mutex_t *__mutex) {
122         return pthread_mutex_lock_p(__mutex);
123 }
124
125 static int (*pthread_mutex_unlock_p) (pthread_mutex_t *__mutex) = NULL;
126
127 int real_pthread_mutex_unlock (pthread_mutex_t *__mutex) {
128         return pthread_mutex_unlock_p(__mutex);
129 }
130
131 static int (*pthread_create_p) (pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void * __restrict) = NULL;
132
133 int real_pthread_create (pthread_t *__restrict __newthread, const pthread_attr_t *__restrict __attr, void *(*__start_routine)(void *), void *__restrict __arg) {
134         return pthread_create_p(__newthread, __attr, __start_routine, __arg);
135 }
136
137 static int (*pthread_join_p) (pthread_t __th, void ** __thread_return) = NULL;
138
139 int real_pthread_join (pthread_t __th, void ** __thread_return) {
140         return pthread_join_p(__th, __thread_return);
141 }
142
143 static void (*pthread_exit_p)(void *) __attribute__((noreturn))= NULL;
144
145 void real_pthread_exit (void * value_ptr) {
146         pthread_exit_p(value_ptr);
147 }
148
149 void real_init_all() {
150         char * error;
151         if (!pthread_mutex_init_p) {
152                 pthread_mutex_init_p = (int (*)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr))dlsym(RTLD_NEXT, "pthread_mutex_init");
153                 if ((error = dlerror()) != NULL) {
154                         fputs(error, stderr);
155                         exit(EXIT_FAILURE);
156                 }
157         }
158         if (!pthread_mutex_lock_p) {
159                 pthread_mutex_lock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_lock");
160                 if ((error = dlerror()) != NULL) {
161                         fputs(error, stderr);
162                         exit(EXIT_FAILURE);
163                 }
164         }
165         if (!pthread_mutex_unlock_p) {
166                 pthread_mutex_unlock_p = (int (*)(pthread_mutex_t *__mutex))dlsym(RTLD_NEXT, "pthread_mutex_unlock");
167                 if ((error = dlerror()) != NULL) {
168                         fputs(error, stderr);
169                         exit(EXIT_FAILURE);
170                 }
171         }
172         if (!pthread_create_p) {
173                 pthread_create_p = (int (*)(pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void *__restrict))dlsym(RTLD_NEXT, "pthread_create");
174                 if ((error = dlerror()) != NULL) {
175                         fputs(error, stderr);
176                         exit(EXIT_FAILURE);
177                 }
178         }
179         if (!pthread_join_p) {
180                 pthread_join_p = (int (*)(pthread_t __th, void ** __thread_return))dlsym(RTLD_NEXT, "pthread_join");
181                 if ((error = dlerror()) != NULL) {
182                         fputs(error, stderr);
183                         exit(EXIT_FAILURE);
184                 }
185         }
186
187         if (!pthread_exit_p) {
188                 *((void (**)(void *)) &pthread_exit_p) = (void (*)(void *))dlsym(RTLD_NEXT, "pthread_exit");
189                 if ((error = dlerror()) != NULL) {
190                         fputs(error, stderr);
191                         exit(EXIT_FAILURE);
192                 }
193         }
194 }
195
196 #ifdef TLS
197 void finalize_helper_thread() {
198         Thread * curr_thread = thread_current();
199         real_pthread_mutex_lock(&curr_thread->mutex);
200         curr_thread->tls = (char *) get_tls_addr();
201         real_pthread_mutex_unlock(&curr_thread->mutex);
202         //Wait in the kernel until it is time for us to finish
203         real_pthread_mutex_lock(&curr_thread->mutex2);
204         real_pthread_mutex_unlock(&curr_thread->mutex2);
205         //return to helper thread function
206         setcontext(&curr_thread->context);
207 }
208
209 void * helper_thread(void * ptr) {
210         Thread * curr_thread = thread_current();
211
212         //build a context for this real thread so we can take it's context
213         int ret = getcontext(&curr_thread->helpercontext);
214         ASSERT(!ret);
215
216         //Setup destructor
217         if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)4)) {
218                 printf("Destructor setup failed\n");
219                 exit(-1);
220         }
221
222
223         /* Initialize new managed context */
224         curr_thread->helper_stack = stack_allocate(STACK_SIZE);
225         curr_thread->helpercontext.uc_stack.ss_sp = curr_thread->helper_stack;
226         curr_thread->helpercontext.uc_stack.ss_size = STACK_SIZE;
227         curr_thread->helpercontext.uc_stack.ss_flags = 0;
228         curr_thread->helpercontext.uc_link = NULL;
229         makecontext(&curr_thread->helpercontext, finalize_helper_thread, 0);
230
231         model_swapcontext(&curr_thread->context, &curr_thread->helpercontext);
232
233
234         //start the real thread
235         thread_startup();
236
237         return NULL;
238 }
239
240 #ifdef TLS
241 void tlsdestructor(void *v) {
242         uintptr_t count = (uintptr_t) v;
243         if (count > 1) {
244                 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)(count - 1))) {
245                         printf("Destructor setup failed\n");
246                         exit(-1);
247                 }
248                 return;
249         }
250         /* Finish thread properly */
251         model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
252 }
253 #endif
254
255 void setup_context() {
256         Thread * curr_thread = thread_current();
257
258         /* Add dummy "start" action, just to create a first clock vector */
259         model->switch_thread(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
260
261         real_init_all();
262
263         /* Initialize our lock */
264         real_pthread_mutex_init(&curr_thread->mutex, NULL);
265         real_pthread_mutex_init(&curr_thread->mutex2, NULL);
266         real_pthread_mutex_lock(&curr_thread->mutex2);
267
268         /* Create the real thread */
269         real_pthread_create(&curr_thread->thread, NULL, helper_thread, NULL);
270         bool notdone = true;
271         while(notdone) {
272                 real_pthread_mutex_lock(&curr_thread->mutex);
273                 if (curr_thread->tls != NULL)
274                         notdone = false;
275                 real_pthread_mutex_unlock(&curr_thread->mutex);
276         }
277
278         set_tls_addr((uintptr_t)curr_thread->tls);
279         setcontext(&curr_thread->context);
280 }
281 #endif
282
283 /**
284  * Create a thread context for a new thread so we can use
285  * setcontext/getcontext/swapcontext to swap it out.
286  * @return 0 on success; otherwise, non-zero error condition
287  */
288 int Thread::create_context()
289 {
290         int ret;
291
292         ret = getcontext(&context);
293         if (ret)
294                 return ret;
295
296         /* Initialize new managed context */
297         stack = stack_allocate(STACK_SIZE);
298         context.uc_stack.ss_sp = stack;
299         context.uc_stack.ss_size = STACK_SIZE;
300         context.uc_stack.ss_flags = 0;
301         context.uc_link = NULL;
302 #ifdef TLS
303         makecontext(&context, setup_context, 0);
304 #else
305         makecontext(&context, thread_startup, 0);
306 #endif
307
308         return 0;
309 }
310
311 /**
312  * Swaps the current context to another thread of execution. This form switches
313  * from a user Thread to a system context.
314  * @param t Thread representing the currently-running thread. The current
315  * context is saved here.
316  * @param ctxt Context to which we will swap. Must hold a valid system context.
317  * @return Does not return, unless we return to Thread t's context. See
318  * swapcontext(3) (returns 0 for success, -1 for failure).
319  */
320 int Thread::swap(Thread *t, ucontext_t *ctxt)
321 {
322         t->set_state(THREAD_READY);
323 #ifdef TLS
324         set_tls_addr((uintptr_t)model->getInitThread()->tls);
325 #endif
326         return model_swapcontext(&t->context, ctxt);
327 }
328
329 /**
330  * Swaps the current context to another thread of execution. This form switches
331  * from a system context to a user Thread.
332  * @param ctxt System context variable to which to save the current context.
333  * @param t Thread to which we will swap. Must hold a valid user context.
334  * @return Does not return, unless we return to the system context (ctxt). See
335  * swapcontext(3) (returns 0 for success, -1 for failure).
336  */
337 int Thread::swap(ucontext_t *ctxt, Thread *t)
338 {
339         t->set_state(THREAD_RUNNING);
340 #ifdef TLS
341         if (t->tls != NULL)
342                 set_tls_addr((uintptr_t)t->tls);
343 #endif
344         return model_swapcontext(ctxt, &t->context);
345 }
346
347 int Thread::swap(Thread *t, Thread *t2)
348 {
349         t2->set_state(THREAD_RUNNING);
350         if (t == t2)
351                 return 0;
352
353 #ifdef TLS
354         if (t2->tls != NULL)
355                 set_tls_addr((uintptr_t)t2->tls);
356 #endif
357         return model_swapcontext(&t->context, &t2->context);
358 }
359
360 /** Terminate a thread. */
361 void Thread::complete()
362 {
363         ASSERT(!is_complete());
364         DEBUG("completed thread %d\n", id_to_int(get_id()));
365         state = THREAD_COMPLETED;
366 }
367
368 void Thread::freeResources() {
369         if (stack)
370                 stack_free(stack);
371 #ifdef TLS
372         if (this != model->getInitThread()) {
373                 real_pthread_mutex_unlock(&mutex2);
374                 real_pthread_join(thread, NULL);
375                 stack_free(helper_stack);
376         }
377 #endif
378         state = THREAD_FREED;
379 }
380
381 /**
382  * @brief Construct a new model-checker Thread
383  *
384  * A model-checker Thread is used for accounting purposes only. It will never
385  * have its own stack, and it should never be inserted into the Scheduler.
386  *
387  * @param tid The thread ID to assign
388  */
389 Thread::Thread(thread_id_t tid) :
390         parent(NULL),
391         acq_fence_cv(new ClockVector()),
392         creation(NULL),
393         pending(NULL),
394         wakeup_state(false),
395         start_routine(NULL),
396         arg(NULL),
397         stack(NULL),
398 #ifdef TLS
399         tls(NULL),
400 #endif
401         user_thread(NULL),
402         id(tid),
403         state(THREAD_READY),    /* Thread is always ready? */
404         last_action_val(0),
405         model_thread(true)
406 {
407         memset(&context, 0, sizeof(context));
408 }
409
410 /**
411  * Construct a new thread.
412  * @param t The thread identifier of the newly created thread.
413  * @param func The function that the thread will call.
414  * @param a The parameter to pass to this function.
415  */
416 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
417         parent(parent),
418         acq_fence_cv(new ClockVector()),
419         creation(NULL),
420         pending(NULL),
421         wakeup_state(false),
422         start_routine(func),
423         pstart_routine(NULL),
424         arg(a),
425 #ifdef TLS
426         tls(NULL),
427 #endif
428         user_thread(t),
429         id(tid),
430         state(THREAD_CREATED),
431         last_action_val(VALUE_NONE),
432         model_thread(false)
433 {
434         int ret;
435
436         /* Initialize state */
437         ret = create_context();
438         if (ret)
439                 model_print("Error in create_context\n");
440
441         user_thread->priv = this;       // WL
442 }
443
444 /**
445  * Construct a new thread for pthread.
446  * @param t The thread identifier of the newly created thread.
447  * @param func The function that the thread will call.
448  * @param a The parameter to pass to this function.
449  */
450 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
451         parent(parent),
452         acq_fence_cv(new ClockVector()),
453         creation(NULL),
454         pending(NULL),
455         wakeup_state(false),
456         start_routine(NULL),
457         pstart_routine(func),
458         arg(a),
459 #ifdef TLS
460         tls(NULL),
461 #endif
462         user_thread(t),
463         id(tid),
464         state(THREAD_CREATED),
465         last_action_val(VALUE_NONE),
466         model_thread(false)
467 {
468         int ret;
469
470         /* Initialize state */
471         ret = create_context();
472         if (ret)
473                 model_print("Error in create_context\n");
474 }
475
476
477 /** Destructor */
478 Thread::~Thread()
479 {
480         if (!is_complete())
481                 complete();
482
483         delete acq_fence_cv;
484 }
485
486 /** @return The thread_id_t corresponding to this Thread object. */
487 thread_id_t Thread::get_id() const
488 {
489         return id;
490 }
491
492 /**
493  * Set a thread's THREAD_* state (@see thread_state)
494  * @param s The state to enter
495  */
496 void Thread::set_state(thread_state s)
497 {
498         ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
499         state = s;
500 }
501
502 /**
503  * Get the Thread that this Thread is immediately waiting on
504  * @return The thread we are waiting on, if any; otherwise NULL
505  */
506 Thread * Thread::waiting_on() const
507 {
508         if (!pending)
509                 return NULL;
510
511         switch (pending->get_type()) {
512                 case THREAD_JOIN:
513                 case PTHREAD_JOIN:
514                         return pending->get_thread_operand();
515                 case ATOMIC_LOCK:
516                         return (Thread *)pending->get_mutex()->get_state()->locked;
517                 default:
518                         return NULL;
519         }
520 }
521
522 /**
523  * Check if this Thread is waiting (blocking) on a given Thread, directly or
524  * indirectly (via a chain of waiting threads)
525  *
526  * @param t The Thread on which we may be waiting
527  * @return True if we are waiting on Thread t; false otherwise
528  */
529 bool Thread::is_waiting_on(const Thread *t) const
530 {
531         Thread *wait;
532
533         // One thread relocks a recursive mutex
534         if (waiting_on() == t && pending->is_lock()) {
535                 int mutex_type = pending->get_mutex()->get_state()->type;
536                 if (mutex_type == PTHREAD_MUTEX_RECURSIVE)
537                         return false;
538         }
539
540         for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())
541                 if (wait == t)
542                         return true;
543         return false;
544 }