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