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 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
67 void initMainThread() {
69 Thread * curr_thread = thread_current();
70 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
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
80 Thread * curr_thread = thread_current();
82 /* Add dummy "start" action, just to create a first clock vector */
83 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
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);
95 /* Finish thread properly */
96 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, curr_thread));
100 static int (*pthread_mutex_init_p)(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) = NULL;
102 int real_pthread_mutex_init(pthread_mutex_t *__mutex, const pthread_mutexattr_t *__mutexattr) {
103 return pthread_mutex_init_p(__mutex, __mutexattr);
106 static int (*pthread_mutex_lock_p) (pthread_mutex_t *__mutex) = NULL;
108 int real_pthread_mutex_lock (pthread_mutex_t *__mutex) {
109 return pthread_mutex_lock_p(__mutex);
112 static int (*pthread_mutex_unlock_p) (pthread_mutex_t *__mutex) = NULL;
114 int real_pthread_mutex_unlock (pthread_mutex_t *__mutex) {
115 return pthread_mutex_unlock_p(__mutex);
118 static int (*pthread_create_p) (pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void * __restrict) = NULL;
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);
124 static int (*pthread_join_p) (pthread_t __th, void ** __thread_return) = NULL;
126 int real_pthread_join (pthread_t __th, void ** __thread_return) {
127 return pthread_join_p(__th, __thread_return);
130 static void (*pthread_exit_p)(void *) __attribute__((noreturn))= NULL;
132 void real_pthread_exit (void * value_ptr) {
133 pthread_exit_p(value_ptr);
136 void real_init_all() {
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);
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);
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);
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);
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);
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);
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);
196 void * helper_thread(void * ptr) {
197 Thread * curr_thread = thread_current();
199 //build a context for this real thread so we can take it's context
200 int ret = getcontext(&curr_thread->helpercontext);
204 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)4)) {
205 printf("Destructor setup failed\n");
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 = model->get_system_context();
216 makecontext(&curr_thread->helpercontext, finalize_helper_thread, 0);
218 model_swapcontext(&curr_thread->context, &curr_thread->helpercontext);
221 //start the real thread
228 void tlsdestructor(void *v) {
229 uintptr_t count = (uintptr_t) v;
231 if (pthread_setspecific(model->get_execution()->getPthreadKey(), (const void *)(count - 1))) {
232 printf("Destructor setup failed\n");
237 /* Finish thread properly */
238 model->switch_to_master(new ModelAction(THREAD_FINISH, std::memory_order_seq_cst, thread_current()));
242 void setup_context() {
243 Thread * curr_thread = thread_current();
245 /* Add dummy "start" action, just to create a first clock vector */
246 model->switch_to_master(new ModelAction(THREAD_START, std::memory_order_seq_cst, curr_thread));
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);
255 /* Create the real thread */
256 real_pthread_create(&curr_thread->thread, NULL, helper_thread, NULL);
259 real_pthread_mutex_lock(&curr_thread->mutex);
260 if (curr_thread->tls != NULL)
262 real_pthread_mutex_unlock(&curr_thread->mutex);
265 set_tls_addr((uintptr_t)curr_thread->tls);
266 setcontext(&curr_thread->context);
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
275 int Thread::create_context()
279 ret = getcontext(&context);
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 = model->get_system_context();
290 makecontext(&context, setup_context, 0);
292 makecontext(&context, thread_startup, 0);
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).
307 int Thread::swap(Thread *t, ucontext_t *ctxt)
309 t->set_state(THREAD_READY);
311 set_tls_addr((uintptr_t)model->getInitThread()->tls);
313 return model_swapcontext(&t->context, ctxt);
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).
324 int Thread::swap(ucontext_t *ctxt, Thread *t)
326 t->set_state(THREAD_RUNNING);
329 set_tls_addr((uintptr_t)t->tls);
331 return model_swapcontext(ctxt, &t->context);
335 /** Terminate a thread and free its stack. */
336 void Thread::complete()
338 ASSERT(!is_complete());
339 DEBUG("completed thread %d\n", id_to_int(get_id()));
340 state = THREAD_COMPLETED;
344 if (this != model->getInitThread()) {
345 ASSERT(thread_current()==NULL);
346 real_pthread_mutex_unlock(&mutex2);
347 real_pthread_join(thread, NULL);
348 stack_free(helper_stack);
354 * @brief Construct a new model-checker Thread
356 * A model-checker Thread is used for accounting purposes only. It will never
357 * have its own stack, and it should never be inserted into the Scheduler.
359 * @param tid The thread ID to assign
361 Thread::Thread(thread_id_t tid) :
363 acq_fence_cv(new ClockVector()),
374 state(THREAD_READY), /* Thread is always ready? */
378 memset(&context, 0, sizeof(context));
382 * Construct a new thread.
383 * @param t The thread identifier of the newly created thread.
384 * @param func The function that the thread will call.
385 * @param a The parameter to pass to this function.
387 Thread::Thread(thread_id_t tid, thrd_t *t, void (*func)(void *), void *a, Thread *parent) :
389 acq_fence_cv(new ClockVector()),
393 pstart_routine(NULL),
400 state(THREAD_CREATED),
401 last_action_val(VALUE_NONE),
406 /* Initialize state */
407 ret = create_context();
409 model_print("Error in create_context\n");
411 user_thread->priv = this; // WL
415 * Construct a new thread for pthread.
416 * @param t The thread identifier of the newly created thread.
417 * @param func The function that the thread will call.
418 * @param a The parameter to pass to this function.
420 Thread::Thread(thread_id_t tid, thrd_t *t, void *(*func)(void *), void *a, Thread *parent) :
422 acq_fence_cv(new ClockVector()),
426 pstart_routine(func),
433 state(THREAD_CREATED),
434 last_action_val(VALUE_NONE),
439 /* Initialize state */
440 ret = create_context();
442 model_print("Error in create_context\n");
455 /** @return The thread_id_t corresponding to this Thread object. */
456 thread_id_t Thread::get_id() const
462 * Set a thread's THREAD_* state (@see thread_state)
463 * @param s The state to enter
465 void Thread::set_state(thread_state s)
467 ASSERT(s == THREAD_COMPLETED || state != THREAD_COMPLETED);
472 * Get the Thread that this Thread is immediately waiting on
473 * @return The thread we are waiting on, if any; otherwise NULL
475 Thread * Thread::waiting_on() const
480 if (pending->get_type() == THREAD_JOIN)
481 return pending->get_thread_operand();
482 else if (pending->get_type() == PTHREAD_JOIN)
483 return pending->get_thread_operand();
484 else if (pending->is_lock())
485 return (Thread *)pending->get_mutex()->get_state()->locked;
490 * Check if this Thread is waiting (blocking) on a given Thread, directly or
491 * indirectly (via a chain of waiting threads)
493 * @param t The Thread on which we may be waiting
494 * @return True if we are waiting on Thread t; false otherwise
496 bool Thread::is_waiting_on(const Thread *t) const
499 for (wait = waiting_on();wait != NULL;wait = wait->waiting_on())