Also send SIGSEGV on EACCES fault
[akaros.git] / user / pthread / pthread.c
index 963b87f..924db08 100644 (file)
@@ -1,3 +1,6 @@
+// Needed for sigmask functions...
+#define _GNU_SOURCE
+
 #include <ros/trapframe.h>
 #include <pthread.h>
 #include <vcore.h>
@@ -21,7 +24,9 @@ struct pthread_queue active_queue = TAILQ_HEAD_INITIALIZER(active_queue);
 struct mcs_pdr_lock queue_lock;
 int threads_ready = 0;
 int threads_active = 0;
+atomic_t threads_total;
 bool can_adjust_vcores = TRUE;
+bool need_tls = TRUE;
 
 /* Array of per-vcore structs to manage waiting on syscalls and handling
  * overflow.  Init'd in pth_init(). */
@@ -37,11 +42,14 @@ void pth_thread_runnable(struct uthread *uthread);
 void pth_thread_paused(struct uthread *uthread);
 void pth_thread_blockon_sysc(struct uthread *uthread, void *sysc);
 void pth_thread_has_blocked(struct uthread *uthread, int flags);
+void pth_thread_refl_fault(struct uthread *uthread, unsigned int trap_nr,
+                           unsigned int err, unsigned long aux);
 void pth_preempt_pending(void);
 void pth_spawn_thread(uintptr_t pc_start, void *data);
 
 /* Event Handlers */
-static void pth_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type);
+static void pth_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type,
+                               void *data);
 
 struct schedule_ops pthread_sched_ops = {
        pth_sched_entry,
@@ -49,6 +57,7 @@ struct schedule_ops pthread_sched_ops = {
        pth_thread_paused,
        pth_thread_blockon_sysc,
        pth_thread_has_blocked,
+       pth_thread_refl_fault,
        0, /* pth_preempt_pending, */
        0, /* pth_spawn_thread, */
 };
@@ -60,6 +69,40 @@ struct schedule_ops *sched_ops = &pthread_sched_ops;
 static void __pthread_free_stack(struct pthread_tcb *pt);
 static int __pthread_allocate_stack(struct pthread_tcb *pt);
 
+/* Trigger a posix signal on a pthread from vcore context */
+static void __pthread_trigger_posix_signal(pthread_t thread, int signo,
+                                           struct siginfo *info)
+{
+       int vcoreid = vcore_id();
+       struct user_context *ctx;
+       if (current_uthread) {
+               struct preempt_data *vcpd = vcpd_of(vcoreid);
+        ctx = &vcpd->uthread_ctx;
+       } else {
+               ctx = &thread->uthread.u_ctx;
+       }
+
+       void *temp_tls_desc = get_tls_desc(vcoreid);
+       set_tls_desc(thread->uthread.tls_desc, vcoreid);
+       trigger_posix_signal(signo, info, ctx);
+       set_tls_desc(temp_tls_desc, vcoreid);
+}
+
+static void __pthread_trigger_pending_posix_signals(pthread_t thread)
+{
+       if (thread->sigpending) {
+               sigset_t andset = thread->sigpending & (~thread->sigmask);
+               if (!__sigisemptyset(&andset)) {
+                       for (int i = 1; i < _NSIG; i++) {
+                               if (__sigismember(&andset, i)) {
+                                       __sigdelset(&thread->sigpending, i);
+                                       __pthread_trigger_posix_signal(thread, i, NULL);
+                               }
+                       }
+               }
+       }
+}
+
 /* Called from vcore entry.  Options usually include restarting whoever was
  * running there before or running a new thread.  Events are handled out of
  * event.c (table of function pointers, stuff like that). */
@@ -67,7 +110,10 @@ void __attribute__((noreturn)) pth_sched_entry(void)
 {
        uint32_t vcoreid = vcore_id();
        if (current_uthread) {
+               /* Run any pending posix signal handlers registered via pthread_kill */
+               __pthread_trigger_pending_posix_signals((pthread_t)current_uthread);
                run_current_uthread();
+               /* Run the thread itself */
                assert(0);
        }
        /* no one currently running, so lets get someone from the ready queue */
@@ -103,6 +149,9 @@ void __attribute__((noreturn)) pth_sched_entry(void)
                        vcore_yield(FALSE);
        } while (1);
        assert(new_thread->state == PTH_RUNNABLE);
+       /* Run any pending posix signal handlers registered via pthread_kill */
+       __pthread_trigger_pending_posix_signals(new_thread);
+       /* Run the thread itself */
        run_uthread((struct uthread*)new_thread);
        assert(0);
 }
@@ -193,7 +242,8 @@ static void restart_thread(struct syscall *sysc)
 
 /* This handler is usually run in vcore context, though I can imagine it being
  * called by a uthread in some other threading library. */
-static void pth_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type)
+static void pth_handle_syscall(struct event_msg *ev_msg, unsigned int ev_type,
+                               void *data)
 {
        struct syscall *sysc;
        assert(in_vcore_context());
@@ -221,7 +271,6 @@ void pth_thread_blockon_sysc(struct uthread *uthread, void *syscall)
 {
        struct syscall *sysc = (struct syscall*)syscall;
        int old_flags;
-       bool need_to_restart = FALSE;
        uint32_t vcoreid = vcore_id();
        /* rip from the active queue */
        struct pthread_tcb *pthread = (struct pthread_tcb*)uthread;
@@ -254,6 +303,48 @@ void pth_thread_has_blocked(struct uthread *uthread, int flags)
                printf("For great justice!\n");
 }
 
+void pth_thread_refl_fault(struct uthread *uthread, unsigned int trap_nr,
+                           unsigned int err, unsigned long aux)
+{
+       struct pthread_tcb *pthread = (struct pthread_tcb*)uthread;
+       pthread->state = PTH_BLK_SYSC;
+       mcs_pdr_lock(&queue_lock);
+       threads_active--;
+       TAILQ_REMOVE(&active_queue, pthread, next);
+       mcs_pdr_unlock(&queue_lock);
+
+       if (trap_nr != 14 && trap_nr != 13) {
+               printf("Pthread has unhandled fault: %d\n", trap_nr);
+               print_user_context(&uthread->u_ctx);
+               exit(-1);
+       }
+
+       if (!(err & PF_VMR_BACKED)) {
+               if (!__sigismember(&pthread->sigmask, SIGSEGV)) {
+                       struct siginfo info = {0};
+                       info.si_code = SEGV_MAPERR;
+                       info.si_addr = (void*)aux;
+                       __pthread_trigger_posix_signal(pthread, SIGSEGV, &info);
+               }
+               pth_thread_runnable(uthread);
+               return;
+       }
+       /* stitching for the event handler.  sysc -> uth, uth -> sysc */
+       uthread->local_sysc.u_data = uthread;
+       uthread->sysc = &uthread->local_sysc;
+       pthread->state = PTH_BLK_SYSC;
+       /* one downside is that we'll never check the return val of the syscall.  if
+        * we errored out, we wouldn't know til we PF'd again, and inspected the old
+        * retval/err and other sysc fields (make sure the PF is on the same addr,
+        * etc).  could run into this issue on truncated files too. */
+       syscall_async(&uthread->local_sysc, SYS_populate_va, aux, 1);
+       if (!register_evq(&uthread->local_sysc, sysc_mgmt[vcore_id()].ev_q)) {
+               /* Lost the race with the call being done.  The kernel won't send the
+                * event.  Just restart him. */
+               restart_thread(&uthread->local_sysc);
+       }
+}
+
 void pth_preempt_pending(void)
 {
 }
@@ -272,6 +363,11 @@ void pthread_can_vcore_request(bool can)
        can_adjust_vcores = can;
 }
 
+void pthread_need_tls(bool need)
+{
+       need_tls = need;
+}
+
 /* Pthread interface stuff and helpers */
 
 int pthread_attr_init(pthread_attr_t *a)
@@ -316,6 +412,7 @@ int pthread_attr_setstacksize(pthread_attr_t *attr, size_t stacksize)
        attr->stacksize = stacksize;
        return 0;
 }
+
 int pthread_attr_getstacksize(const pthread_attr_t *attr, size_t *stacksize)
 {
        *stacksize = attr->stacksize;
@@ -346,6 +443,8 @@ void pthread_lib_init(void)
        t->detached = TRUE;
        t->state = PTH_RUNNING;
        t->joiner = 0;
+       __sigemptyset(&t->sigmask);
+       __sigemptyset(&t->sigpending);
        assert(t->id == 0);
        /* Put the new pthread (thread0) on the active queue */
        mcs_pdr_lock(&queue_lock);
@@ -361,7 +460,7 @@ void pthread_lib_init(void)
        enable_kevent(EV_USER_IPI, 0, EVENT_IPI | EVENT_VCORE_PRIVATE);
 
        /* Handle syscall events. */
-       ev_handlers[EV_SYSCALL] = pth_handle_syscall;
+       register_ev_handler(EV_SYSCALL, pth_handle_syscall, 0);
        /* Set up the per-vcore structs to track outstanding syscalls */
        sysc_mgmt = malloc(sizeof(struct sysc_mgmt) * max_vcores());
        assert(sysc_mgmt);
@@ -408,11 +507,13 @@ void pthread_lib_init(void)
         * have its init stuff use things like vcore stacks or TLSs, we'll need to
         * change this. */
        uthread_lib_init((struct uthread*)t);
+       atomic_init(&threads_total, 1);                 /* one for thread0 */
 }
 
-int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
-                   void *(*start_routine)(void *), void *arg)
+int __pthread_create(pthread_t *thread, const pthread_attr_t *attr,
+                     void *(*start_routine)(void *), void *arg)
 {
+       struct uth_thread_attr uth_attr = {0};
        run_once(pthread_lib_init());
        /* Create the actual thread */
        struct pthread_tcb *pthread;
@@ -425,6 +526,8 @@ int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
        pthread->id = get_next_pid();
        pthread->detached = FALSE;                              /* default */
        pthread->joiner = 0;
+       pthread->sigmask = ((pthread_t)current_uthread)->sigmask;
+       __sigemptyset(&pthread->sigpending);
        /* Respect the attributes */
        if (attr) {
                if (attr->stacksize)                                    /* don't set a 0 stacksize */
@@ -438,14 +541,24 @@ int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
        /* Set the u_tf to start up in __pthread_run, which will call the real
         * start_routine and pass it the arg.  Note those aren't set until later in
         * pthread_create(). */
-       init_user_ctx(&pthread->uthread.u_ctx, (long)&__pthread_run,
-                     (long)(pthread->stacktop));
+       init_user_ctx(&pthread->uthread.u_ctx, (uintptr_t)&__pthread_run,
+                     (uintptr_t)(pthread->stacktop));
        pthread->start_routine = start_routine;
        pthread->arg = arg;
        /* Initialize the uthread */
-       uthread_init((struct uthread*)pthread);
-       pth_thread_runnable((struct uthread*)pthread);
+       if (need_tls)
+               uth_attr.want_tls = TRUE;
+       uthread_init((struct uthread*)pthread, &uth_attr);
        *thread = pthread;
+       atomic_inc(&threads_total);
+       return 0;
+}
+
+int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
+                   void *(*start_routine)(void *), void *arg)
+{
+       if (!__pthread_create(thread, attr, start_routine, arg))
+               pth_thread_runnable((struct uthread*)*thread);
        return 0;
 }
 
@@ -539,11 +652,19 @@ static void __pth_exit_cb(struct uthread *uthread, void *junk)
                        pth_thread_runnable((struct uthread*)temp_pth);
                }
        }
+       /* If we were the last pthread, we exit for the whole process.  Keep in mind
+        * that thread0 is counted in this, so this will only happen if that thread
+        * calls pthread_exit(). */
+       if ((atomic_fetch_and_add(&threads_total, -1) == 1))
+               exit(0);
 }
 
 void pthread_exit(void *ret)
 {
        struct pthread_tcb *pthread = pthread_self();
+       /* Some apps could call pthread_exit before initing.  This will slow down
+        * our pthread exits slightly. */
+       pthread_lib_init();
        pthread->retval = ret;
        destroy_dtls();
        uthread_yield(FALSE, __pth_exit_cb, 0);
@@ -951,17 +1072,38 @@ int pthread_detach(pthread_t thread)
        return 0;
 }
 
-int pthread_kill (pthread_t __threadid, int __signo)
+int pthread_kill(pthread_t thread, int signo)
 {
-       printf("pthread_kill is not yet implemented!");
-       return -1;
+       // Slightly racy with clearing of mask when triggering the signal, but
+       // that's OK, as signals are inherently racy since they don't queue up.
+       return sigaddset(&thread->sigpending, signo);
 }
 
 
 int pthread_sigmask(int how, const sigset_t *set, sigset_t *oset)
 {
-       printf("pthread_sigmask is not yet implemented!");
-       return -1;
+       if (how != SIG_BLOCK && how != SIG_SETMASK && how != SIG_UNBLOCK) {
+               errno = EINVAL;
+               return -1;
+       }
+
+       pthread_t pthread = ((struct pthread_tcb*)current_uthread);
+       if (oset)
+               *oset = pthread->sigmask;
+       switch (how) {
+               case SIG_BLOCK:
+                       pthread->sigmask = pthread->sigmask | *set;
+                       break;
+               case SIG_SETMASK:
+                       pthread->sigmask = *set;
+                       break;
+               case SIG_UNBLOCK:
+                       pthread->sigmask = pthread->sigmask & ~(*set);
+                       break;
+       }
+       // Ensures any signals we just unmasked get processed if they are pending
+       pthread_yield();
+       return 0;
 }
 
 int pthread_sigqueue(pthread_t *thread, int sig, const union sigval value)