* Updated header: Added 2006. Changed address of FSF. Changed email
[cacao.git] / src / threads / native / threads.c
1 /* src/threads/native/threads.c - native threads support
2
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
7
8    This file is part of CACAO.
9
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.
14
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.
19
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
23    02110-1301, USA.
24
25    Contact: cacao@cacaojvm.org
26
27    Authors: Stefan Ring
28
29    Changes: Christian Thalinger
30
31    $Id: threads.c 4357 2006-01-22 23:33:38Z twisti $
32
33 */
34
35
36 #include <stdlib.h>
37 #include <string.h>
38 #include <assert.h>
39 #include <sys/types.h>
40 #include <unistd.h>
41 #include <signal.h>
42 #include <sys/time.h>
43 #include <time.h>
44 #include <errno.h>
45
46 #include <pthread.h>
47 #include <semaphore.h>
48
49 #include "config.h"
50 #include "vm/types.h"
51
52 #include "arch.h"
53
54 #ifndef USE_MD_THREAD_STUFF
55 #include "machine-instr.h"
56 #else
57 #include "threads/native/generic-primitives.h"
58 #endif
59
60 #include "cacao/cacao.h"
61 #include "mm/boehm.h"
62 #include "mm/memory.h"
63 #include "native/native.h"
64 #include "native/include/java_lang_Object.h"
65 #include "native/include/java_lang_Throwable.h"
66 #include "native/include/java_lang_Thread.h"
67 #include "native/include/java_lang_ThreadGroup.h"
68 #include "native/include/java_lang_VMThread.h"
69 #include "threads/native/threads.h"
70 #include "toolbox/avl.h"
71 #include "toolbox/logging.h"
72 #include "vm/builtin.h"
73 #include "vm/exceptions.h"
74 #include "vm/global.h"
75 #include "vm/loader.h"
76 #include "vm/options.h"
77 #include "vm/stringlocal.h"
78 #include "vm/jit/asmpart.h"
79
80 #if !defined(__DARWIN__)
81 #if defined(__LINUX__)
82 #define GC_LINUX_THREADS
83 #elif defined(__MIPS__)
84 #define GC_IRIX_THREADS
85 #endif
86 #include "boehm-gc/include/gc.h"
87 #endif
88
89 #ifdef USE_MD_THREAD_STUFF
90 pthread_mutex_t _atomic_add_lock = PTHREAD_MUTEX_INITIALIZER;
91 pthread_mutex_t _cas_lock = PTHREAD_MUTEX_INITIALIZER;
92 pthread_mutex_t _mb_lock = PTHREAD_MUTEX_INITIALIZER;
93 #endif
94
95 #ifdef MUTEXSIM
96
97 /* We need this for older MacOSX (10.1.x) */
98
99 typedef struct {
100         pthread_mutex_t mutex;
101         pthread_t owner;
102         int count;
103 } pthread_mutex_rec_t;
104
105 static void pthread_mutex_init_rec(pthread_mutex_rec_t *m)
106 {
107         pthread_mutex_init(&m->mutex, NULL);
108         m->count = 0;
109 }
110
111 static void pthread_mutex_destroy_rec(pthread_mutex_rec_t *m)
112 {
113         pthread_mutex_destroy(&m->mutex);
114 }
115
116 static void pthread_mutex_lock_rec(pthread_mutex_rec_t *m)
117 {
118         for (;;)
119                 if (!m->count)
120                 {
121                         pthread_mutex_lock(&m->mutex);
122                         m->owner = pthread_self();
123                         m->count++;
124                         break;
125                 } else {
126                         if (m->owner != pthread_self())
127                                 pthread_mutex_lock(&m->mutex);
128                         else
129                         {
130                                 m->count++;
131                                 break;
132                         }
133                 }
134 }
135
136 static void pthread_mutex_unlock_rec(pthread_mutex_rec_t *m)
137 {
138         if (!--m->count)
139                 pthread_mutex_unlock(&m->mutex);
140 }
141
142 #else /* MUTEXSIM */
143
144 #define pthread_mutex_lock_rec pthread_mutex_lock
145 #define pthread_mutex_unlock_rec pthread_mutex_unlock
146 #define pthread_mutex_rec_t pthread_mutex_t
147
148 #endif /* MUTEXSIM */
149
150 static void setPriority(pthread_t tid, int priority)
151 {
152         struct sched_param schedp;
153         int policy;
154
155         pthread_getschedparam(tid, &policy, &schedp);
156         schedp.sched_priority = priority;
157         pthread_setschedparam(tid, policy, &schedp);
158 }
159
160
161 static avl_tree *criticaltree;
162 threadobject *mainthreadobj;
163
164 #ifndef HAVE___THREAD
165 pthread_key_t tkey_threadinfo;
166 #else
167 __thread threadobject *threadobj;
168 #endif
169
170 static pthread_mutex_rec_t compiler_mutex;
171 static pthread_mutex_rec_t tablelock;
172
173 void compiler_lock()
174 {
175         pthread_mutex_lock_rec(&compiler_mutex);
176 }
177
178 void compiler_unlock()
179 {
180         pthread_mutex_unlock_rec(&compiler_mutex);
181 }
182
183 void tables_lock()
184 {
185     pthread_mutex_lock_rec(&tablelock);
186 }
187
188 void tables_unlock()
189 {
190     pthread_mutex_unlock_rec(&tablelock);
191 }
192
193
194 static s4 criticalcompare(const void *pa, const void *pb)
195 {
196         const threadcritnode *na = pa;
197         const threadcritnode *nb = pb;
198
199         if (na->mcodebegin < nb->mcodebegin)
200                 return -1;
201         if (na->mcodebegin > nb->mcodebegin)
202                 return 1;
203         return 0;
204 }
205
206
207 static const threadcritnode *findcritical(u1 *mcodeptr)
208 {
209     avl_node *n;
210     const threadcritnode *m;
211
212     n = criticaltree->root;
213         m = NULL;
214
215     if (!n)
216         return NULL;
217
218     for (;;) {
219         const threadcritnode *d = n->data;
220
221         if (mcodeptr == d->mcodebegin)
222             return d;
223
224         if (mcodeptr < d->mcodebegin) {
225             if (n->childs[0])
226                 n = n->childs[0];
227             else
228                 return m;
229
230         } else {
231             if (n->childs[1]) {
232                 m = n->data;
233                 n = n->childs[1];
234             } else
235                 return n->data;
236         }
237     }
238 }
239
240
241 void thread_registercritical(threadcritnode *n)
242 {
243         avl_insert(criticaltree, n);
244 }
245
246 u1 *thread_checkcritical(u1 *mcodeptr)
247 {
248         const threadcritnode *n = findcritical(mcodeptr);
249         return (n && mcodeptr < n->mcodeend && mcodeptr > n->mcodebegin) ? n->mcoderestart : NULL;
250 }
251
252 static void thread_addstaticcritical()
253 {
254         /* XXX TWISTI: this is just a quick hack */
255 #if defined(ENABLE_JIT)
256         threadcritnode *n = &asm_criticalsections;
257
258         while (n->mcodebegin)
259                 thread_registercritical(n++);
260 #endif
261 }
262
263 static pthread_mutex_t threadlistlock;
264
265 static pthread_mutex_t stopworldlock;
266 volatile int stopworldwhere;
267
268 static sem_t suspend_ack;
269 #if defined(__MIPS__)
270 static pthread_mutex_t suspend_ack_lock = PTHREAD_MUTEX_INITIALIZER;
271 static pthread_cond_t suspend_cond = PTHREAD_COND_INITIALIZER;
272 #endif
273
274 /*
275  * where - 1 from within GC
276            2 class numbering
277  */
278 void lock_stopworld(int where)
279 {
280         pthread_mutex_lock(&stopworldlock);
281         stopworldwhere = where;
282 }
283
284 void unlock_stopworld()
285 {
286         stopworldwhere = 0;
287         pthread_mutex_unlock(&stopworldlock);
288 }
289
290 #if !defined(__DARWIN__)
291 /* Caller must hold threadlistlock */
292 static int cast_sendsignals(int sig, int count)
293 {
294         /* Count threads */
295         threadobject *tobj = mainthreadobj;
296         nativethread *infoself = THREADINFO;
297
298         if (count == 0)
299                 do {
300                         count++;
301                         tobj = tobj->info.next;
302                 } while (tobj != mainthreadobj);
303
304         do {
305                 nativethread *info = &tobj->info;
306                 if (info != infoself)
307                         pthread_kill(info->tid, sig);
308                 tobj = tobj->info.next;
309         } while (tobj != mainthreadobj);
310
311         return count-1;
312 }
313
314 #else
315
316 static void cast_darwinstop()
317 {
318         threadobject *tobj = mainthreadobj;
319         nativethread *infoself = THREADINFO;
320
321         do {
322                 nativethread *info = &tobj->info;
323                 if (info != infoself)
324                 {
325                         thread_state_flavor_t flavor = PPC_THREAD_STATE;
326                         mach_msg_type_number_t thread_state_count = PPC_THREAD_STATE_COUNT;
327                         ppc_thread_state_t thread_state;
328                         mach_port_t thread = info->mach_thread;
329                         kern_return_t r;
330
331                         r = thread_suspend(thread);
332                         if (r != KERN_SUCCESS) {
333                                 log_text("thread_suspend failed");
334                                 assert(0);
335                         }
336
337                         r = thread_get_state(thread, flavor,
338                                 (natural_t*)&thread_state, &thread_state_count);
339                         if (r != KERN_SUCCESS) {
340                                 log_text("thread_get_state failed");
341                                 assert(0);
342                         }
343
344                         thread_restartcriticalsection(&thread_state);
345
346                         r = thread_set_state(thread, flavor,
347                                 (natural_t*)&thread_state, thread_state_count);
348                         if (r != KERN_SUCCESS) {
349                                 log_text("thread_set_state failed");
350                                 assert(0);
351                         }
352                 }
353                 tobj = tobj->info.next;
354         } while (tobj != mainthreadobj);
355 }
356
357 static void cast_darwinresume()
358 {
359         threadobject *tobj = mainthreadobj;
360         nativethread *infoself = THREADINFO;
361
362         do {
363                 nativethread *info = &tobj->info;
364                 if (info != infoself)
365                 {
366                         mach_port_t thread = info->mach_thread;
367                         kern_return_t r;
368
369                         r = thread_resume(thread);
370                         if (r != KERN_SUCCESS) {
371                                 log_text("thread_resume failed");
372                                 assert(0);
373                         }
374                 }
375                 tobj = tobj->info.next;
376         } while (tobj != mainthreadobj);
377 }
378
379 #endif
380
381 #if defined(__MIPS__)
382 static void cast_irixresume()
383 {
384         pthread_mutex_lock(&suspend_ack_lock);
385         pthread_cond_broadcast(&suspend_cond);
386         pthread_mutex_unlock(&suspend_ack_lock);
387 }
388 #endif
389
390 void cast_stopworld()
391 {
392         int count, i;
393         lock_stopworld(2);
394         pthread_mutex_lock(&threadlistlock);
395 #if defined(__DARWIN__)
396         cast_darwinstop();
397 #else
398         count = cast_sendsignals(GC_signum1(), 0);
399         for (i=0; i<count; i++)
400                 sem_wait(&suspend_ack);
401 #endif
402         pthread_mutex_unlock(&threadlistlock);
403 }
404
405 void cast_startworld()
406 {
407         pthread_mutex_lock(&threadlistlock);
408 #if defined(__DARWIN__)
409         cast_darwinresume();
410 #elif defined(__MIPS__)
411         cast_irixresume();
412 #else
413         cast_sendsignals(GC_signum2(), -1);
414 #endif
415         pthread_mutex_unlock(&threadlistlock);
416         unlock_stopworld();
417 }
418
419 #if !defined(__DARWIN__)
420 static void sigsuspend_handler(ucontext_t *ctx)
421 {
422         int sig;
423         sigset_t sigs;
424         
425         /* XXX TWISTI: this is just a quick hack */
426 #if defined(ENABLE_JIT)
427         thread_restartcriticalsection(ctx);
428 #endif
429
430         /* Do as Boehm does. On IRIX a condition variable is used for wake-up
431            (not POSIX async-safe). */
432 #if defined(__IRIX__)
433         pthread_mutex_lock(&suspend_ack_lock);
434         sem_post(&suspend_ack);
435         pthread_cond_wait(&suspend_cond, &suspend_ack_lock);
436         pthread_mutex_unlock(&suspend_ack_lock);
437 #else
438         sem_post(&suspend_ack);
439
440         sig = GC_signum2();
441         sigfillset(&sigs);
442         sigdelset(&sigs, sig);
443         sigsuspend(&sigs);
444 #endif
445 }
446
447 int cacao_suspendhandler(ucontext_t *ctx)
448 {
449         if (stopworldwhere != 2)
450                 return 0;
451
452         sigsuspend_handler(ctx);
453         return 1;
454 }
455 #endif
456
457 static void setthreadobject(threadobject *thread)
458 {
459 #if !defined(HAVE___THREAD)
460         pthread_setspecific(tkey_threadinfo, thread);
461 #else
462         threadobj = thread;
463 #endif
464 }
465
466
467 /* thread_setself **************************************************************
468
469    XXX
470
471 *******************************************************************************/
472
473 void *thread_getself(void)
474 {
475         return pthread_getspecific(tkey_threadinfo);
476 }
477
478
479 static monitorLockRecord *dummyLR;
480
481 static void initPools();
482
483
484 /* thread_preinit **************************************************************
485
486    Do some early initialization of stuff required.
487
488 *******************************************************************************/
489
490 void threads_preinit(void)
491 {
492 #ifndef MUTEXSIM
493         pthread_mutexattr_t mutexattr;
494         pthread_mutexattr_init(&mutexattr);
495         pthread_mutexattr_settype(&mutexattr, PTHREAD_MUTEX_RECURSIVE);
496         pthread_mutex_init(&compiler_mutex, &mutexattr);
497         pthread_mutex_init(&tablelock, &mutexattr);
498         pthread_mutexattr_destroy(&mutexattr);
499 #else
500         pthread_mutex_init_rec(&compiler_mutex);
501         pthread_mutex_init_rec(&tablelock);
502 #endif
503
504         pthread_mutex_init(&threadlistlock, NULL);
505         pthread_mutex_init(&stopworldlock, NULL);
506
507         /* Allocate something so the garbage collector's signal handlers
508            are installed. */
509         heap_allocate(1, false, NULL);
510
511         mainthreadobj = NEW(threadobject);
512         mainthreadobj->info.tid = pthread_self();
513 #if !defined(HAVE___THREAD)
514         pthread_key_create(&tkey_threadinfo, NULL);
515 #endif
516         setthreadobject(mainthreadobj);
517         initPools();
518
519         /* Every newly created object's monitorPtr points here so we save
520            a check against NULL */
521
522         dummyLR = NEW(monitorLockRecord);
523         dummyLR->o = NULL;
524         dummyLR->ownerThread = NULL;
525         dummyLR->waiting = false;
526
527         /* we need a working dummyLR before initializing the critical
528            section tree */
529
530     criticaltree = avl_create(&criticalcompare);
531
532         thread_addstaticcritical();
533         sem_init(&suspend_ack, 0, 0);
534 }
535
536
537 static pthread_attr_t threadattr;
538
539 static void freeLockRecordPools(lockRecordPool *);
540
541
542 /* threads_init ****************************************************************
543
544    Initializes the threads required by the JVM: main, finalizer.
545
546 *******************************************************************************/
547
548 bool threads_init(u1 *stackbottom)
549 {
550         java_lang_String      *threadname;
551         java_lang_Thread      *mainthread;
552         java_lang_ThreadGroup *threadgroup;
553         threadobject          *tempthread;
554         methodinfo            *method;
555
556         tempthread = mainthreadobj;
557
558         freeLockRecordPools(mainthreadobj->ee.lrpool);
559
560         /* This is kinda tricky, we grow the java.lang.Thread object so we
561            can keep the execution environment there. No Thread object must
562            have been created at an earlier time. */
563
564         class_java_lang_VMThread->instancesize = sizeof(threadobject);
565
566         /* create a VMThread */
567
568         mainthreadobj = (threadobject *) builtin_new(class_java_lang_VMThread);
569
570         if (!mainthreadobj)
571                 return false;
572
573         FREE(tempthread, threadobject);
574
575         initThread(&mainthreadobj->o);
576
577         setthreadobject(mainthreadobj);
578
579         initLocks();
580
581         mainthreadobj->info.next = mainthreadobj;
582         mainthreadobj->info.prev = mainthreadobj;
583
584 #if defined(ENABLE_INTRP)
585         /* create interpreter stack */
586
587         if (opt_intrp) {
588                 MSET(intrp_main_stack, 0, u1, opt_stacksize);
589                 mainthreadobj->info._global_sp = intrp_main_stack + opt_stacksize;
590         }
591 #endif
592
593         threadname = javastring_new(utf_new_char("main"));
594
595         /* allocate and init ThreadGroup */
596
597         threadgroup = (java_lang_ThreadGroup *)
598                 native_new_and_init(class_java_lang_ThreadGroup);
599
600         if (!threadgroup)
601                 throw_exception_exit();
602
603         /* create a Thread */
604
605         mainthread = (java_lang_Thread *) builtin_new(class_java_lang_Thread);
606
607         if (!mainthread)
608                 throw_exception_exit();
609
610         mainthreadobj->o.thread = mainthread;
611
612         /* call Thread.<init>(Ljava/lang/VMThread;Ljava/lang/String;IZ)V */
613
614         method = class_resolveclassmethod(class_java_lang_Thread,
615                                                                           utf_init,
616                                                                           utf_new_char("(Ljava/lang/VMThread;Ljava/lang/String;IZ)V"),
617                                                                           class_java_lang_Thread,
618                                                                           true);
619
620         if (!method)
621                 return false;
622
623         ASM_CALLJAVAFUNCTION(method, mainthread, mainthreadobj, threadname,
624                                                  (void *) 5);
625
626         if (*exceptionptr)
627                 return false;
628
629         mainthread->group = threadgroup;
630         /* XXX This is a hack because the fourth argument was omitted */
631         mainthread->daemon = false;
632
633         /* add mainthread to ThreadGroup */
634
635         method = class_resolveclassmethod(class_java_lang_ThreadGroup,
636                                                                           utf_new_char("addThread"),
637                                                                           utf_new_char("(Ljava/lang/Thread;)V"),
638                                                                           class_java_lang_ThreadGroup,
639                                                                           true);
640
641         if (!method)
642                 return false;
643
644         ASM_CALLJAVAFUNCTION(method, threadgroup, mainthread, NULL, NULL);
645
646         if (*exceptionptr)
647                 return false;
648
649         setPriority(pthread_self(), 5);
650
651         pthread_attr_init(&threadattr);
652         pthread_attr_setdetachstate(&threadattr, PTHREAD_CREATE_DETACHED);
653
654         /* everything's ok */
655
656         return true;
657 }
658
659
660 void initThread(java_lang_VMThread *t)
661 {
662         threadobject *thread = (threadobject*) t;
663         nativethread *info = &thread->info;
664         info->tid = pthread_self();
665         /* TODO destroy all those things */
666         pthread_mutex_init(&info->joinMutex, NULL);
667         pthread_cond_init(&info->joinCond, NULL);
668
669         pthread_mutex_init(&thread->waitLock, NULL);
670         pthread_cond_init(&thread->waitCond, NULL);
671         thread->interrupted = false;
672         thread->signaled = false;
673         thread->isSleeping = false;
674 }
675
676 static void initThreadLocks(threadobject *);
677
678
679 typedef struct {
680         threadobject *thread;
681         functionptr   function;
682         sem_t        *psem;
683         sem_t        *psem_first;
684 } startupinfo;
685
686
687 /* threads_startup *************************************************************
688
689    Thread startup function called by pthread_create.
690
691 ******************************************************************************/
692
693 static void *threads_startup_thread(void *t)
694 {
695         startupinfo  *startup;
696         threadobject *thread;
697         sem_t        *psem;
698         nativethread *info;
699         threadobject *tnext;
700         methodinfo   *method;
701         functionptr   function;
702
703 #if defined(ENABLE_INTRP)
704         u1 *intrp_thread_stack;
705
706         /* create interpreter stack */
707
708         if (opt_intrp) {
709                 intrp_thread_stack = (u1 *) alloca(opt_stacksize);
710                 MSET(intrp_thread_stack, 0, u1, opt_stacksize);
711         }
712 #endif
713
714         /* get passed startupinfo structure and the values in there */
715
716         startup = t;
717
718         thread   = startup->thread;
719         function = startup->function;
720         psem     = startup->psem;
721
722         info = &thread->info;
723
724         /* Seems like we've encountered a situation where info->tid was not set by
725          * pthread_create. We alleviate this problem by waiting for pthread_create
726          * to return. */
727         sem_wait(startup->psem_first);
728
729         t = NULL;
730 #if defined(__DARWIN__)
731         info->mach_thread = mach_thread_self();
732 #endif
733         setthreadobject(thread);
734
735         /* insert the thread into the threadlist */
736
737         pthread_mutex_lock(&threadlistlock);
738
739         info->prev = mainthreadobj;
740         info->next = tnext = mainthreadobj->info.next;
741         mainthreadobj->info.next = thread;
742         tnext->info.prev = thread;
743
744         pthread_mutex_unlock(&threadlistlock);
745
746         initThreadLocks(thread);
747
748         startup = NULL;
749         sem_post(psem);
750
751         setPriority(info->tid, thread->o.thread->priority);
752
753 #if defined(ENABLE_INTRP)
754         /* set interpreter stack */
755
756         if (opt_intrp)
757                 THREADINFO->_global_sp = (void *) (intrp_thread_stack + opt_stacksize);
758 #endif
759
760         /* find and run the Thread.run()V method if no other function was passed */
761
762         if (function == NULL) {
763                 method = class_resolveclassmethod(thread->o.header.vftbl->class,
764                                                                                   utf_run,
765                                                                                   utf_void__void,
766                                                                                   thread->o.header.vftbl->class,
767                                                                                   true);
768
769                 if (!method)
770                         throw_exception();
771
772                 ASM_CALLJAVAFUNCTION(method, thread, NULL, NULL, NULL);
773
774         } else {
775                 /* call passed function, e.g. finalizer_thread */
776
777                 (function)();
778         }
779
780         /* Allow lock record pools to be used by other threads. They
781            cannot be deleted so we'd better not waste them. */
782
783         freeLockRecordPools(thread->ee.lrpool);
784
785         /* remove thread from thread list, do this inside a lock */
786
787         pthread_mutex_lock(&threadlistlock);
788         info->next->info.prev = info->prev;
789         info->prev->info.next = info->next;
790         pthread_mutex_unlock(&threadlistlock);
791
792         /* reset thread id (lock on joinMutex? TWISTI) */
793
794         pthread_mutex_lock(&info->joinMutex);
795         info->tid = 0;
796         pthread_mutex_unlock(&info->joinMutex);
797
798         pthread_cond_broadcast(&info->joinCond);
799
800         return NULL;
801 }
802
803
804 /* threads_start_thread ********************************************************
805
806    Start a thread in the JVM.
807
808 ******************************************************************************/
809
810 void threads_start_thread(thread *t, functionptr function)
811 {
812         nativethread *info;
813         sem_t         sem;
814         sem_t         sem_first;
815         startupinfo   startup;
816
817         info = &((threadobject *) t->vmThread)->info;
818
819         /* fill startupinfo structure passed by pthread_create to XXX */
820
821         startup.thread     = (threadobject*) t->vmThread;
822         startup.function   = function;       /* maybe we don't call Thread.run()V */
823         startup.psem       = &sem;
824         startup.psem_first = &sem_first;
825
826         sem_init(&sem, 0, 0);
827         sem_init(&sem_first, 0, 0);
828         
829         if (pthread_create(&info->tid, &threadattr, threads_startup_thread,
830                                            &startup)) {
831                 log_text("pthread_create failed");
832                 assert(0);
833         }
834
835         sem_post(&sem_first);
836
837         /* wait here until the thread has entered itself into the thread list */
838
839         sem_wait(&sem);
840         sem_destroy(&sem);
841         sem_destroy(&sem_first);
842 }
843
844
845 /* At the end of the program, we wait for all running non-daemon threads to die
846  */
847
848 static threadobject *findNonDaemon(threadobject *thread)
849 {
850         while (thread != mainthreadobj) {
851                 if (!thread->o.thread->daemon)
852                         return thread;
853                 thread = thread->info.prev;
854         }
855
856         return NULL;
857 }
858
859 void joinAllThreads()
860 {
861         threadobject *thread;
862         pthread_mutex_lock(&threadlistlock);
863         while ((thread = findNonDaemon(mainthreadobj->info.prev)) != NULL) {
864                 nativethread *info = &thread->info;
865                 pthread_mutex_lock(&info->joinMutex);
866                 pthread_mutex_unlock(&threadlistlock);
867                 while (info->tid)
868                         pthread_cond_wait(&info->joinCond, &info->joinMutex);
869                 pthread_mutex_unlock(&info->joinMutex);
870                 pthread_mutex_lock(&threadlistlock);
871         }
872         pthread_mutex_unlock(&threadlistlock);
873 }
874
875 static void initLockRecord(monitorLockRecord *r, threadobject *t)
876 {
877         r->lockCount = 1;
878         r->ownerThread = t;
879         r->queuers = 0;
880         r->o = NULL;
881         r->waiter = NULL;
882         r->incharge = (monitorLockRecord *) &dummyLR;
883         r->waiting = false;
884         sem_init(&r->queueSem, 0, 0);
885         pthread_mutex_init(&r->resolveLock, NULL);
886         pthread_cond_init(&r->resolveWait, NULL);
887 }
888
889 /* No lock record must ever be destroyed because there may still be references
890  * to it.
891
892 static void destroyLockRecord(monitorLockRecord *r)
893 {
894         sem_destroy(&r->queueSem);
895         pthread_mutex_destroy(&r->resolveLock);
896         pthread_cond_destroy(&r->resolveWait);
897 }
898 */
899
900 void initLocks()
901 {
902         initThreadLocks(mainthreadobj);
903 }
904
905 static void initThreadLocks(threadobject *thread)
906 {
907         thread->ee.firstLR = NULL;
908         thread->ee.lrpool = NULL;
909         thread->ee.numlr = 0;
910 }
911
912 static lockRecordPool *allocNewLockRecordPool(threadobject *thread, int size)
913 {
914         lockRecordPool *p = mem_alloc(sizeof(lockRecordPoolHeader) + sizeof(monitorLockRecord) * size);
915         int i;
916
917         p->header.size = size;
918         for (i=0; i<size; i++) {
919                 initLockRecord(&p->lr[i], thread);
920                 p->lr[i].nextFree = &p->lr[i+1];
921         }
922         p->lr[i-1].nextFree = NULL;
923         return p;
924 }
925
926 #define INITIALLOCKRECORDS 8
927
928 pthread_mutex_t pool_lock;
929 lockRecordPool *global_pool;
930
931 static void initPools()
932 {
933         pthread_mutex_init(&pool_lock, NULL);
934 }
935
936 static lockRecordPool *allocLockRecordPool(threadobject *t, int size)
937 {
938         pthread_mutex_lock(&pool_lock);
939         if (global_pool) {
940                 int i;
941                 lockRecordPool *pool = global_pool;
942                 global_pool = pool->header.next;
943                 pthread_mutex_unlock(&pool_lock);
944
945                 for (i=0; i < pool->header.size; i++)
946                         pool->lr[i].ownerThread = t;
947                 
948                 return pool;
949         }
950         pthread_mutex_unlock(&pool_lock);
951
952         return allocNewLockRecordPool(t, size);
953 }
954
955 static void freeLockRecordPools(lockRecordPool *pool)
956 {
957         lockRecordPoolHeader *last;
958         pthread_mutex_lock(&pool_lock);
959         last = &pool->header;
960         while (last->next)
961                 last = &last->next->header;
962         last->next = global_pool;
963         global_pool = pool;
964         pthread_mutex_unlock(&pool_lock);
965 }
966
967 static monitorLockRecord *allocLockRecordSimple(threadobject *t)
968 {
969         monitorLockRecord *r = t->ee.firstLR;
970
971         if (!r) {
972                 int poolsize = t->ee.numlr ? t->ee.numlr * 2 : INITIALLOCKRECORDS;
973                 lockRecordPool *pool = allocLockRecordPool(t, poolsize);
974                 pool->header.next = t->ee.lrpool;
975                 t->ee.lrpool = pool;
976                 r = &pool->lr[0];
977                 t->ee.numlr += pool->header.size;
978         }
979         
980         t->ee.firstLR = r->nextFree;
981         return r;
982 }
983
984 static inline void recycleLockRecord(threadobject *t, monitorLockRecord *r)
985 {
986         r->nextFree = t->ee.firstLR;
987         t->ee.firstLR = r;
988 }
989
990 void initObjectLock(java_objectheader *o)
991 {
992         o->monitorPtr = dummyLR;
993 }
994
995
996 /* get_dummyLR *****************************************************************
997
998    Returns the global dummy monitor lock record. The pointer is
999    required in the code generator to set up a virtual
1000    java_objectheader for code patch locking.
1001
1002 *******************************************************************************/
1003
1004 monitorLockRecord *get_dummyLR(void)
1005 {
1006         return dummyLR;
1007 }
1008
1009
1010 static void queueOnLockRecord(monitorLockRecord *lr, java_objectheader *o)
1011 {
1012         atomic_add(&lr->queuers, 1);
1013
1014         MEMORY_BARRIER_AFTER_ATOMIC();
1015
1016         while (lr->o == o)
1017                 sem_wait(&lr->queueSem);
1018
1019         atomic_add(&lr->queuers, -1);
1020 }
1021
1022 static void freeLockRecord(monitorLockRecord *lr)
1023 {
1024         int q;
1025         lr->o = NULL;
1026         MEMORY_BARRIER();
1027         q = lr->queuers;
1028         while (q--)
1029                 sem_post(&lr->queueSem);
1030 }
1031
1032 static inline void handleWaiter(monitorLockRecord *mlr, monitorLockRecord *lr)
1033 {
1034         if (lr->waiting)
1035                 mlr->waiter = lr;
1036 }
1037
1038 monitorLockRecord *monitorEnter(threadobject *t, java_objectheader *o)
1039 {
1040         for (;;) {
1041                 monitorLockRecord *lr = o->monitorPtr;
1042                 if (lr->o != o) {
1043                         monitorLockRecord *nlr, *mlr = allocLockRecordSimple(t);
1044                         mlr->o = o;
1045                         if (mlr == lr) {
1046                                 MEMORY_BARRIER();
1047                                 nlr = o->monitorPtr;
1048                                 if (nlr == lr) {
1049                                         handleWaiter(mlr, lr);
1050                                         return mlr;
1051                                 }
1052                         } else {
1053                                 if (lr->ownerThread != t)
1054                                         mlr->incharge = lr;
1055                                 MEMORY_BARRIER_BEFORE_ATOMIC();
1056                                 nlr = (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) mlr);
1057                         }
1058                         if (nlr == lr) {
1059                                 if (mlr == lr || lr->o != o) {
1060                                         handleWaiter(mlr, lr);
1061                                         return mlr;
1062                                 }
1063                                 while (lr->o == o)
1064                                         queueOnLockRecord(lr, o);
1065                                 handleWaiter(mlr, lr);
1066                                 return mlr;
1067                         }
1068                         freeLockRecord(mlr);
1069                         recycleLockRecord(t, mlr);
1070                         queueOnLockRecord(nlr, o);
1071                 } else {
1072                         if (lr->ownerThread == t) {
1073                                 lr->lockCount++;
1074                                 return lr;
1075                         }
1076                         queueOnLockRecord(lr, o);
1077                 }
1078         }
1079 }
1080
1081 static void wakeWaiters(monitorLockRecord *lr)
1082 {
1083         monitorLockRecord *tmplr;
1084         s4 q;
1085
1086         /* assign lock record to a temporary variable */
1087
1088         tmplr = lr;
1089
1090         do {
1091                 q = tmplr->queuers;
1092
1093                 while (q--)
1094                         sem_post(&tmplr->queueSem);
1095
1096                 tmplr = tmplr->waiter;
1097         } while (tmplr != NULL && tmplr != lr);
1098 }
1099
1100 #define GRAB_LR(lr,t) \
1101     if (lr->ownerThread != t) { \
1102                 lr = lr->incharge; \
1103         }
1104
1105 #define CHECK_MONITORSTATE(lr,t,mo,a) \
1106     if (lr == NULL || lr->o != mo || lr->ownerThread != t) { \
1107                 *exceptionptr = new_illegalmonitorstateexception(); \
1108                 a; \
1109         }
1110
1111 bool monitorExit(threadobject *t, java_objectheader *o)
1112 {
1113         monitorLockRecord *lr = o->monitorPtr;
1114         GRAB_LR(lr, t);
1115         CHECK_MONITORSTATE(lr, t, o, return false);
1116         if (lr->lockCount > 1) {
1117                 lr->lockCount--;
1118                 return true;
1119         }
1120         if (lr->waiter) {
1121                 monitorLockRecord *wlr = lr->waiter;
1122                 if (o->monitorPtr != lr ||
1123                         (void*) compare_and_swap((long*) &o->monitorPtr, (long) lr, (long) wlr) != lr)
1124                 {
1125                         monitorLockRecord *nlr = o->monitorPtr;
1126                         nlr->waiter = wlr;
1127                         STORE_ORDER_BARRIER();
1128                 } else
1129                         wakeWaiters(wlr);
1130                 lr->waiter = NULL;
1131         }
1132         freeLockRecord(lr);
1133         recycleLockRecord(t, lr);
1134         return true;
1135 }
1136
1137 static void removeFromWaiters(monitorLockRecord *lr, monitorLockRecord *wlr)
1138 {
1139         do {
1140                 if (lr->waiter == wlr) {
1141                         lr->waiter = wlr->waiter;
1142                         break;
1143                 }
1144                 lr = lr->waiter;
1145         } while (lr);
1146 }
1147
1148 static inline bool timespec_less(const struct timespec *tv1, const struct timespec *tv2)
1149 {
1150         return tv1->tv_sec < tv2->tv_sec || (tv1->tv_sec == tv2->tv_sec && tv1->tv_nsec < tv2->tv_nsec);
1151 }
1152
1153 static bool timeIsEarlier(const struct timespec *tv)
1154 {
1155         struct timeval tvnow;
1156         struct timespec tsnow;
1157         gettimeofday(&tvnow, NULL);
1158         tsnow.tv_sec = tvnow.tv_sec;
1159         tsnow.tv_nsec = tvnow.tv_usec * 1000;
1160         return timespec_less(&tsnow, tv);
1161 }
1162
1163
1164 /* waitWithTimeout *************************************************************
1165
1166    XXX
1167
1168 *******************************************************************************/
1169
1170 static bool waitWithTimeout(threadobject *t, monitorLockRecord *lr, struct timespec *wakeupTime)
1171 {
1172         bool wasinterrupted;
1173
1174         pthread_mutex_lock(&t->waitLock);
1175
1176         t->isSleeping = true;
1177
1178         if (wakeupTime->tv_sec || wakeupTime->tv_nsec)
1179                 while (!t->interrupted && !t->signaled && timeIsEarlier(wakeupTime))
1180                         pthread_cond_timedwait(&t->waitCond, &t->waitLock, wakeupTime);
1181         else
1182                 while (!t->interrupted && !t->signaled)
1183                         pthread_cond_wait(&t->waitCond, &t->waitLock);
1184
1185         wasinterrupted = t->interrupted;
1186         t->interrupted = false;
1187         t->signaled = false;
1188         t->isSleeping = false;
1189
1190         pthread_mutex_unlock(&t->waitLock);
1191
1192         return wasinterrupted;
1193 }
1194
1195
1196 static void calcAbsoluteTime(struct timespec *tm, s8 millis, s4 nanos)
1197 {
1198         if (millis || nanos) {
1199                 struct timeval tv;
1200                 long nsec;
1201                 gettimeofday(&tv, NULL);
1202                 tv.tv_sec += millis / 1000;
1203                 millis %= 1000;
1204                 nsec = tv.tv_usec * 1000 + (s4) millis * 1000000 + nanos;
1205                 tm->tv_sec = tv.tv_sec + nsec / 1000000000;
1206                 tm->tv_nsec = nsec % 1000000000;
1207         } else {
1208                 tm->tv_sec = 0;
1209                 tm->tv_nsec = 0;
1210         }
1211 }
1212
1213 void monitorWait(threadobject *t, java_objectheader *o, s8 millis, s4 nanos)
1214 {
1215         bool wasinterrupted;
1216         struct timespec wakeupTime;
1217         monitorLockRecord *mlr, *lr = o->monitorPtr;
1218         GRAB_LR(lr, t);
1219         CHECK_MONITORSTATE(lr, t, o, return);
1220
1221         calcAbsoluteTime(&wakeupTime, millis, nanos);
1222         
1223         if (lr->waiter)
1224                 wakeWaiters(lr->waiter);
1225         lr->waiting = true;
1226         STORE_ORDER_BARRIER();
1227         freeLockRecord(lr);
1228         wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1229         mlr = monitorEnter(t, o);
1230         removeFromWaiters(mlr, lr);
1231         mlr->lockCount = lr->lockCount;
1232         lr->lockCount = 1;
1233         lr->waiting = false;
1234         lr->waiter = NULL;
1235         recycleLockRecord(t, lr);
1236
1237         if (wasinterrupted)
1238                 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1239 }
1240
1241 static void notifyOneOrAll(threadobject *t, java_objectheader *o, bool one)
1242 {
1243         monitorLockRecord *lr = o->monitorPtr;
1244         GRAB_LR(lr, t);
1245         CHECK_MONITORSTATE(lr, t, o, return);
1246         do {
1247                 threadobject *wthread;
1248                 monitorLockRecord *wlr = lr->waiter;
1249                 if (!wlr)
1250                         break;
1251                 wthread = wlr->ownerThread;
1252                 pthread_mutex_lock(&wthread->waitLock);
1253                 if (wthread->isSleeping)
1254                         pthread_cond_signal(&wthread->waitCond);
1255                 wthread->signaled = true;
1256                 pthread_mutex_unlock(&wthread->waitLock);
1257                 lr = wlr;
1258         } while (!one);
1259 }
1260
1261 bool threadHoldsLock(threadobject *t, java_objectheader *o)
1262 {
1263         monitorLockRecord *lr = o->monitorPtr;
1264         GRAB_LR(lr, t);
1265         /* The reason why we have to check against NULL is that
1266          * dummyLR->incharge == NULL */
1267         return lr && lr->o == o && lr->ownerThread == t;
1268 }
1269
1270 void interruptThread(java_lang_VMThread *thread)
1271 {
1272         threadobject *t = (threadobject*) thread;
1273
1274         t->interrupted = true;
1275         pthread_mutex_lock(&t->waitLock);
1276         if (t->isSleeping)
1277                 pthread_cond_signal(&t->waitCond);
1278         pthread_mutex_unlock(&t->waitLock);
1279 }
1280
1281 bool interruptedThread()
1282 {
1283         threadobject *t = (threadobject*) THREADOBJECT;
1284         bool intr = t->interrupted;
1285         t->interrupted = false;
1286         return intr;
1287 }
1288
1289 bool isInterruptedThread(java_lang_VMThread *thread)
1290 {
1291         threadobject *t = (threadobject*) thread;
1292         return t->interrupted;
1293 }
1294
1295 void sleepThread(s8 millis, s4 nanos)
1296 {
1297         bool wasinterrupted;
1298         threadobject *t = (threadobject*) THREADOBJECT;
1299         monitorLockRecord *lr;
1300         struct timespec wakeupTime;
1301         calcAbsoluteTime(&wakeupTime, millis, nanos);
1302
1303         lr = allocLockRecordSimple(t);
1304         wasinterrupted = waitWithTimeout(t, lr, &wakeupTime);
1305         recycleLockRecord(t, lr);
1306
1307         if (wasinterrupted)
1308                 *exceptionptr = new_exception(string_java_lang_InterruptedException);
1309 }
1310
1311 void yieldThread()
1312 {
1313         sched_yield();
1314 }
1315
1316 void setPriorityThread(thread *t, s4 priority)
1317 {
1318         nativethread *info = &((threadobject*) t->vmThread)->info;
1319         setPriority(info->tid, priority);
1320 }
1321
1322 void wait_cond_for_object(java_objectheader *o, s8 time, s4 nanos)
1323 {
1324         threadobject *t = (threadobject*) THREADOBJECT;
1325         monitorWait(t, o, time, nanos);
1326 }
1327
1328 void signal_cond_for_object(java_objectheader *o)
1329 {
1330         threadobject *t = (threadobject*) THREADOBJECT;
1331         notifyOneOrAll(t, o, true);
1332 }
1333
1334 void broadcast_cond_for_object(java_objectheader *o)
1335 {
1336         threadobject *t = (threadobject*) THREADOBJECT;
1337         notifyOneOrAll(t, o, false);
1338 }
1339
1340
1341 /* threads_dump ****************************************************************
1342
1343    Dumps info for all threads running in the JVM. This function is
1344    called when SIGQUIT (<ctrl>-\) is sent to CACAO.
1345
1346 *******************************************************************************/
1347
1348 void threads_dump(void)
1349 {
1350         threadobject       *tobj;
1351         java_lang_VMThread *vmt;
1352         nativethread       *nt;
1353         ExecEnvironment    *ee;
1354         java_lang_Thread   *t;
1355         utf                *name;
1356
1357         tobj = mainthreadobj;
1358
1359         printf("Full thread dump CACAO "VERSION":\n");
1360
1361         /* iterate over all started threads */
1362
1363         do {
1364                 /* get thread objects */
1365
1366                 vmt = &tobj->o;
1367                 nt  = &tobj->info;
1368                 ee  = &tobj->ee;
1369                 t   = vmt->thread;
1370
1371                 /* the thread may be currently in initalization, don't print it */
1372
1373                 if (t) {
1374                         /* get thread name */
1375
1376                         name = javastring_toutf(t->name, false);
1377
1378                         printf("\n\"");
1379                         utf_display(name);
1380                         printf("\" ");
1381
1382                         if (t->daemon)
1383                                 printf("daemon ");
1384
1385 #if SIZEOF_VOID_P == 8
1386                         printf("prio=%d tid=0x%016lx\n", t->priority, nt->tid);
1387 #else
1388                         printf("prio=%d tid=0x%08lx\n", t->priority, nt->tid);
1389 #endif
1390
1391                         /* send SIGUSR1 to thread to print stacktrace */
1392
1393                         pthread_kill(nt->tid, SIGUSR1);
1394
1395                         /* sleep this thread a bit, so the signal can reach the thread */
1396
1397                         sleepThread(10, 0);
1398                 }
1399
1400                 tobj = tobj->info.next;
1401         } while (tobj && (tobj != mainthreadobj));
1402 }
1403
1404
1405 /*
1406  * These are local overrides for various environment variables in Emacs.
1407  * Please do not remove this and leave it at the end of the file, where
1408  * Emacs will automagically detect them.
1409  * ---------------------------------------------------------------------
1410  * Local variables:
1411  * mode: c
1412  * indent-tabs-mode: t
1413  * c-basic-offset: 4
1414  * tab-width: 4
1415  * End:
1416  */