-#include <ros/arch/trapframe.h>
+#include <ros/trapframe.h>
#include <pthread.h>
#include <vcore.h>
#include <mcs.h>
#include <arch/arch.h>
#include <sys/queue.h>
#include <sys/mman.h>
-#include <assert.h>
#include <event.h>
#include <ucq.h>
pthread_exit(me->start_routine(me->arg));
}
+/* GIANT WARNING: if you make any changes to this, also change the broadcast
+ * wakeups (cond var, barrier, etc) */
void pth_thread_runnable(struct uthread *uthread)
{
struct pthread_tcb *pthread = (struct pthread_tcb*)uthread;
/* Insert the newly created thread into the ready queue of threads.
* It will be removed from this queue later when vcore_entry() comes up */
mcs_pdr_lock(&queue_lock);
+ /* Again, GIANT WARNING: if you change this, change batch wakeup code */
TAILQ_INSERT_TAIL(&ready_queue, pthread, next);
threads_ready++;
mcs_pdr_unlock(&queue_lock);
/* At this point, you could do something clever, like put it at the front of
* the runqueue, see if it was holding a lock, do some accounting, or
* whatever. */
- uthread_runnable(uthread);
+ pth_thread_runnable(uthread);
}
/* Restarts a uthread hanging off a syscall. For the simple pthread case, we
assert(((struct pthread_tcb*)ut_restartee)->state == PTH_BLK_SYSC);
assert(ut_restartee->sysc == sysc); /* set in uthread.c */
ut_restartee->sysc = 0; /* so we don't 'reblock' on this later */
- uthread_runnable(ut_restartee);
+ pth_thread_runnable(ut_restartee);
}
/* This handler is usually run in vcore context, though I can imagine it being
static void __pthread_free_stack(struct pthread_tcb *pt)
{
- assert(!munmap(pt->stacktop - pt->stacksize, pt->stacksize));
+ int ret = munmap(pt->stacktop - pt->stacksize, pt->stacksize);
+ assert(!ret);
}
static int __pthread_allocate_stack(struct pthread_tcb *pt)
void pthread_lib_init(void)
{
uintptr_t mmap_block;
+ struct pthread_tcb *t;
+ int ret;
/* Some testing code might call this more than once (once for a slimmed down
* pth 2LS, and another from pthread_create(). Also, this is racy, but the
* first time through we are an SCP. */
assert(!in_multi_mode());
mcs_pdr_init(&queue_lock);
/* Create a pthread_tcb for the main thread */
- pthread_t t = (pthread_t)calloc(1, sizeof(struct pthread_tcb));
- assert(t);
+ ret = posix_memalign((void**)&t, __alignof__(struct pthread_tcb),
+ sizeof(struct pthread_tcb));
+ assert(!ret);
+ memset(t, 0, sizeof(struct pthread_tcb)); /* aggressively 0 for bugs */
t->id = get_next_pid();
t->stacksize = USTACK_NUM_PAGES * PGSIZE;
t->stacktop = (void*)USTACKTOP;
t->joiner = 0;
assert(t->id == 0);
/* Put the new pthread (thread0) on the active queue */
- mcs_pdr_lock(&queue_lock); /* arguably, we don't need these (_S mode) */
+ mcs_pdr_lock(&queue_lock);
threads_active++;
TAILQ_INSERT_TAIL(&active_queue, t, next);
mcs_pdr_unlock(&queue_lock);
run_once(pthread_lib_init());
/* Create the actual thread */
struct pthread_tcb *pthread;
- pthread = (pthread_t)calloc(1, sizeof(struct pthread_tcb));
- assert(pthread);
+ int ret = posix_memalign((void**)&pthread, __alignof__(struct pthread_tcb),
+ sizeof(struct pthread_tcb));
+ assert(!ret);
+ memset(pthread, 0, sizeof(struct pthread_tcb)); /* aggressively 0 for bugs*/
pthread->stacksize = PTHREAD_STACK_SIZE; /* default */
pthread->state = PTH_CREATED;
pthread->id = get_next_pid();
/* 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_tf(&pthread->uthread.utf, (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);
- uthread_runnable((struct uthread*)pthread);
+ pth_thread_runnable((struct uthread*)pthread);
*thread = pthread;
return 0;
}
/* wake ourselves, not the exited one! */
printd("[pth] %08p already exit, rewaking ourselves, joiner %08p\n",
temp_pth, pthread);
- uthread_runnable(uthread); /* wake ourselves */
+ pth_thread_runnable(uthread); /* wake ourselves */
}
}
/* they joined before we exited, we need to wake them */
printd("[pth] %08p exiting, waking joiner %08p\n",
pthread, temp_pth);
- uthread_runnable((struct uthread*)temp_pth);
+ pth_thread_runnable((struct uthread*)temp_pth);
}
}
}
__pthread_generic_yield(pthread);
pthread->state = PTH_BLK_YIELDING;
/* just immediately restart it */
- uthread_runnable(uthread);
+ pth_thread_runnable(uthread);
}
/* Cooperative yielding of the processor, to allow other threads to run */
return 0;
}
+/* Helper for spinning sync, returns TRUE if it is okay to keep spinning.
+ *
+ * Alternatives include:
+ * old_count <= num_vcores() (barrier code, pass in old_count as *state,
+ * but this only works if every awake pthread
+ * will belong to the barrier).
+ * just spin for a bit (use *state to track spins)
+ * FALSE (always is safe)
+ * etc...
+ * 'threads_ready' isn't too great since sometimes it'll be non-zero when it is
+ * about to become 0. We really want "I have no threads waiting to run that
+ * aren't going to run on their on unless this core yields instead of spins". */
+/* TODO: consider making this a 2LS op */
+static inline bool safe_to_spin(unsigned int *state)
+{
+ return !threads_ready;
+}
+
/* Set *spun to 0 when calling this the first time. It will yield after 'spins'
* calls. Use this for adaptive mutexes and such. */
static inline void spin_to_sleep(unsigned int spins, unsigned int *spun)
int pthread_cond_init(pthread_cond_t *c, const pthread_condattr_t *a)
{
- c->attr = a;
- memset(c->waiters,0,sizeof(c->waiters));
- memset(c->in_use,0,sizeof(c->in_use));
- c->next_waiter = 0;
- return 0;
+ TAILQ_INIT(&c->waiters);
+ spin_pdr_init(&c->spdr_lock);
+ if (a) {
+ c->attr_pshared = a->pshared;
+ c->attr_clock = a->clock;
+ } else {
+ c->attr_pshared = PTHREAD_PROCESS_PRIVATE;
+ c->attr_clock = 0;
+ }
+ return 0;
}
int pthread_cond_destroy(pthread_cond_t *c)
{
- return 0;
+ return 0;
}
int pthread_cond_broadcast(pthread_cond_t *c)
{
- memset(c->waiters,0,sizeof(c->waiters));
- return 0;
+ unsigned int nr_woken = 0; /* assuming less than 4 bil threads */
+ struct pthread_queue restartees = TAILQ_HEAD_INITIALIZER(restartees);
+ struct pthread_tcb *pthread_i;
+ spin_pdr_lock(&c->spdr_lock);
+ /* moves all items from waiters onto the end of restartees */
+ TAILQ_CONCAT(&restartees, &c->waiters, next);
+ spin_pdr_unlock(&c->spdr_lock);
+ /* Do the work of pth_thread_runnable(). We're in uth context here, but I
+ * think it's okay. When we need to (when locking) we drop into VC ctx, as
+ * far as the kernel and other cores are concerned. */
+ TAILQ_FOREACH(pthread_i, &restartees, next) {
+ pthread_i->state = PTH_RUNNABLE;
+ nr_woken++;
+ }
+ /* Amortize the lock grabbing over all restartees */
+ mcs_pdr_lock(&queue_lock);
+ threads_ready += nr_woken;
+ TAILQ_CONCAT(&ready_queue, &restartees, next);
+ mcs_pdr_unlock(&queue_lock);
+ if (can_adjust_vcores)
+ vcore_request(threads_ready);
+ return 0;
}
+/* spec says this needs to work regardless of whether or not it holds the mutex
+ * already. */
int pthread_cond_signal(pthread_cond_t *c)
{
- int i;
- for(i = 0; i < MAX_PTHREADS; i++)
- {
- if(c->waiters[i])
- {
- c->waiters[i] = 0;
- break;
- }
- }
- return 0;
+ struct pthread_tcb *pthread;
+ spin_pdr_lock(&c->spdr_lock);
+ pthread = TAILQ_FIRST(&c->waiters);
+ if (!pthread) {
+ spin_pdr_unlock(&c->spdr_lock);
+ return 0;
+ }
+ TAILQ_REMOVE(&c->waiters, pthread, next);
+ spin_pdr_unlock(&c->spdr_lock);
+ pth_thread_runnable((struct uthread*)pthread);
+ return 0;
}
-int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m)
+/* Communicate btw cond_wait and its callback */
+struct cond_junk {
+ pthread_cond_t *c;
+ pthread_mutex_t *m;
+};
+
+/* Callback/bottom half of cond wait. For those writing these pth callbacks,
+ * the minimum is call generic, set state (communicate with runnable), then do
+ * something that causes it to be runnable in the future (or right now). */
+static void __pth_wait_cb(struct uthread *uthread, void *junk)
{
- uint32_t old_waiter = c->next_waiter;
- uint32_t my_waiter = c->next_waiter;
-
- //allocate a slot
- while (atomic_swap_u32(& (c->in_use[my_waiter]), SLOT_IN_USE) == SLOT_IN_USE)
- {
- my_waiter = (my_waiter + 1) % MAX_PTHREADS;
- assert (old_waiter != my_waiter); // do not want to wrap around
- }
- c->waiters[my_waiter] = WAITER_WAITING;
- c->next_waiter = (my_waiter+1) % MAX_PTHREADS; // race on next_waiter but ok, because it is advisary
-
- pthread_mutex_unlock(m);
-
- volatile int* poll = &c->waiters[my_waiter];
- while(*poll);
- c->in_use[my_waiter] = SLOT_FREE;
- pthread_mutex_lock(m);
+ struct pthread_tcb *pthread = (struct pthread_tcb*)uthread;
+ pthread_cond_t *c = ((struct cond_junk*)junk)->c;
+ pthread_mutex_t *m = ((struct cond_junk*)junk)->m;
+ /* this removes us from the active list; we can reuse next below */
+ __pthread_generic_yield(pthread);
+ pthread->state = PTH_BLK_MUTEX;
+ spin_pdr_lock(&c->spdr_lock);
+ TAILQ_INSERT_TAIL(&c->waiters, pthread, next);
+ spin_pdr_unlock(&c->spdr_lock);
+ pthread_mutex_unlock(m);
+}
- return 0;
+int pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m)
+{
+ struct cond_junk local_junk;
+ local_junk.c = c;
+ local_junk.m = m;
+ uthread_yield(TRUE, __pth_wait_cb, &local_junk);
+ pthread_mutex_lock(m);
+ return 0;
}
int pthread_condattr_init(pthread_condattr_t *a)
{
- a = PTHREAD_PROCESS_PRIVATE;
- return 0;
+ a->pshared = PTHREAD_PROCESS_PRIVATE;
+ a->clock = 0;
+ return 0;
}
int pthread_condattr_destroy(pthread_condattr_t *a)
{
- return 0;
+ return 0;
+}
+
+int pthread_condattr_getpshared(pthread_condattr_t *a, int *s)
+{
+ *s = a->pshared;
+ return 0;
}
int pthread_condattr_setpshared(pthread_condattr_t *a, int s)
{
- a->pshared = s;
- return 0;
+ a->pshared = s;
+ if (s == PTHREAD_PROCESS_SHARED) {
+ printf("Warning: we don't do shared pthread condvars btw diff MCPs\n");
+ return -1;
+ }
+ return 0;
}
-int pthread_condattr_getpshared(pthread_condattr_t *a, int *s)
+int pthread_condattr_getclock(const pthread_condattr_t *attr,
+ clockid_t *clock_id)
{
- *s = a->pshared;
- return 0;
+ *clock_id = attr->clock;
+}
+
+int pthread_condattr_setclock(pthread_condattr_t *attr, clockid_t clock_id)
+{
+ printf("Warning: we don't do pthread condvar clock stuff\n");
+ attr->clock = clock_id;
}
pthread_t pthread_self()
return 0;
}
-int pthread_barrier_init(pthread_barrier_t* b, const pthread_barrierattr_t* a, int count)
+int pthread_barrier_init(pthread_barrier_t *b,
+ const pthread_barrierattr_t *a, int count)
{
- b->nprocs = b->count = count;
- b->sense = 0;
- pthread_mutex_init(&b->pmutex, 0);
- return 0;
+ b->total_threads = count;
+ b->sense = 0;
+ atomic_set(&b->count, count);
+ spin_pdr_init(&b->lock);
+ TAILQ_INIT(&b->waiters);
+ b->nr_waiters = 0;
+ return 0;
}
-int pthread_barrier_wait(pthread_barrier_t* b)
-{
- unsigned int spinner = 0;
- int ls = !b->sense;
-
- pthread_mutex_lock(&b->pmutex);
- int count = --b->count;
- pthread_mutex_unlock(&b->pmutex);
+struct barrier_junk {
+ pthread_barrier_t *b;
+ int ls;
+};
- if(count == 0)
- {
- printd("Thread %d is last to hit the barrier, resetting...\n", pthread_self()->id);
- b->count = b->nprocs;
- wmb();
- b->sense = ls;
- return PTHREAD_BARRIER_SERIAL_THREAD;
- }
- else
- {
- while(b->sense != ls) {
- cpu_relax();
- spin_to_sleep(PTHREAD_BARRIER_SPINS, &spinner);
- }
- return 0;
- }
+/* Callback/bottom half of barrier. */
+static void __pth_barrier_cb(struct uthread *uthread, void *junk)
+{
+ struct pthread_tcb *pthread = (struct pthread_tcb*)uthread;
+ pthread_barrier_t *b = ((struct barrier_junk*)junk)->b;
+ int ls = ((struct barrier_junk*)junk)->ls;
+ /* Removes from active list, we can reuse. must also restart */
+ __pthread_generic_yield(pthread);
+ /* TODO: if we used a trylock, we could bail as soon as we see sense */
+ spin_pdr_lock(&b->lock);
+ /* If sense is ls (our free value), we lost the race and shouldn't sleep */
+ if (b->sense == ls) {
+ /* TODO: i'd like to fast-path the wakeup, skipping pth_runnable */
+ pthread->state = PTH_BLK_YIELDING; /* not sure which state for this */
+ spin_pdr_unlock(&b->lock);
+ pth_thread_runnable(uthread);
+ return;
+ }
+ /* otherwise, we sleep */
+ pthread->state = PTH_BLK_MUTEX; /* TODO: consider ignoring this */
+ TAILQ_INSERT_TAIL(&b->waiters, pthread, next);
+ b->nr_waiters++;
+ spin_pdr_unlock(&b->lock);
+}
+
+/* We assume that the same threads participating in the barrier this time will
+ * also participate next time. Imagine a thread stopped right after its fetch
+ * and add - we know it is coming through eventually. We finish and change the
+ * sense, which should allow the delayed thread to eventually break through.
+ * But if another n threads come in first, we'll set the sense back to the old
+ * value, thereby catching the delayed thread til the next barrier.
+ *
+ * A note on preemption: if any thread gets preempted and it is never dealt
+ * with, eventually we deadlock, with all threads waiting on the last one to
+ * enter (and any stragglers from one run will be the last in the next run).
+ * One way or another, we need to handle preemptions. The current 2LS requests
+ * an IPI for a preempt, so we'll be fine. Any other strategies will need to
+ * consider how barriers work. Any time we sleep, we'll be okay (since that
+ * frees up our core to handle preemptions/run other threads. */
+int pthread_barrier_wait(pthread_barrier_t *b)
+{
+ unsigned int spin_state = 0;
+ int ls = !b->sense; /* when b->sense is the value we read, then we're free*/
+ int nr_waiters;
+ struct pthread_queue restartees = TAILQ_HEAD_INITIALIZER(restartees);
+ struct pthread_tcb *pthread_i;
+ struct barrier_junk local_junk;
+
+ long old_count = atomic_fetch_and_add(&b->count, -1);
+
+ if (old_count == 1) {
+ printd("Thread %d is last to hit the barrier, resetting...\n",
+ pthread_self()->id);
+ /* TODO: we might want to grab the lock right away, so a few short
+ * circuit faster? */
+ atomic_set(&b->count, b->total_threads);
+ /* we still need to maintain ordering btw count and sense, in case
+ * another thread doesn't sleep (if we wrote sense first, they could
+ * break out, race around, and muck with count before it is time) */
+ /* wmb(); handled by the spin lock */
+ spin_pdr_lock(&b->lock);
+ /* Sense is only protected in addition to decisions to sleep */
+ b->sense = ls; /* set to free everyone */
+ /* All access to nr_waiters is protected by the lock */
+ if (!b->nr_waiters) {
+ spin_pdr_unlock(&b->lock);
+ return PTHREAD_BARRIER_SERIAL_THREAD;
+ }
+ TAILQ_CONCAT(&restartees, &b->waiters, next);
+ nr_waiters = b->nr_waiters;
+ b->nr_waiters = 0;
+ spin_pdr_unlock(&b->lock);
+ /* TODO: do we really need this state tracking? */
+ TAILQ_FOREACH(pthread_i, &restartees, next)
+ pthread_i->state = PTH_RUNNABLE;
+ /* bulk restart waiters (skipping pth_thread_runnable()) */
+ mcs_pdr_lock(&queue_lock);
+ threads_ready += nr_waiters;
+ TAILQ_CONCAT(&ready_queue, &restartees, next);
+ mcs_pdr_unlock(&queue_lock);
+ if (can_adjust_vcores)
+ vcore_request(threads_ready);
+ return PTHREAD_BARRIER_SERIAL_THREAD;
+ } else {
+ /* Spin if there are no other threads to run. No sense sleeping */
+ do {
+ if (b->sense == ls)
+ return 0;
+ cpu_relax();
+ } while (safe_to_spin(&spin_state));
+
+ /* Try to sleep, when we wake/return, we're free to go */
+ local_junk.b = b;
+ local_junk.ls = ls;
+ uthread_yield(TRUE, __pth_barrier_cb, &local_junk);
+ // assert(b->sense == ls);
+ return 0;
+ }
}
-int pthread_barrier_destroy(pthread_barrier_t* b)
+int pthread_barrier_destroy(pthread_barrier_t *b)
{
- pthread_mutex_destroy(&b->pmutex);
- return 0;
+ assert(TAILQ_EMPTY(&b->waiters));
+ assert(!b->nr_waiters);
+ /* Free any locks (if we end up using an MCS) */
+ return 0;
}
int pthread_detach(pthread_t thread)