#include "namespace.h"
#include <errno.h>
#include <pthread.h>
#include <pthread_np.h>
#include "un-namespace.h"
#include "thr_private.h"
static int suspend_common(pthread_t, pthread_t, int);
int
_pthread_suspend_np(pthread_t thread)
{
pthread_t curthread = tls_get_curthread();
int ret;
if (thread == curthread)
ret = EDEADLK;
else if ((ret = _thr_ref_add(curthread, thread, 0))
== 0) {
THR_THREAD_LOCK(curthread, thread);
suspend_common(curthread, thread, 1);
THR_THREAD_UNLOCK(curthread, thread);
_thr_ref_delete(curthread, thread);
}
return (ret);
}
void
_pthread_suspend_all_np(void)
{
pthread_t curthread = tls_get_curthread();
pthread_t thread;
int ret;
THREAD_LIST_LOCK(curthread);
TAILQ_FOREACH(thread, &_thread_list, tle) {
if (thread != curthread) {
THR_THREAD_LOCK(curthread, thread);
if (thread->state != PS_DEAD &&
!(thread->flags & THR_FLAGS_SUSPENDED))
thread->flags |= THR_FLAGS_NEED_SUSPEND;
THR_THREAD_UNLOCK(curthread, thread);
}
}
restart:
TAILQ_FOREACH(thread, &_thread_list, tle) {
if (thread != curthread) {
THR_THREAD_LOCK(curthread, thread);
ret = suspend_common(curthread, thread, 0);
if (ret == 0) {
thread->refcount++;
THREAD_LIST_UNLOCK(curthread);
suspend_common(curthread, thread, 1);
THR_THREAD_UNLOCK(curthread, thread);
THREAD_LIST_LOCK(curthread);
_thr_ref_delete_unlocked(curthread, thread);
goto restart;
}
THR_THREAD_UNLOCK(curthread, thread);
}
}
THREAD_LIST_UNLOCK(curthread);
}
static int
suspend_common(pthread_t curthread, pthread_t thread, int waitok)
{
umtx_t tmp;
while (thread->state != PS_DEAD &&
!(thread->flags & THR_FLAGS_SUSPENDED)) {
thread->flags |= THR_FLAGS_NEED_SUSPEND;
tmp = thread->cycle;
_thr_send_sig(thread, SIGCANCEL);
THR_THREAD_UNLOCK(curthread, thread);
if (waitok) {
_thr_umtx_wait(&thread->cycle, tmp, NULL, 0);
THR_THREAD_LOCK(curthread, thread);
} else {
THR_THREAD_LOCK(curthread, thread);
return (0);
}
}
return (1);
}
__strong_reference(_pthread_suspend_np, pthread_suspend_np);
__strong_reference(_pthread_suspend_all_np, pthread_suspend_all_np);