2 * @brief Thread functions.
10 #include "threads-model.h"
13 /* global "model" object */
15 #include "execution.h"
17 #include "clockvector.h"
21 uintptr_t get_tls_addr() {
23 asm ("mov %%fs:0, %0" : "=r" (addr));
27 #include <asm/prctl.h>
28 #include <sys/prctl.h>
30 int arch_prctl(int code, unsigned long addr);
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");
38 /** Allocate a stack for a new thread. */
39 static void * stack_allocate(size_t size)
41 return Thread_malloc(size);
44 /** Free a stack for a terminated thread. */
45 static void stack_free(void *stack)
51 * @brief Get the current Thread
53 * Must be called from a user context
55 * @return The currently executing thread
57 Thread * thread_current(void)
60 return model->get_current_thread();
64 * @brief Get the current Thread id
66 * Must be called from a user context
68 * @return The id of the currently executing thread
70 thread_id_t thread_current_id(void)
73 return model->get_current_thread_id();
77 model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
80 void initMainThread() {
82 Thread * curr_thread = thread_current();
83 model->switch_thread(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
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
93 Thread * curr_thread = thread_current();
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));
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);
108 /* Finish thread properly */
109 model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, curr_thread));
113 static int (*pthread_mutex_init_p)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) = NULL;
115 int real_pthread_mutex_init(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) {
116 return pthread_mutex_init_p(__mutex, __mutexattr);
119 static int (*pthread_mutex_lock_p) (pthread_mutex_t *__mutex) = NULL;
121 int real_pthread_mutex_lock (pthread_mutex_t *__mutex) {
122 return pthread_mutex_lock_p(__mutex);
125 static int (*pthread_mutex_unlock_p) (pthread_mutex_t *__mutex) = NULL;
127 int real_pthread_mutex_unlock (pthread_mutex_t *__mutex) {
128 return pthread_mutex_unlock_p(__mutex);
131 static int (*pthread_create_p) (pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void * __restrict) = NULL;
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);
137 static int (*pthread_join_p) (pthread_t __th, void ** __thread_return) = NULL;
139 int real_pthread_join (pthread_t __th, void ** __thread_return) {
140 return pthread_join_p(__th, __thread_return);
143 static void (*pthread_exit_p)(void *) __attribute__((noreturn))= NULL;
145 void real_pthread_exit (void * value_ptr) {
146 pthread_exit_p(value_ptr);
149 void real_init_all() {
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);
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);
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);
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);
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);
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);
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);
209 void * helper_thread(void * ptr) {
210 Thread * curr_thread = thread_current();
212 //build a context for this real thread so we can take it's context
213 int ret = getcontext(&curr_thread->helpercontext);
217 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)4)) {
218 printf("Destructor setup failed\n");
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);
231 model_swapcontext(&curr_thread->context, &curr_thread->helpercontext);
234 //start the real thread
241 void tlsdestructor(void *v) {
242 uintptr_t count = (uintptr_t) v;
244 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)(count - 1))) {
245 printf("Destructor setup failed\n");
250 /* Finish thread properly */
251 model->switch_thread(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
255 void setup_context() {
256 Thread * curr_thread = thread_current();
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));
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);
268 /* Create the real thread */
269 real_pthread_create(&curr_thread->thread, NULL, helper_thread, NULL);
272 real_pthread_mutex_lock(&curr_thread->mutex);
273 if (curr_thread->tls != NULL)
275 real_pthread_mutex_unlock(&curr_thread->mutex);
278 set_tls_addr((uintptr_t)curr_thread->tls);
279 setcontext(&curr_thread->context);
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
288 int Thread::create_context()
292 ret = getcontext(&context);
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;
303 makecontext(&context, setup_context, 0);
305 makecontext(&context, thread_startup, 0);
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).
320 int Thread::swap(Thread *t, ucontext_t *ctxt)
322 t->set_state(THREAD_READY);
324 set_tls_addr((uintptr_t)model->getInitThread()->tls);
326 return model_swapcontext(&t->context, ctxt);
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).
337 int Thread::swap(ucontext_t *ctxt, Thread *t)
339 t->set_state(THREAD_RUNNING);
342 set_tls_addr((uintptr_t)t->tls);
344 return model_swapcontext(ctxt, &t->context);
347 int Thread::swap(Thread *t, Thread *t2)
349 t2->set_state(THREAD_RUNNING);
355 set_tls_addr((uintptr_t)t2->tls);
357 return model_swapcontext(&t->context, &t2->context);
360 /** Terminate a thread. */
361 void Thread::complete()
363 ASSERT(!is_complete());
364 DEBUG("completed thread %d\n", id_to_int(get_id()));
365 state = THREAD_COMPLETED;
368 void Thread::freeResources() {
372 if (this != model->getInitThread()) {
373 real_pthread_mutex_unlock(&mutex2);
374 real_pthread_join(thread, NULL);
375 stack_free(helper_stack);
378 state = THREAD_FREED;
382 * @brief Construct a new model-checker Thread
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.
387 * @param tid The thread ID to assign
389 Thread::Thread(thread_id_t tid) :
391 acq_fence_cv(new ClockVector()),
403 state(THREAD_READY), /* Thread is always ready? */
407 memset(&context, 0, sizeof(context));
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.
416 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
418 acq_fence_cv(new ClockVector()),
423 pstart_routine(NULL),
430 state(THREAD_CREATED),
431 last_action_val(VALUE_NONE),
436 /* Initialize state */
437 ret = create_context();
439 model_print("Error in create_context\n");
441 user_thread->priv = this; // WL
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.
450 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
452 acq_fence_cv(new ClockVector()),
457 pstart_routine(func),
464 state(THREAD_CREATED),
465 last_action_val(VALUE_NONE),
470 /* Initialize state */
471 ret = create_context();
473 model_print("Error in create_context\n");
486 /** @return The thread_id_t corresponding to this Thread object. */
487 thread_id_t Thread::get_id() const
493 * Set a thread's THREAD_* state (@see thread_state)
494 * @param s The state to enter
496 void Thread::set_state(thread_state s)
498 ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
503 * Get the Thread that this Thread is immediately waiting on
504 * @return The thread we are waiting on, if any; otherwise NULL
506 Thread * Thread::waiting_on() const
511 if (pending->get_type() == THREAD_JOIN)
512 return pending->get_thread_operand();
513 else if (pending->get_type() == PTHREAD_JOIN)
514 return pending->get_thread_operand();
515 else if (pending->is_lock())
516 return (Thread *)pending->get_mutex()->get_state()->locked;
521 * Check if this Thread is waiting (blocking) on a given Thread, directly or
522 * indirectly (via a chain of waiting threads)
524 * @param t The Thread on which we may be waiting
525 * @return True if we are waiting on Thread t; false otherwise
527 bool Thread::is_waiting_on(const Thread *t) const
531 // One thread relocks a recursive mutex
532 if (waiting_on() == t && pending->is_lock()) {
533 int mutex_type = pending->get_mutex()->get_state()->type;
534 if (mutex_type == PTHREAD_MUTEX_RECURSIVE)
538 for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())