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 4552 2006-03-04 17:15:44Z twisti $
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 static void setthreadobject(threadobject *thread)
468 #if !defined(HAVE___THREAD)
469 pthread_setspecific(tkey_threadinfo, thread);
476 /* thread_setself **************************************************************
480 *******************************************************************************/
482 void *thread_getself(void)
488 static monitorLockRecord *dummyLR;
490 static void initPools();
493 /* thread_preinit **************************************************************
495 Do some early initialization of stuff required.
497 *******************************************************************************/
499 void threads_preinit(void)
502 pthread_mutexattr_t mutexattr;
503 pthread_mutexattr_init(&mutexattr);
504 pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
505 pthread_mutex_init(&compiler_mutex, &mutexattr);
506 pthread_mutex_init(&tablelock, &mutexattr);
507 pthread_mutexattr_destroy(&mutexattr);
509 pthread_mutex_init_rec(&compiler_mutex);
510 pthread_mutex_init_rec(&tablelock);
513 pthread_mutex_init(&threadlistlock, NULL);
514 pthread_mutex_init(&stopworldlock, NULL);
516 /* Allocate something so the garbage collector's signal handlers
518 heap_allocate(1, false, NULL);
520 mainthreadobj = NEW(threadobject);
521 mainthreadobj->info.tid = pthread_self();
522 #if !defined(HAVE___THREAD)
523 pthread_key_create(&tkey_threadinfo, NULL);
525 setthreadobject(mainthreadobj);
528 /* Every newly created object's monitorPtr points here so we save
529 a check against NULL */
531 dummyLR = NEW(monitorLockRecord);
533 dummyLR->ownerThread = NULL;
534 dummyLR->waiting = NULL;
535 dummyLR->incharge = dummyLR;
537 /* we need a working dummyLR before initializing the critical
540 criticaltree = avl_create(&criticalcompare);
542 thread_addstaticcritical();
543 sem_init(&suspend_ack, 0, 0);
547 static pthread_attr_t threadattr;
549 static void freeLockRecordPools(lockRecordPool *);
552 /* threads_init ****************************************************************
554 Initializes the threads required by the JVM: main, finalizer.
556 *******************************************************************************/
558 bool threads_init(u1 *stackbottom)
560 java_lang_String *threadname;
561 java_lang_Thread *mainthread;
562 java_lang_ThreadGroup *threadgroup;
563 threadobject *tempthread;
566 tempthread = mainthreadobj;
568 freeLockRecordPools(mainthreadobj->ee.lrpool);
570 /* This is kinda tricky, we grow the java.lang.Thread object so we
571 can keep the execution environment there. No Thread object must
572 have been created at an earlier time. */
574 class_java_lang_VMThread->instancesize = sizeof(threadobject);
576 /* create a VMThread */
578 mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
583 FREE(tempthread, threadobject);
585 initThread(&mainthreadobj->o);
587 setthreadobject(mainthreadobj);
591 mainthreadobj->info.next = mainthreadobj;
592 mainthreadobj->info.prev = mainthreadobj;
594 #if defined(ENABLE_INTRP)
595 /* create interpreter stack */
598 MSET(intrp_main_stack, 0, u1, opt_stacksize);
599 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
603 threadname = javastring_new(utf_new_char("main"));
605 /* allocate and init ThreadGroup */
607 threadgroup = (java_lang_ThreadGroup *)
608 native_new_and_init(class_java_lang_ThreadGroup);
611 throw_exception_exit();
613 /* create a Thread */
615 mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
618 throw_exception_exit();
620 mainthreadobj->o.thread = mainthread;
622 /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
624 method = class_resolveclassmethod(class_java_lang_Thread,
626 utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
627 class_java_lang_Thread,
633 (void) vm_call_method_intern(method, mainthread, mainthreadobj, threadname,
639 mainthread->group = threadgroup;
640 /* XXX This is a hack because the fourth argument was omitted */
641 mainthread->daemon = false;
643 /* add mainthread to ThreadGroup */
645 method = class_resolveclassmethod(class_java_lang_ThreadGroup,
646 utf_new_char("addThread"),
647 utf_new_char("(Ljava/lang/Thread;)V"),
648 class_java_lang_ThreadGroup,
654 (void) vm_call_method_intern(method, threadgroup, mainthread, NULL, NULL);
659 setPriority(pthread_self(), 5);
661 pthread_attr_init(&threadattr);
662 pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
664 /* everything's ok */
670 void initThread(java_lang_VMThread *t)
672 threadobject *thread = (threadobject*) t;
673 nativethread *info = &thread->info;
674 info->tid = pthread_self();
675 /* TODO destroy all those things */
676 pthread_mutex_init(&info->joinMutex, NULL);
677 pthread_cond_init(&info->joinCond, NULL);
679 pthread_mutex_init(&thread->waitLock, NULL);
680 pthread_cond_init(&thread->waitCond, NULL);
681 thread->interrupted = false;
682 thread->signaled = false;
683 thread->isSleeping = false;
686 static void initThreadLocks(threadobject *);
690 threadobject *thread;
691 functionptr function;
697 /* threads_startup *************************************************************
699 Thread startup function called by pthread_create.
701 ******************************************************************************/
703 static void *threads_startup_thread(void *t)
705 startupinfo *startup;
706 threadobject *thread;
711 functionptr function;
713 #if defined(ENABLE_INTRP)
714 u1 *intrp_thread_stack;
716 /* create interpreter stack */
719 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
720 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
722 intrp_thread_stack = NULL;
726 /* get passed startupinfo structure and the values in there */
730 thread = startup->thread;
731 function = startup->function;
732 psem = startup->psem;
734 info = &thread->info;
736 /* Seems like we've encountered a situation where info->tid was not set by
737 * pthread_create. We alleviate this problem by waiting for pthread_create
739 sem_wait(startup->psem_first);
742 #if defined(__DARWIN__)
743 info->mach_thread = mach_thread_self();
745 setthreadobject(thread);
747 /* insert the thread into the threadlist */
749 pthread_mutex_lock(&threadlistlock);
751 info->prev = mainthreadobj;
752 info->next = tnext = mainthreadobj->info.next;
753 mainthreadobj->info.next = thread;
754 tnext->info.prev = thread;
756 pthread_mutex_unlock(&threadlistlock);
758 initThreadLocks(thread);
763 setPriority(info->tid, thread->o.thread->priority);
765 #if defined(ENABLE_INTRP)
766 /* set interpreter stack */
769 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
772 /* find and run the Thread.run()V method if no other function was passed */
774 if (function == NULL) {
775 method = class_resolveclassmethod(thread->o.header.vftbl->class,
778 thread->o.header.vftbl->class,
784 (void) vm_call_method_intern(method, thread, NULL, NULL, NULL);
788 /* call passed function, e.g. finalizer_thread */
793 /* Allow lock record pools to be used by other threads. They
794 cannot be deleted so we'd better not waste them. */
796 freeLockRecordPools(thread->ee.lrpool);
798 /* remove thread from thread list, do this inside a lock */
800 pthread_mutex_lock(&threadlistlock);
801 info->next->info.prev = info->prev;
802 info->prev->info.next = info->next;
803 pthread_mutex_unlock(&threadlistlock);
805 /* reset thread id (lock on joinMutex? TWISTI) */
807 pthread_mutex_lock(&info->joinMutex);
809 pthread_mutex_unlock(&info->joinMutex);
811 pthread_cond_broadcast(&info->joinCond);
817 /* threads_start_thread ********************************************************
819 Start a thread in the JVM.
821 ******************************************************************************/
823 void threads_start_thread(thread *t, functionptr function)
830 info = &((threadobject *) t->vmThread)->info;
832 /* fill startupinfo structure passed by pthread_create to XXX */
834 startup.thread = (threadobject*) t->vmThread;
835 startup.function = function; /* maybe we don't call Thread.run()V */
837 startup.psem_first = &sem_first;
839 sem_init(&sem, 0, 0);
840 sem_init(&sem_first, 0, 0);
842 if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
844 log_text("pthread_create failed");
848 sem_post(&sem_first);
850 /* wait here until the thread has entered itself into the thread list */
854 sem_destroy(&sem_first);
858 /* At the end of the program, we wait for all running non-daemon threads to die
861 static threadobject *findNonDaemon(threadobject *thread)
863 while (thread != mainthreadobj) {
864 if (!thread->o.thread->daemon)
866 thread = thread->info.prev;
872 void joinAllThreads()
874 threadobject *thread;
875 pthread_mutex_lock(&threadlistlock);
876 while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
877 nativethread *info = &thread->info;
878 pthread_mutex_lock(&info->joinMutex);
879 pthread_mutex_unlock(&threadlistlock);
881 pthread_cond_wait(&info->joinCond, &info->joinMutex);
882 pthread_mutex_unlock(&info->joinMutex);
883 pthread_mutex_lock(&threadlistlock);
885 pthread_mutex_unlock(&threadlistlock);
888 static void initLockRecord(monitorLockRecord *r, threadobject *t)
895 r->incharge = (monitorLockRecord *) &dummyLR;
897 sem_init(&r->queueSem, 0, 0);
898 pthread_mutex_init(&r->resolveLock, NULL);
899 pthread_cond_init(&r->resolveWait, NULL);
902 /* No lock record must ever be destroyed because there may still be references
905 static void destroyLockRecord(monitorLockRecord *r)
907 sem_destroy(&r->queueSem);
908 pthread_mutex_destroy(&r->resolveLock);
909 pthread_cond_destroy(&r->resolveWait);
915 initThreadLocks(mainthreadobj);
918 static void initThreadLocks(threadobject *thread)
920 thread->ee.firstLR = NULL;
921 thread->ee.lrpool = NULL;
922 thread->ee.numlr = 0;
925 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
927 lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
930 p->header.size = size;
931 for (i=0; i<size; i++) {
932 initLockRecord(&p->lr[i], thread);
933 p->lr[i].nextFree = &p->lr[i+1];
935 p->lr[i-1].nextFree = NULL;
939 #define INITIALLOCKRECORDS 8
941 pthread_mutex_t pool_lock;
942 lockRecordPool *global_pool;
944 static void initPools()
946 pthread_mutex_init(&pool_lock, NULL);
949 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
951 pthread_mutex_lock(&pool_lock);
954 lockRecordPool *pool = global_pool;
955 global_pool = pool->header.next;
956 pthread_mutex_unlock(&pool_lock);
958 for (i=0; i < pool->header.size; i++) {
959 pool->lr[i].ownerThread = t;
960 pool->lr[i].nextFree = &pool->lr[i+1];
962 pool->lr[i-1].nextFree = NULL;
966 pthread_mutex_unlock(&pool_lock);
968 return allocNewLockRecordPool(t, size);
971 static void freeLockRecordPools(lockRecordPool *pool)
973 lockRecordPoolHeader *last;
974 pthread_mutex_lock(&pool_lock);
975 last = &pool->header;
977 last = &last->next->header;
978 last->next = global_pool;
980 pthread_mutex_unlock(&pool_lock);
983 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
985 monitorLockRecord *r;
991 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
992 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
993 pool->header.next = t->ee.lrpool;
996 t->ee.numlr += pool->header.size;
999 t->ee.firstLR = r->nextFree;
1001 r->nextFree = NULL; /* in order to find invalid uses of nextFree */
1006 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
1010 assert(r->ownerThread == t);
1011 assert(r->nextFree == NULL);
1013 r->nextFree = t->ee.firstLR;
1017 void initObjectLock(java_objectheader *o)
1021 o->monitorPtr = dummyLR;
1025 /* get_dummyLR *****************************************************************
1027 Returns the global dummy monitor lock record. The pointer is
1028 required in the code generator to set up a virtual
1029 java_objectheader for code patch locking.
1031 *******************************************************************************/
1033 monitorLockRecord *get_dummyLR(void)
1039 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
1041 atomic_add(&lr->queuers, 1);
1043 MEMORY_BARRIER_AFTER_ATOMIC();
1046 sem_wait(&lr->queueSem);
1048 atomic_add(&lr->queuers, -1);
1051 static void freeLockRecord(monitorLockRecord *lr)
1058 sem_post(&lr->queueSem);
1061 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr, java_objectheader *o)
1063 if (lr->waiting == o)
1067 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1070 monitorLockRecord *lr = o->monitorPtr;
1072 /* the lock record does not lock this object */
1073 monitorLockRecord *nlr;
1074 monitorLockRecord *mlr;
1076 /* allocate a new lock record for this object */
1077 mlr = allocLockRecordSimple(t);
1080 /* check if it is the same record the object refered to earlier */
1083 nlr = o->monitorPtr;
1085 /* the object still refers to the same lock record */
1087 handleWaiter(mlr, lr, o);
1092 /* no, it's another lock record */
1093 /* if we don't own the old record, set incharge XXX */
1094 if (lr->ownerThread != t)
1097 /* if the object still refers to lr, replace it by the new mlr */
1098 MEMORY_BARRIER_BEFORE_ATOMIC();
1099 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1103 /* we swapped the new record in successfully */
1104 if (mlr == lr || lr->o != o) {
1105 /* the old lock record is the same as the new one, or */
1106 /* it locks another object. */
1108 handleWaiter(mlr, lr, o);
1111 /* lr locks the object, we have to wait */
1113 queueOnLockRecord(lr, o);
1116 handleWaiter(mlr, lr, o);
1120 /* forget this mlr lock record, wait on nlr and try again */
1121 freeLockRecord(mlr);
1122 recycleLockRecord(t, mlr);
1123 queueOnLockRecord(nlr, o);
1126 /* the lock record is for the object we want */
1128 if (lr->ownerThread == t) {
1129 /* we own it already, just recurse */
1134 /* it's locked. we wait and then try again */
1135 queueOnLockRecord(lr, o);
1140 static void wakeWaiters(monitorLockRecord *lr)
1142 monitorLockRecord *tmplr;
1145 /* assign lock record to a temporary variable */
1153 sem_post(&tmplr->queueSem);
1155 tmplr = tmplr->waiter;
1156 } while (tmplr != NULL && tmplr != lr);
1159 #define GRAB_LR(lr,t) \
1160 if (lr->ownerThread != t) { \
1161 lr = lr->incharge; \
1164 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1165 if (lr->o != mo || lr->ownerThread != t) { \
1166 *exceptionptr = new_illegalmonitorstateexception(); \
1170 bool monitorExit(threadobject *t, java_objectheader *o)
1172 monitorLockRecord *lr = o->monitorPtr;
1174 CHECK_MONITORSTATE(lr, t, o, return false);
1176 if (lr->lockCount > 1) {
1177 /* we had locked this one recursively. just decrement, it will */
1178 /* still be locked. */
1184 monitorLockRecord *wlr = lr->waiter;
1185 if (o->monitorPtr != lr ||
1186 (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1188 monitorLockRecord *nlr = o->monitorPtr;
1190 STORE_ORDER_BARRIER();
1198 /* unlock and throw away this lock record */
1200 recycleLockRecord(t, lr);
1204 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1207 if (lr->waiter == wlr) {
1208 lr->waiter = wlr->waiter;
1212 } while (lr); /* XXX need to break cycle? */
1215 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1217 return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1220 static bool timeIsEarlier(const struct timespec *tv)
1222 struct timeval tvnow;
1223 struct timespec tsnow;
1224 gettimeofday(&tvnow, NULL);
1225 tsnow.tv_sec = tvnow.tv_sec;
1226 tsnow.tv_nsec = tvnow.tv_usec * 1000;
1227 return timespec_less(&tsnow, tv);
1231 /* waitWithTimeout *************************************************************
1235 *******************************************************************************/
1237 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1239 bool wasinterrupted;
1241 pthread_mutex_lock(&t->waitLock);
1243 t->isSleeping = true;
1245 if (wakeupTime->tv_sec || wakeupTime->tv_nsec) {
1246 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1247 pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1250 while (!t->interrupted && !t->signaled)
1251 pthread_cond_wait(&t->waitCond, &t->waitLock);
1254 wasinterrupted = t->interrupted;
1255 t->interrupted = false;
1256 t->signaled = false;
1257 t->isSleeping = false;
1259 pthread_mutex_unlock(&t->waitLock);
1261 return wasinterrupted;
1265 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1267 if (millis || nanos) {
1270 gettimeofday(&tv, NULL);
1271 tv.tv_sec += millis / 1000;
1273 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1274 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1275 tm->tv_nsec = nsec % 1000000000;
1283 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1285 bool wasinterrupted;
1286 struct timespec wakeupTime;
1287 monitorLockRecord *mlr, *lr = o->monitorPtr;
1289 CHECK_MONITORSTATE(lr, t, o, return);
1291 calcAbsoluteTime(&wakeupTime, millis, nanos);
1294 wakeWaiters(lr->waiter);
1296 STORE_ORDER_BARRIER();
1298 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1299 mlr = monitorEnter(t, o);
1300 removeFromWaiters(mlr, lr);
1301 mlr->lockCount = lr->lockCount;
1305 recycleLockRecord(t, lr);
1308 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1311 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1313 monitorLockRecord *lr = o->monitorPtr;
1315 CHECK_MONITORSTATE(lr, t, o, return);
1317 threadobject *wthread;
1318 monitorLockRecord *wlr = lr->waiter;
1321 wthread = wlr->ownerThread;
1322 pthread_mutex_lock(&wthread->waitLock);
1323 if (wthread->isSleeping)
1324 pthread_cond_signal(&wthread->waitCond);
1325 wthread->signaled = true;
1326 pthread_mutex_unlock(&wthread->waitLock);
1331 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1333 monitorLockRecord *lr = o->monitorPtr;
1335 /* The reason why we have to check against NULL is that
1336 * dummyLR->incharge == NULL */
1337 return lr->o == o && lr->ownerThread == t;
1340 void interruptThread(java_lang_VMThread *thread)
1342 threadobject *t = (threadobject*) thread;
1344 pthread_mutex_lock(&t->waitLock);
1346 pthread_cond_signal(&t->waitCond);
1347 t->interrupted = true;
1348 pthread_mutex_unlock(&t->waitLock);
1351 bool interruptedThread()
1353 threadobject *t = (threadobject*) THREADOBJECT;
1354 bool intr = t->interrupted;
1355 t->interrupted = false;
1359 bool isInterruptedThread(java_lang_VMThread *thread)
1361 threadobject *t = (threadobject*) thread;
1362 return t->interrupted;
1366 /* thread_sleep ****************************************************************
1368 Sleep the current thread for the specified amount of time.
1370 *******************************************************************************/
1372 void thread_sleep(s8 millis, s4 nanos)
1375 struct timespec wakeupTime;
1376 monitorLockRecord *lr;
1377 bool wasinterrupted;
1379 t = (threadobject *) THREADOBJECT;
1381 calcAbsoluteTime(&wakeupTime, millis, nanos);
1383 lr = allocLockRecordSimple(t);
1385 wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1387 recycleLockRecord(t, lr);
1390 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1398 void setPriorityThread(thread *t, s4 priority)
1400 nativethread *info = &((threadobject*) t->vmThread)->info;
1401 setPriority(info->tid, priority);
1404 void wait_cond_for_object(java_objectheader *o, s8 millis, s4 nanos)
1406 threadobject *t = (threadobject*) THREADOBJECT;
1407 monitorWait(t, o, millis, nanos);
1410 void signal_cond_for_object(java_objectheader *o)
1412 threadobject *t = (threadobject*) THREADOBJECT;
1413 notifyOneOrAll(t, o, true);
1416 void broadcast_cond_for_object(java_objectheader *o)
1418 threadobject *t = (threadobject*) THREADOBJECT;
1419 notifyOneOrAll(t, o, false);
1423 /* threads_dump ****************************************************************
1425 Dumps info for all threads running in the JVM. This function is
1426 called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1428 *******************************************************************************/
1430 void threads_dump(void)
1433 java_lang_VMThread *vmt;
1435 java_lang_Thread *t;
1438 tobj = mainthreadobj;
1440 printf("Full thread dump CACAO "VERSION":\n");
1442 /* iterate over all started threads */
1445 /* get thread objects */
1451 /* the thread may be currently in initalization, don't print it */
1454 /* get thread name */
1456 name = javastring_toutf(t->name, false);
1465 #if SIZEOF_VOID_P == 8
1466 printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1468 printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1471 /* send SIGUSR1 to thread to print stacktrace */
1473 pthread_kill(nt->tid, SIGUSR1);
1475 /* sleep this thread a bit, so the signal can reach the thread */
1477 thread_sleep(10, 0);
1480 tobj = tobj->info.next;
1481 } while (tobj && (tobj != mainthreadobj));
1486 * These are local overrides for various environment variables in Emacs.
1487 * Please do not remove this and leave it at the end of the file, where
1488 * Emacs will automagically detect them.
1489 * ---------------------------------------------------------------------
1492 * indent-tabs-mode: t
1496 * vim:noexpandtab:sw=4:ts=4: