1 /* src/threads/native/threads.c - native threads support
3 Copyright (C) 1996-2005, 2006 R. Grafl, A. Krall, C. Kruegel,
4 C. Oates, R. Obermaisser, M. Platter, M. Probst, S. Ring,
5 E. Steiner, C. Thalinger, D. Thuernbeck, P. Tomsich, C. Ullrich,
6 J. Wenninger, Institut f. Computersprachen - TU Wien
8 This file is part of CACAO.
10 This program is free software; you can redistribute it and/or
11 modify it under the terms of the GNU General Public License as
12 published by the Free Software Foundation; either version 2, or (at
13 your option) any later version.
15 This program is distributed in the hope that it will be useful, but
16 WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with this program; if not, write to the Free Software
22 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25 Contact: cacao@cacaojvm.org
29 Changes: Christian Thalinger
32 $Id: threads.c 4661 2006-03-21 00:04:59Z motse $
42 #include <sys/types.h>
50 #include <semaphore.h>
56 #ifndef USE_MD_THREAD_STUFF
57 #include "machine-instr.h"
59 #include "threads/native/generic-primitives.h"
63 #include "mm/memory.h"
64 #include "native/native.h"
65 #include "native/include/java_lang_Object.h"
66 #include "native/include/java_lang_Throwable.h"
67 #include "native/include/java_lang_Thread.h"
68 #include "native/include/java_lang_ThreadGroup.h"
69 #include "native/include/java_lang_VMThread.h"
70 #include "threads/native/threads.h"
71 #include "toolbox/avl.h"
72 #include "toolbox/logging.h"
73 #include "vm/builtin.h"
74 #include "vm/exceptions.h"
75 #include "vm/global.h"
76 #include "vm/loader.h"
77 #include "vm/options.h"
78 #include "vm/stringlocal.h"
80 #include "vm/jit/asmpart.h"
82 #if !defined(__DARWIN__)
83 #if defined(__LINUX__)
84 #define GC_LINUX_THREADS
85 #elif defined(__MIPS__)
86 #define GC_IRIX_THREADS
88 #include "boehm-gc/include/gc.h"
91 #ifdef USE_MD_THREAD_STUFF
92 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
93 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
94 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
99 /* We need this for older MacOSX (10.1.x) */
102 pthread_mutex_t mutex;
105 } pthread_mutex_rec_t;
107 static void pthread_mutex_init_rec(pthread_mutex_rec_t *m)
109 pthread_mutex_init(&m->mutex, NULL);
113 static void pthread_mutex_destroy_rec(pthread_mutex_rec_t *m)
115 pthread_mutex_destroy(&m->mutex);
118 static void pthread_mutex_lock_rec(pthread_mutex_rec_t *m)
123 pthread_mutex_lock(&m->mutex);
124 m->owner = pthread_self();
129 if (m->owner != pthread_self()) {
130 pthread_mutex_lock(&m->mutex);
140 static void pthread_mutex_unlock_rec(pthread_mutex_rec_t *m)
143 pthread_mutex_unlock(&m->mutex);
148 #define pthread_mutex_lock_rec pthread_mutex_lock
149 #define pthread_mutex_unlock_rec pthread_mutex_unlock
150 #define pthread_mutex_rec_t pthread_mutex_t
152 #endif /* MUTEXSIM */
154 static void setPriority(pthread_t tid, int priority)
156 struct sched_param schedp;
159 pthread_getschedparam(tid, &policy, &schedp);
160 schedp.sched_priority = priority;
161 pthread_setschedparam(tid, policy, &schedp);
165 static avl_tree *criticaltree;
166 threadobject *mainthreadobj;
168 #ifndef HAVE___THREAD
169 pthread_key_t tkey_threadinfo;
171 __thread threadobject *threadobj;
174 static pthread_mutex_rec_t compiler_mutex;
175 static pthread_mutex_rec_t tablelock;
179 pthread_mutex_lock_rec(&compiler_mutex);
182 void compiler_unlock()
184 pthread_mutex_unlock_rec(&compiler_mutex);
189 pthread_mutex_lock_rec(&tablelock);
194 pthread_mutex_unlock_rec(&tablelock);
198 static s4 criticalcompare(const void *pa, const void *pb)
200 const threadcritnode *na = pa;
201 const threadcritnode *nb = pb;
203 if (na->mcodebegin < nb->mcodebegin)
205 if (na->mcodebegin > nb->mcodebegin)
211 static const threadcritnode *findcritical(u1 *mcodeptr)
214 const threadcritnode *m;
216 n = criticaltree->root;
223 const threadcritnode *d = n->data;
225 if (mcodeptr == d->mcodebegin)
228 if (mcodeptr < d->mcodebegin) {
249 void thread_registercritical(threadcritnode *n)
251 avl_insert(criticaltree, n);
254 u1 *thread_checkcritical(u1 *mcodeptr)
256 const threadcritnode *n = findcritical(mcodeptr);
257 return (n && mcodeptr < n->mcodeend && mcodeptr > n->mcodebegin) ? n->mcoderestart : NULL;
260 static void thread_addstaticcritical()
262 /* XXX TWISTI: this is just a quick hack */
263 #if defined(ENABLE_JIT)
264 threadcritnode *n = &asm_criticalsections;
266 while (n->mcodebegin)
267 thread_registercritical(n++);
271 static pthread_mutex_t threadlistlock;
273 static pthread_mutex_t stopworldlock;
274 volatile int stopworldwhere;
276 static sem_t suspend_ack;
277 #if defined(__MIPS__)
278 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
279 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
283 * where - 1 from within GC
286 void lock_stopworld(int where)
288 pthread_mutex_lock(&stopworldlock);
289 stopworldwhere = where;
292 void unlock_stopworld()
295 pthread_mutex_unlock(&stopworldlock);
298 #if !defined(__DARWIN__)
299 /* Caller must hold threadlistlock */
300 static int cast_sendsignals(int sig, int count)
303 threadobject *tobj = mainthreadobj;
304 nativethread *infoself = THREADINFO;
309 tobj = tobj->info.next;
310 } while (tobj != mainthreadobj);
314 nativethread *info = &tobj->info;
315 if (info != infoself)
316 pthread_kill(info->tid, sig);
317 tobj = tobj->info.next;
318 } while (tobj != mainthreadobj);
325 static void cast_darwinstop()
327 threadobject *tobj = mainthreadobj;
328 nativethread *infoself = THREADINFO;
331 nativethread *info = &tobj->info;
332 if (info != infoself)
334 thread_state_flavor_t flavor = PPC_THREAD_STATE;
335 mach_msg_type_number_t thread_state_count = PPC_THREAD_STATE_COUNT;
336 ppc_thread_state_t thread_state;
337 mach_port_t thread = info->mach_thread;
340 r = thread_suspend(thread);
341 if (r != KERN_SUCCESS) {
342 log_text("thread_suspend failed");
346 r = thread_get_state(thread, flavor,
347 (natural_t*)&thread_state, &thread_state_count);
348 if (r != KERN_SUCCESS) {
349 log_text("thread_get_state failed");
353 thread_restartcriticalsection(&thread_state);
355 r = thread_set_state(thread, flavor,
356 (natural_t*)&thread_state, thread_state_count);
357 if (r != KERN_SUCCESS) {
358 log_text("thread_set_state failed");
362 tobj = tobj->info.next;
363 } while (tobj != mainthreadobj);
366 static void cast_darwinresume()
368 threadobject *tobj = mainthreadobj;
369 nativethread *infoself = THREADINFO;
372 nativethread *info = &tobj->info;
373 if (info != infoself)
375 mach_port_t thread = info->mach_thread;
378 r = thread_resume(thread);
379 if (r != KERN_SUCCESS) {
380 log_text("thread_resume failed");
384 tobj = tobj->info.next;
385 } while (tobj != mainthreadobj);
390 #if defined(__MIPS__)
391 static void cast_irixresume()
393 pthread_mutex_lock(&suspend_ack_lock);
394 pthread_cond_broadcast(&suspend_cond);
395 pthread_mutex_unlock(&suspend_ack_lock);
399 void cast_stopworld()
403 pthread_mutex_lock(&threadlistlock);
404 #if defined(__DARWIN__)
407 count = cast_sendsignals(GC_signum1(), 0);
408 for (i=0; i<count; i++)
409 sem_wait(&suspend_ack);
411 pthread_mutex_unlock(&threadlistlock);
414 void cast_startworld()
416 pthread_mutex_lock(&threadlistlock);
417 #if defined(__DARWIN__)
419 #elif defined(__MIPS__)
422 cast_sendsignals(GC_signum2(), -1);
424 pthread_mutex_unlock(&threadlistlock);
428 #if !defined(__DARWIN__)
429 static void sigsuspend_handler(ucontext_t *ctx)
434 /* XXX TWISTI: this is just a quick hack */
435 #if defined(ENABLE_JIT)
436 thread_restartcriticalsection(ctx);
439 /* Do as Boehm does. On IRIX a condition variable is used for wake-up
440 (not POSIX async-safe). */
441 #if defined(__IRIX__)
442 pthread_mutex_lock(&suspend_ack_lock);
443 sem_post(&suspend_ack);
444 pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
445 pthread_mutex_unlock(&suspend_ack_lock);
447 sem_post(&suspend_ack);
451 sigdelset(&sigs, sig);
456 int cacao_suspendhandler(ucontext_t *ctx)
458 if (stopworldwhere != 2)
461 sigsuspend_handler(ctx);
466 #if !defined(ENABLE_JVMTI)
467 static void setthreadobject(threadobject *thread)
469 void setthreadobject(threadobject *thread)
472 #if !defined(HAVE___THREAD)
473 pthread_setspecific(tkey_threadinfo, thread);
480 /* thread_setself **************************************************************
484 *******************************************************************************/
486 void *thread_getself(void)
492 static monitorLockRecord *dummyLR;
494 static void initPools();
497 /* thread_preinit **************************************************************
499 Do some early initialization of stuff required.
501 *******************************************************************************/
503 void threads_preinit(void)
506 pthread_mutexattr_t mutexattr;
507 pthread_mutexattr_init(&mutexattr);
508 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
509 pthread_mutex_init(&compiler_mutex, &mutexattr);
510 pthread_mutex_init(&tablelock, &mutexattr);
511 pthread_mutexattr_destroy(&mutexattr);
513 pthread_mutex_init_rec(&compiler_mutex);
514 pthread_mutex_init_rec(&tablelock);
517 pthread_mutex_init(&threadlistlock, NULL);
518 pthread_mutex_init(&stopworldlock, NULL);
520 /* Allocate something so the garbage collector's signal handlers
522 heap_allocate(1, false, NULL);
524 mainthreadobj = NEW(threadobject);
525 mainthreadobj->info.tid = pthread_self();
526 #if !defined(HAVE___THREAD)
527 pthread_key_create(&tkey_threadinfo, NULL);
529 setthreadobject(mainthreadobj);
532 /* Every newly created object's monitorPtr points here so we save
533 a check against NULL */
535 dummyLR = NEW(monitorLockRecord);
537 dummyLR->ownerThread = NULL;
538 dummyLR->waiting = NULL;
539 dummyLR->incharge = dummyLR;
541 /* we need a working dummyLR before initializing the critical
544 criticaltree = avl_create(&criticalcompare);
546 thread_addstaticcritical();
547 sem_init(&suspend_ack, 0, 0);
551 static pthread_attr_t threadattr;
553 static void freeLockRecordPools(lockRecordPool *);
556 /* threads_init ****************************************************************
558 Initializes the threads required by the JVM: main, finalizer.
560 *******************************************************************************/
562 bool threads_init(u1 *stackbottom)
564 java_lang_String *threadname;
565 java_lang_Thread *mainthread;
566 java_lang_ThreadGroup *threadgroup;
567 threadobject *tempthread;
570 tempthread = mainthreadobj;
572 freeLockRecordPools(mainthreadobj->ee.lrpool);
574 /* This is kinda tricky, we grow the java.lang.Thread object so we
575 can keep the execution environment there. No Thread object must
576 have been created at an earlier time. */
578 class_java_lang_VMThread->instancesize = sizeof(threadobject);
580 /* create a VMThread */
582 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
587 FREE(tempthread, threadobject);
589 initThread(&mainthreadobj->o);
591 setthreadobject(mainthreadobj);
595 mainthreadobj->info.next = mainthreadobj;
596 mainthreadobj->info.prev = mainthreadobj;
598 #if defined(ENABLE_INTRP)
599 /* create interpreter stack */
602 MSET(intrp_main_stack, 0, u1, opt_stacksize);
603 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
607 threadname = javastring_new(utf_new_char("main"));
609 /* allocate and init ThreadGroup */
611 threadgroup = (java_lang_ThreadGroup *)
612 native_new_and_init(class_java_lang_ThreadGroup);
615 throw_exception_exit();
617 /* create a Thread */
619 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
622 throw_exception_exit();
624 mainthreadobj->o.thread = mainthread;
626 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
628 method = class_resolveclassmethod(class_java_lang_Thread,
630 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
631 class_java_lang_Thread,
637 (void) vm_call_method(method, (java_objectheader *) mainthread,
638 mainthreadobj, threadname, 5, false);
643 mainthread->group = threadgroup;
645 /* add mainthread to ThreadGroup */
647 method = class_resolveclassmethod(class_java_lang_ThreadGroup,
648 utf_new_char("addThread"),
649 utf_new_char("(Ljava/lang/Thread;)V"),
650 class_java_lang_ThreadGroup,
656 (void) vm_call_method(method, (java_objectheader *) threadgroup,
662 setPriority(pthread_self(), 5);
664 pthread_attr_init(&threadattr);
665 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
667 /* everything's ok */
673 void initThread(java_lang_VMThread *t)
675 threadobject *thread = (threadobject*) t;
676 nativethread *info = &thread->info;
677 info->tid = pthread_self();
678 /* TODO destroy all those things */
679 pthread_mutex_init(&info->joinMutex, NULL);
680 pthread_cond_init(&info->joinCond, NULL);
682 pthread_mutex_init(&thread->waitLock, NULL);
683 pthread_cond_init(&thread->waitCond, NULL);
684 thread->interrupted = false;
685 thread->signaled = false;
686 thread->isSleeping = false;
689 static void initThreadLocks(threadobject *);
693 threadobject *thread;
694 functionptr function;
700 /* threads_startup *************************************************************
702 Thread startup function called by pthread_create.
704 ******************************************************************************/
706 static void *threads_startup_thread(void *t)
708 startupinfo *startup;
709 threadobject *thread;
714 functionptr function;
716 #if defined(ENABLE_INTRP)
717 u1 *intrp_thread_stack;
719 /* create interpreter stack */
722 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
723 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
725 intrp_thread_stack = NULL;
729 /* get passed startupinfo structure and the values in there */
733 thread = startup->thread;
734 function = startup->function;
735 psem = startup->psem;
737 info = &thread->info;
739 /* Seems like we've encountered a situation where info->tid was not set by
740 * pthread_create. We alleviate this problem by waiting for pthread_create
742 sem_wait(startup->psem_first);
745 #if defined(__DARWIN__)
746 info->mach_thread = mach_thread_self();
748 setthreadobject(thread);
750 /* insert the thread into the threadlist */
752 pthread_mutex_lock(&threadlistlock);
754 info->prev = mainthreadobj;
755 info->next = tnext = mainthreadobj->info.next;
756 mainthreadobj->info.next = thread;
757 tnext->info.prev = thread;
759 pthread_mutex_unlock(&threadlistlock);
761 initThreadLocks(thread);
766 setPriority(info->tid, thread->o.thread->priority);
768 #if defined(ENABLE_INTRP)
769 /* set interpreter stack */
772 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
775 /* find and run the Thread.run()V method if no other function was passed */
777 if (function == NULL) {
778 method = class_resolveclassmethod(thread->o.header.vftbl->class,
781 thread->o.header.vftbl->class,
787 (void) vm_call_method(method, (java_objectheader *) thread);
791 /* call passed function, e.g. finalizer_thread */
796 /* Allow lock record pools to be used by other threads. They
797 cannot be deleted so we'd better not waste them. */
799 freeLockRecordPools(thread->ee.lrpool);
801 /* remove thread from thread list, do this inside a lock */
803 pthread_mutex_lock(&threadlistlock);
804 info->next->info.prev = info->prev;
805 info->prev->info.next = info->next;
806 pthread_mutex_unlock(&threadlistlock);
808 /* reset thread id (lock on joinMutex? TWISTI) */
810 pthread_mutex_lock(&info->joinMutex);
812 pthread_mutex_unlock(&info->joinMutex);
814 pthread_cond_broadcast(&info->joinCond);
820 /* threads_start_thread ********************************************************
822 Start a thread in the JVM.
824 ******************************************************************************/
826 void threads_start_thread(thread *t, functionptr function)
833 info = &((threadobject *) t->vmThread)->info;
835 /* fill startupinfo structure passed by pthread_create to XXX */
837 startup.thread = (threadobject*) t->vmThread;
838 startup.function = function; /* maybe we don't call Thread.run()V */
840 startup.psem_first = &sem_first;
842 sem_init(&sem, 0, 0);
843 sem_init(&sem_first, 0, 0);
845 if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
847 log_text("pthread_create failed");
851 sem_post(&sem_first);
853 /* wait here until the thread has entered itself into the thread list */
857 sem_destroy(&sem_first);
861 /* At the end of the program, we wait for all running non-daemon threads to die
864 static threadobject *findNonDaemon(threadobject *thread)
866 while (thread != mainthreadobj) {
867 if (!thread->o.thread->daemon)
869 thread = thread->info.prev;
875 void joinAllThreads()
877 threadobject *thread;
878 pthread_mutex_lock(&threadlistlock);
879 while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
880 nativethread *info = &thread->info;
881 pthread_mutex_lock(&info->joinMutex);
882 pthread_mutex_unlock(&threadlistlock);
884 pthread_cond_wait(&info->joinCond, &info->joinMutex);
885 pthread_mutex_unlock(&info->joinMutex);
886 pthread_mutex_lock(&threadlistlock);
888 pthread_mutex_unlock(&threadlistlock);
891 static void initLockRecord(monitorLockRecord *r, threadobject *t)
898 r->incharge = (monitorLockRecord *) &dummyLR;
900 sem_init(&r->queueSem, 0, 0);
901 pthread_mutex_init(&r->resolveLock, NULL);
902 pthread_cond_init(&r->resolveWait, NULL);
905 /* No lock record must ever be destroyed because there may still be references
908 static void destroyLockRecord(monitorLockRecord *r)
910 sem_destroy(&r->queueSem);
911 pthread_mutex_destroy(&r->resolveLock);
912 pthread_cond_destroy(&r->resolveWait);
918 initThreadLocks(mainthreadobj);
921 static void initThreadLocks(threadobject *thread)
923 thread->ee.firstLR = NULL;
924 thread->ee.lrpool = NULL;
925 thread->ee.numlr = 0;
928 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
930 lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
933 p->header.size = size;
934 for (i=0; i<size; i++) {
935 initLockRecord(&p->lr[i], thread);
936 p->lr[i].nextFree = &p->lr[i+1];
938 p->lr[i-1].nextFree = NULL;
942 #define INITIALLOCKRECORDS 8
944 pthread_mutex_t pool_lock;
945 lockRecordPool *global_pool;
947 static void initPools()
949 pthread_mutex_init(&pool_lock, NULL);
952 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
954 pthread_mutex_lock(&pool_lock);
957 lockRecordPool *pool = global_pool;
958 global_pool = pool->header.next;
959 pthread_mutex_unlock(&pool_lock);
961 for (i=0; i < pool->header.size; i++) {
962 pool->lr[i].ownerThread = t;
963 pool->lr[i].nextFree = &pool->lr[i+1];
965 pool->lr[i-1].nextFree = NULL;
969 pthread_mutex_unlock(&pool_lock);
971 return allocNewLockRecordPool(t, size);
974 static void freeLockRecordPools(lockRecordPool *pool)
976 lockRecordPoolHeader *last;
977 pthread_mutex_lock(&pool_lock);
978 last = &pool->header;
980 last = &last->next->header;
981 last->next = global_pool;
983 pthread_mutex_unlock(&pool_lock);
986 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
988 monitorLockRecord *r;
994 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
995 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
996 pool->header.next = t->ee.lrpool;
999 t->ee.numlr += pool->header.size;
1002 t->ee.firstLR = r->nextFree;
1004 r->nextFree = NULL; /* in order to find invalid uses of nextFree */
1009 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
1013 assert(r->ownerThread == t);
1014 assert(r->nextFree == NULL);
1016 r->nextFree = t->ee.firstLR;
1020 void initObjectLock(java_objectheader *o)
1024 o->monitorPtr = dummyLR;
1028 /* get_dummyLR *****************************************************************
1030 Returns the global dummy monitor lock record. The pointer is
1031 required in the code generator to set up a virtual
1032 java_objectheader for code patch locking.
1034 *******************************************************************************/
1036 monitorLockRecord *get_dummyLR(void)
1042 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
1044 atomic_add(&lr->queuers, 1);
1046 MEMORY_BARRIER_AFTER_ATOMIC();
1049 sem_wait(&lr->queueSem);
1051 atomic_add(&lr->queuers, -1);
1054 static void freeLockRecord(monitorLockRecord *lr)
1061 sem_post(&lr->queueSem);
1064 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr, java_objectheader *o)
1066 if (lr->waiting == o)
1070 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1073 monitorLockRecord *lr = o->monitorPtr;
1075 /* the lock record does not lock this object */
1076 monitorLockRecord *nlr;
1077 monitorLockRecord *mlr;
1079 /* allocate a new lock record for this object */
1080 mlr = allocLockRecordSimple(t);
1083 /* check if it is the same record the object refered to earlier */
1086 nlr = o->monitorPtr;
1088 /* the object still refers to the same lock record */
1090 handleWaiter(mlr, lr, o);
1095 /* no, it's another lock record */
1096 /* if we don't own the old record, set incharge XXX */
1097 if (lr->ownerThread != t)
1100 /* if the object still refers to lr, replace it by the new mlr */
1101 MEMORY_BARRIER_BEFORE_ATOMIC();
1102 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1106 /* we swapped the new record in successfully */
1107 if (mlr == lr || lr->o != o) {
1108 /* the old lock record is the same as the new one, or */
1109 /* it locks another object. */
1111 handleWaiter(mlr, lr, o);
1114 /* lr locks the object, we have to wait */
1116 queueOnLockRecord(lr, o);
1119 handleWaiter(mlr, lr, o);
1123 /* forget this mlr lock record, wait on nlr and try again */
1124 freeLockRecord(mlr);
1125 recycleLockRecord(t, mlr);
1126 queueOnLockRecord(nlr, o);
1129 /* the lock record is for the object we want */
1131 if (lr->ownerThread == t) {
1132 /* we own it already, just recurse */
1137 /* it's locked. we wait and then try again */
1138 queueOnLockRecord(lr, o);
1143 static void wakeWaiters(monitorLockRecord *lr)
1145 monitorLockRecord *tmplr;
1148 /* assign lock record to a temporary variable */
1156 sem_post(&tmplr->queueSem);
1158 tmplr = tmplr->waiter;
1159 } while (tmplr != NULL && tmplr != lr);
1162 #define GRAB_LR(lr,t) \
1163 if (lr->ownerThread != t) { \
1164 lr = lr->incharge; \
1167 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1168 if (lr->o != mo || lr->ownerThread != t) { \
1169 *exceptionptr = new_illegalmonitorstateexception(); \
1173 bool monitorExit(threadobject *t, java_objectheader *o)
1175 monitorLockRecord *lr = o->monitorPtr;
1177 CHECK_MONITORSTATE(lr, t, o, return false);
1179 if (lr->lockCount > 1) {
1180 /* we had locked this one recursively. just decrement, it will */
1181 /* still be locked. */
1187 monitorLockRecord *wlr = lr->waiter;
1188 if (o->monitorPtr != lr ||
1189 (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1191 monitorLockRecord *nlr = o->monitorPtr;
1193 STORE_ORDER_BARRIER();
1201 /* unlock and throw away this lock record */
1203 recycleLockRecord(t, lr);
1207 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1210 if (lr->waiter == wlr) {
1211 lr->waiter = wlr->waiter;
1215 } while (lr); /* XXX need to break cycle? */
1218 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1220 return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1223 static bool timeIsEarlier(const struct timespec *tv)
1225 struct timeval tvnow;
1226 struct timespec tsnow;
1227 gettimeofday(&tvnow, NULL);
1228 tsnow.tv_sec = tvnow.tv_sec;
1229 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1230 return timespec_less(&tsnow, tv);
1234 /* waitWithTimeout *************************************************************
1238 *******************************************************************************/
1240 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1242 bool wasinterrupted;
1244 pthread_mutex_lock(&t->waitLock);
1246 t->isSleeping = true;
1248 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1249 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1250 pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1253 while (!t->interrupted && !t->signaled)
1254 pthread_cond_wait(&t->waitCond, &t->waitLock);
1257 wasinterrupted = t->interrupted;
1258 t->interrupted = false;
1259 t->signaled = false;
1260 t->isSleeping = false;
1262 pthread_mutex_unlock(&t->waitLock);
1264 return wasinterrupted;
1268 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1270 if (millis || nanos) {
1273 gettimeofday(&tv, NULL);
1274 tv.tv_sec += millis / 1000;
1276 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1277 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1278 tm->tv_nsec = nsec % 1000000000;
1286 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1288 bool wasinterrupted;
1289 struct timespec wakeupTime;
1290 monitorLockRecord *mlr, *lr = o->monitorPtr;
1292 CHECK_MONITORSTATE(lr, t, o, return);
1294 calcAbsoluteTime(&wakeupTime, millis, nanos);
1297 wakeWaiters(lr->waiter);
1299 STORE_ORDER_BARRIER();
1301 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1302 mlr = monitorEnter(t, o);
1303 removeFromWaiters(mlr, lr);
1304 mlr->lockCount = lr->lockCount;
1308 recycleLockRecord(t, lr);
1311 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1314 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1316 monitorLockRecord *lr = o->monitorPtr;
1318 CHECK_MONITORSTATE(lr, t, o, return);
1320 threadobject *wthread;
1321 monitorLockRecord *wlr = lr->waiter;
1324 wthread = wlr->ownerThread;
1325 pthread_mutex_lock(&wthread->waitLock);
1326 if (wthread->isSleeping)
1327 pthread_cond_signal(&wthread->waitCond);
1328 wthread->signaled = true;
1329 pthread_mutex_unlock(&wthread->waitLock);
1334 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1336 monitorLockRecord *lr = o->monitorPtr;
1338 /* The reason why we have to check against NULL is that
1339 * dummyLR->incharge == NULL */
1340 return lr->o == o && lr->ownerThread == t;
1343 void interruptThread(java_lang_VMThread *thread)
1345 threadobject *t = (threadobject*) thread;
1347 pthread_mutex_lock(&t->waitLock);
1349 pthread_cond_signal(&t->waitCond);
1350 t->interrupted = true;
1351 pthread_mutex_unlock(&t->waitLock);
1354 bool interruptedThread()
1356 threadobject *t = (threadobject*) THREADOBJECT;
1357 bool intr = t->interrupted;
1358 t->interrupted = false;
1362 bool isInterruptedThread(java_lang_VMThread *thread)
1364 threadobject *t = (threadobject*) thread;
1365 return t->interrupted;
1369 /* thread_sleep ****************************************************************
1371 Sleep the current thread for the specified amount of time.
1373 *******************************************************************************/
1375 void thread_sleep(s8 millis, s4 nanos)
1378 struct timespec wakeupTime;
1379 monitorLockRecord *lr;
1380 bool wasinterrupted;
1382 t = (threadobject *) THREADOBJECT;
1384 calcAbsoluteTime(&wakeupTime, millis, nanos);
1386 lr = allocLockRecordSimple(t);
1388 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1390 recycleLockRecord(t, lr);
1393 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1401 void setPriorityThread(thread *t, s4 priority)
1403 nativethread *info = &((threadobject*) t->vmThread)->info;
1404 setPriority(info->tid, priority);
1407 void wait_cond_for_object(java_objectheader *o, s8 millis, s4 nanos)
1409 threadobject *t = (threadobject*) THREADOBJECT;
1410 monitorWait(t, o, millis, nanos);
1413 void signal_cond_for_object(java_objectheader *o)
1415 threadobject *t = (threadobject*) THREADOBJECT;
1416 notifyOneOrAll(t, o, true);
1419 void broadcast_cond_for_object(java_objectheader *o)
1421 threadobject *t = (threadobject*) THREADOBJECT;
1422 notifyOneOrAll(t, o, false);
1426 /* threads_dump ****************************************************************
1428 Dumps info for all threads running in the JVM. This function is
1429 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1431 *******************************************************************************/
1433 void threads_dump(void)
1436 java_lang_VMThread *vmt;
1438 java_lang_Thread *t;
1441 tobj = mainthreadobj;
1443 printf("Full thread dump CACAO "VERSION":\n");
1445 /* iterate over all started threads */
1448 /* get thread objects */
1454 /* the thread may be currently in initalization, don't print it */
1457 /* get thread name */
1459 name = javastring_toutf(t->name, false);
1468 #if SIZEOF_VOID_P == 8
1469 printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1471 printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1474 /* send SIGUSR1 to thread to print stacktrace */
1476 pthread_kill(nt->tid, SIGUSR1);
1478 /* sleep this thread a bit, so the signal can reach the thread */
1480 thread_sleep(10, 0);
1483 tobj = tobj->info.next;
1484 } while (tobj && (tobj != mainthreadobj));
1489 * These are local overrides for various environment variables in Emacs.
1490 * Please do not remove this and leave it at the end of the file, where
1491 * Emacs will automagically detect them.
1492 * ---------------------------------------------------------------------
1495 * indent-tabs-mode: t
1499 * vim:noexpandtab:sw=4:ts=4: