OSDN Git Service

a26c3bd336e78406473514031264ea99cd91494e
[pf3gnuchains/gcc-fork.git] / libjava / posix-threads.cc
1 // posix-threads.cc - interface between libjava and POSIX threads.
2
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2004, 2006  Free Software Foundation
4
5    This file is part of libgcj.
6
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License.  Please consult the file "LIBGCJ_LICENSE" for
9 details.  */
10
11 // TO DO:
12 // * Document signal handling limitations
13
14 #include <config.h>
15
16 #include "posix.h"
17 #include "posix-threads.h"
18
19 // If we're using the Boehm GC, then we need to override some of the
20 // thread primitives.  This is fairly gross.
21 #ifdef HAVE_BOEHM_GC
22 #include <gc.h>
23 #endif /* HAVE_BOEHM_GC */
24
25 #include <stdlib.h>
26 #include <time.h>
27 #include <signal.h>
28 #include <errno.h>
29 #include <limits.h>
30 #ifdef HAVE_UNISTD_H
31 #include <unistd.h>     // To test for _POSIX_THREAD_PRIORITY_SCHEDULING
32 #endif
33
34 #include <gcj/cni.h>
35 #include <jvm.h>
36 #include <java/lang/Thread.h>
37 #include <java/lang/System.h>
38 #include <java/lang/Long.h>
39 #include <java/lang/OutOfMemoryError.h>
40 #include <java/lang/InternalError.h>
41
42 // This is used to implement thread startup.
43 struct starter
44 {
45   _Jv_ThreadStartFunc *method;
46   _Jv_Thread_t *data;
47 };
48
49 // This is the key used to map from the POSIX thread value back to the
50 // Java object representing the thread.  The key is global to all
51 // threads, so it is ok to make it a global here.
52 pthread_key_t _Jv_ThreadKey;
53
54 // This is the key used to map from the POSIX thread value back to the
55 // _Jv_Thread_t* representing the thread.
56 pthread_key_t _Jv_ThreadDataKey;
57
58 // We keep a count of all non-daemon threads which are running.  When
59 // this reaches zero, _Jv_ThreadWait returns.
60 static pthread_mutex_t daemon_mutex;
61 static pthread_cond_t daemon_cond;
62 static int non_daemon_count;
63
64 // The signal to use when interrupting a thread.
65 #if defined(LINUX_THREADS) || defined(FREEBSD_THREADS)
66   // LinuxThreads (prior to glibc 2.1) usurps both SIGUSR1 and SIGUSR2.
67   // GC on FreeBSD uses both SIGUSR1 and SIGUSR2.
68 #  define INTR SIGHUP
69 #else /* LINUX_THREADS */
70 #  define INTR SIGUSR2
71 #endif /* LINUX_THREADS */
72
73 //
74 // These are the flags that can appear in _Jv_Thread_t.
75 //
76
77 // Thread started.
78 #define FLAG_START   0x01
79 // Thread is daemon.
80 #define FLAG_DAEMON  0x02
81
82 \f
83
84 int
85 _Jv_MutexLock (_Jv_Mutex_t *mu)
86 {
87   pthread_t self = pthread_self ();
88   if (mu->owner == self)
89     {
90       mu->count++;
91     }
92   else
93     {
94       JvSetThreadState holder (_Jv_ThreadCurrent(), JV_BLOCKED);
95         
96 #     ifdef LOCK_DEBUG
97         int result = pthread_mutex_lock (&mu->mutex);
98         if (0 != result)
99           {
100             fprintf(stderr, "Pthread_mutex_lock returned %d\n", result);
101             for (;;) {}
102           }
103 #     else
104         pthread_mutex_lock (&mu->mutex);
105 #     endif
106       mu->count = 1;
107       mu->owner = self;
108     }
109   return 0;
110 }
111
112 // Wait for the condition variable "CV" to be notified. 
113 // Return values:
114 // 0: the condition was notified, or the timeout expired.
115 // _JV_NOT_OWNER: the thread does not own the mutex "MU".   
116 // _JV_INTERRUPTED: the thread was interrupted. Its interrupted flag is set.   
117 int
118 _Jv_CondWait (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu,
119               jlong millis, jint nanos)
120 {
121   pthread_t self = pthread_self();
122   if (mu->owner != self)
123     return _JV_NOT_OWNER;
124
125   struct timespec ts;
126
127   JvThreadState new_state = JV_WAITING;
128   if (millis > 0 || nanos > 0)
129     {
130       // Calculate the abstime corresponding to the timeout.
131       unsigned long long seconds;
132       unsigned long usec;
133
134       // For better accuracy, should use pthread_condattr_setclock
135       // and clock_gettime.
136 #ifdef HAVE_GETTIMEOFDAY
137       timeval tv;
138       gettimeofday (&tv, NULL);
139       usec = tv.tv_usec;
140       seconds = tv.tv_sec;
141 #else
142       unsigned long long startTime = java::lang::System::currentTimeMillis();
143       seconds = startTime / 1000;
144       /* Assume we're about half-way through this millisecond.  */
145       usec = (startTime % 1000) * 1000 + 500;
146 #endif
147       /* These next two statements cannot overflow.  */
148       usec += nanos / 1000;
149       usec += (millis % 1000) * 1000;
150       /* These two statements could overflow only if tv.tv_sec was
151          insanely large.  */
152       seconds += millis / 1000;
153       seconds += usec / 1000000;
154
155       ts.tv_sec = seconds;
156       if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
157         {
158           // We treat a timeout that won't fit into a struct timespec
159           // as a wait forever.
160           millis = nanos = 0;
161         }
162       else
163         /* This next statement also cannot overflow.  */
164         ts.tv_nsec = (usec % 1000000) * 1000 + (nanos % 1000);
165     }
166
167   _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
168   java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
169
170   pthread_mutex_lock (&current->wait_mutex);
171
172   // Now that we hold the wait mutex, check if this thread has been 
173   // interrupted already.
174   if (current_obj->interrupt_flag)
175     {
176       pthread_mutex_unlock (&current->wait_mutex);
177       return _JV_INTERRUPTED;
178     }
179
180   // Set the thread's state.
181   JvSetThreadState holder (current_obj, new_state);
182
183   // Add this thread to the cv's wait set.
184   current->next = NULL;
185
186   if (cv->first == NULL)
187     cv->first = current;
188   else
189     for (_Jv_Thread_t *t = cv->first;; t = t->next)
190       {
191         if (t->next == NULL)
192           {
193             t->next = current;
194             break;
195           }
196       }
197
198   // Record the current lock depth, so it can be restored when we re-aquire it.
199   int count = mu->count;
200
201   // Release the monitor mutex.
202   mu->count = 0;
203   mu->owner = 0;
204   pthread_mutex_unlock (&mu->mutex);
205   
206   int r = 0;
207   bool done_sleeping = false;
208
209   while (! done_sleeping)
210     {
211       if (millis == 0 && nanos == 0)
212         r = pthread_cond_wait (&current->wait_cond, &current->wait_mutex);
213       else
214         r = pthread_cond_timedwait (&current->wait_cond, &current->wait_mutex, 
215                                     &ts);
216
217       // In older glibc's (prior to 2.1.3), the cond_wait functions may 
218       // spuriously wake up on a signal. Catch that here.
219       if (r != EINTR)
220         done_sleeping = true;
221     }
222   
223   // Check for an interrupt *before* releasing the wait mutex.
224   jboolean interrupted = current_obj->interrupt_flag;
225   
226   pthread_mutex_unlock (&current->wait_mutex);
227
228   //  Reaquire the monitor mutex, and restore the lock count.
229   pthread_mutex_lock (&mu->mutex);
230   mu->owner = self;
231   mu->count = count;
232
233   // If we were interrupted, or if a timeout occurred, remove ourself from
234   // the cv wait list now. (If we were notified normally, notify() will have
235   // already taken care of this)
236   if (r == ETIMEDOUT || interrupted)
237     {
238       _Jv_Thread_t *prev = NULL;
239       for (_Jv_Thread_t *t = cv->first; t != NULL; t = t->next)
240         {
241           if (t == current)
242             {
243               if (prev != NULL)
244                 prev->next = t->next;
245               else
246                 cv->first = t->next;
247               t->next = NULL;
248               break;
249             }
250           prev = t;
251         }
252       if (interrupted)
253         return _JV_INTERRUPTED;
254     }
255   
256   return 0;
257 }
258
259 int
260 _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
261 {
262   if (_Jv_MutexCheckMonitor (mu))
263     return _JV_NOT_OWNER;
264
265   _Jv_Thread_t *target;
266   _Jv_Thread_t *prev = NULL;
267
268   for (target = cv->first; target != NULL; target = target->next)
269     {
270       pthread_mutex_lock (&target->wait_mutex);
271
272       if (target->thread_obj->interrupt_flag)
273         {
274           // Don't notify a thread that has already been interrupted.
275           pthread_mutex_unlock (&target->wait_mutex);
276           prev = target;
277           continue;
278         }
279
280       pthread_cond_signal (&target->wait_cond);
281       pthread_mutex_unlock (&target->wait_mutex);
282
283       // Two concurrent notify() calls must not be delivered to the same 
284       // thread, so remove the target thread from the cv wait list now.
285       if (prev == NULL)
286         cv->first = target->next;
287       else
288         prev->next = target->next;
289                 
290       target->next = NULL;
291       
292       break;
293     }
294
295   return 0;
296 }
297
298 int
299 _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
300 {
301   if (_Jv_MutexCheckMonitor (mu))
302     return _JV_NOT_OWNER;
303
304   _Jv_Thread_t *target;
305   _Jv_Thread_t *prev = NULL;
306
307   for (target = cv->first; target != NULL; target = target->next)
308     {
309       pthread_mutex_lock (&target->wait_mutex);
310       pthread_cond_signal (&target->wait_cond);
311       pthread_mutex_unlock (&target->wait_mutex);
312
313       if (prev != NULL)
314         prev->next = NULL;
315       prev = target;
316     }
317   if (prev != NULL)
318     prev->next = NULL;
319     
320   cv->first = NULL;
321
322   return 0;
323 }
324
325 void
326 _Jv_ThreadInterrupt (_Jv_Thread_t *data)
327 {
328   pthread_mutex_lock (&data->wait_mutex);
329
330   // Set the thread's interrupted flag *after* aquiring its wait_mutex. This
331   // ensures that there are no races with the interrupt flag being set after 
332   // the waiting thread checks it and before pthread_cond_wait is entered.
333   data->thread_obj->interrupt_flag = true;
334
335   // Interrupt blocking system calls using a signal.
336   pthread_kill (data->thread, INTR);
337   
338   pthread_cond_signal (&data->wait_cond);
339   
340   pthread_mutex_unlock (&data->wait_mutex);
341 }
342
343 /**
344  * Releases the block on a thread created by _Jv_ThreadPark().  This
345  * method can also be used to terminate a blockage caused by a prior
346  * call to park.  This operation is unsafe, as the thread must be
347  * guaranteed to be live.
348  *
349  * @param thread the thread to unblock.
350  */
351 void
352 ParkHelper::unpark ()
353 {
354   using namespace ::java::lang;
355   volatile obj_addr_t *ptr = &permit;
356
357   /* If this thread is in state RUNNING, give it a permit and return
358      immediately.  */
359   if (compare_and_swap 
360       (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PERMIT))
361     return;
362
363   /* If this thread is parked, put it into state RUNNING and send it a
364      signal.  */
365   if (compare_and_swap
366       (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING))
367     {
368       pthread_mutex_lock (&mutex);
369       int result = pthread_cond_signal (&cond);
370       pthread_mutex_unlock (&mutex);
371       JvAssert (result == 0);
372     }
373 }
374
375 /**
376  * Sets our state to dead.
377  */
378 void
379 ParkHelper::deactivate ()
380 {
381   permit = ::java::lang::Thread::THREAD_PARK_DEAD;
382 }
383
384 void
385 ParkHelper::init ()
386 {
387   pthread_mutex_init (&mutex, NULL);
388   pthread_cond_init (&cond, NULL);
389   permit = ::java::lang::Thread::THREAD_PARK_RUNNING;
390 }
391
392 /**
393  * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
394  * thread is interrupted or the optional timeout expires.  If an
395  * unpark call has already occurred, this also counts.  A timeout
396  * value of zero is defined as no timeout.  When isAbsolute is true,
397  * the timeout is in milliseconds relative to the epoch.  Otherwise,
398  * the value is the number of nanoseconds which must occur before
399  * timeout.  This call may also return spuriously (i.e.  for no
400  * apparent reason).
401  *
402  * @param isAbsolute true if the timeout is specified in milliseconds from
403  *                   the epoch.
404  * @param time either the number of nanoseconds to wait, or a time in
405  *             milliseconds from the epoch to wait for.
406  */
407 void
408 ParkHelper::park (jboolean isAbsolute, jlong time)
409 {
410   using namespace ::java::lang;
411   volatile obj_addr_t *ptr = &permit;
412
413   /* If we have a permit, return immediately.  */
414   if (compare_and_swap 
415       (ptr, Thread::THREAD_PARK_PERMIT, Thread::THREAD_PARK_RUNNING))
416     return;
417
418   struct timespec ts;
419
420   if (time)
421     {
422       unsigned long long seconds;
423       unsigned long usec;
424
425       if (isAbsolute)
426         {
427           ts.tv_sec = time / 1000;
428           ts.tv_nsec = (time % 1000) * 1000 * 1000;
429         }
430       else
431         {
432           // Calculate the abstime corresponding to the timeout.
433           jlong nanos = time;
434           jlong millis = 0;
435
436           // For better accuracy, should use pthread_condattr_setclock
437           // and clock_gettime.
438 #ifdef HAVE_GETTIMEOFDAY
439           timeval tv;
440           gettimeofday (&tv, NULL);
441           usec = tv.tv_usec;
442           seconds = tv.tv_sec;
443 #else
444           unsigned long long startTime
445             = java::lang::System::currentTimeMillis();
446           seconds = startTime / 1000;
447           /* Assume we're about half-way through this millisecond.  */
448           usec = (startTime % 1000) * 1000 + 500;
449 #endif
450           /* These next two statements cannot overflow.  */
451           usec += nanos / 1000;
452           usec += (millis % 1000) * 1000;
453           /* These two statements could overflow only if tv.tv_sec was
454              insanely large.  */
455           seconds += millis / 1000;
456           seconds += usec / 1000000;
457
458           ts.tv_sec = seconds;
459           if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
460             {
461               // We treat a timeout that won't fit into a struct timespec
462               // as a wait forever.
463               millis = nanos = 0;
464             }
465           else
466             /* This next statement also cannot overflow.  */
467             ts.tv_nsec = (usec % 1000000) * 1000 + (nanos % 1000);
468         }
469     }
470
471   pthread_mutex_lock (&mutex);
472   if (compare_and_swap 
473       (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PARKED))
474     {
475       int result = 0;
476
477       if (! time)
478         result = pthread_cond_wait (&cond, &mutex);
479       else
480         result = pthread_cond_timedwait (&cond, &mutex, &ts);
481
482       JvAssert (result == 0 || result == ETIMEDOUT);
483
484       /* If we were unparked by some other thread, this will already
485          be in state THREAD_PARK_RUNNING.  If we timed out or were
486          interrupted, we have to do it ourself.  */
487       permit = Thread::THREAD_PARK_RUNNING;
488     }
489   pthread_mutex_unlock (&mutex);
490 }
491
492 static void
493 handle_intr (int)
494 {
495   // Do nothing.
496 }
497
498 void
499 _Jv_BlockSigchld()
500 {
501   sigset_t mask;
502   sigemptyset (&mask);
503   sigaddset (&mask, SIGCHLD);
504   int c = pthread_sigmask (SIG_BLOCK, &mask, NULL);
505   if (c != 0)
506     JvFail (strerror (c));
507 }
508
509 void
510 _Jv_UnBlockSigchld()
511 {
512   sigset_t mask;
513   sigemptyset (&mask);
514   sigaddset (&mask, SIGCHLD);
515   int c = pthread_sigmask (SIG_UNBLOCK, &mask, NULL);
516   if (c != 0)
517     JvFail (strerror (c));
518 }
519
520 void
521 _Jv_InitThreads (void)
522 {
523   pthread_key_create (&_Jv_ThreadKey, NULL);
524   pthread_key_create (&_Jv_ThreadDataKey, NULL);
525   pthread_mutex_init (&daemon_mutex, NULL);
526   pthread_cond_init (&daemon_cond, 0);
527   non_daemon_count = 0;
528
529   // Arrange for the interrupt signal to interrupt system calls.
530   struct sigaction act;
531   act.sa_handler = handle_intr;
532   sigemptyset (&act.sa_mask);
533   act.sa_flags = 0;
534   sigaction (INTR, &act, NULL);
535
536   // Block SIGCHLD here to ensure that any non-Java threads inherit the new 
537   // signal mask.
538   _Jv_BlockSigchld();
539
540   // Check/set the thread stack size.
541   size_t min_ss = 32 * 1024;
542   
543   if (sizeof (void *) == 8)
544     // Bigger default on 64-bit systems.
545     min_ss *= 2;
546
547 #ifdef PTHREAD_STACK_MIN
548   if (min_ss < PTHREAD_STACK_MIN)
549     min_ss = PTHREAD_STACK_MIN;
550 #endif
551   
552   if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
553     gcj::stack_size = min_ss;
554 }
555
556 _Jv_Thread_t *
557 _Jv_ThreadInitData (java::lang::Thread *obj)
558 {
559   _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
560   data->flags = 0;
561   data->thread_obj = obj;
562
563   pthread_mutex_init (&data->wait_mutex, NULL);
564   pthread_cond_init (&data->wait_cond, NULL);
565
566   return data;
567 }
568
569 void
570 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
571 {
572   pthread_mutex_destroy (&data->wait_mutex);
573   pthread_cond_destroy (&data->wait_cond);
574   _Jv_Free ((void *)data);
575 }
576
577 void
578 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
579 {
580 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
581   if (data->flags & FLAG_START)
582     {
583       struct sched_param param;
584
585       param.sched_priority = prio;
586       pthread_setschedparam (data->thread, SCHED_OTHER, &param);
587     }
588 #endif
589 }
590
591 void
592 _Jv_ThreadRegister (_Jv_Thread_t *data)
593 {
594   pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
595   pthread_setspecific (_Jv_ThreadDataKey, data);
596
597   // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
598   // is called. Since it may need to be accessed from the new thread, work 
599   // around the potential race here by explicitly setting it again.
600   data->thread = pthread_self ();
601
602 # ifdef SLOW_PTHREAD_SELF
603     // Clear all self cache slots that might be needed by this thread.
604     int dummy;
605     int low_index = SC_INDEX(&dummy) + SC_CLEAR_MIN;
606     int high_index = SC_INDEX(&dummy) + SC_CLEAR_MAX;
607     for (int i = low_index; i <= high_index; ++i) 
608       {
609         int current_index = i;
610         if (current_index < 0)
611           current_index += SELF_CACHE_SIZE;
612         if (current_index >= SELF_CACHE_SIZE)
613           current_index -= SELF_CACHE_SIZE;
614         _Jv_self_cache[current_index].high_sp_bits = BAD_HIGH_SP_VALUE;
615       }
616 # endif
617   // Block SIGCHLD which is used in natPosixProcess.cc.
618   _Jv_BlockSigchld();
619 }
620
621 void
622 _Jv_ThreadUnRegister ()
623 {
624   pthread_setspecific (_Jv_ThreadKey, NULL);
625   pthread_setspecific (_Jv_ThreadDataKey, NULL);
626 }
627
628 // This function is called when a thread is started.  We don't arrange
629 // to call the `run' method directly, because this function must
630 // return a value.
631 static void *
632 really_start (void *x)
633 {
634   struct starter *info = (struct starter *) x;
635
636   _Jv_ThreadRegister (info->data);
637
638   info->method (info->data->thread_obj);
639
640   if (! (info->data->flags & FLAG_DAEMON))
641     {
642       pthread_mutex_lock (&daemon_mutex);
643       --non_daemon_count;
644       if (! non_daemon_count)
645         pthread_cond_signal (&daemon_cond);
646       pthread_mutex_unlock (&daemon_mutex);
647     }
648
649   return NULL;
650 }
651
652 void
653 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
654                  _Jv_ThreadStartFunc *meth)
655 {
656   struct sched_param param;
657   pthread_attr_t attr;
658   struct starter *info;
659
660   if (data->flags & FLAG_START)
661     return;
662   data->flags |= FLAG_START;
663
664   // Block SIGCHLD which is used in natPosixProcess.cc.
665   // The current mask is inherited by the child thread.
666   _Jv_BlockSigchld();
667
668   param.sched_priority = thread->getPriority();
669
670   pthread_attr_init (&attr);
671   pthread_attr_setschedparam (&attr, &param);
672   pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
673   
674   // Set stack size if -Xss option was given.
675   if (gcj::stack_size > 0)
676     {
677       int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
678       if (e != 0)
679         JvFail (strerror (e));
680     }
681
682   info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
683   info->method = meth;
684   info->data = data;
685
686   if (! thread->isDaemon())
687     {
688       pthread_mutex_lock (&daemon_mutex);
689       ++non_daemon_count;
690       pthread_mutex_unlock (&daemon_mutex);
691     }
692   else
693     data->flags |= FLAG_DAEMON;
694   int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
695   
696   pthread_attr_destroy (&attr);
697
698   if (r)
699     {
700       const char* msg = "Cannot create additional threads";
701       throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
702     }
703 }
704
705 void
706 _Jv_ThreadWait (void)
707 {
708   pthread_mutex_lock (&daemon_mutex);
709   if (non_daemon_count)
710     pthread_cond_wait (&daemon_cond, &daemon_mutex);
711   pthread_mutex_unlock (&daemon_mutex);
712 }
713
714 #if defined(SLOW_PTHREAD_SELF)
715
716 #include "sysdep/locks.h"
717
718 // Support for pthread_self() lookup cache.
719 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
720
721 _Jv_ThreadId_t
722 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
723 {
724   pthread_t self = pthread_self();
725   sce -> high_sp_bits = high_sp_bits;
726   write_barrier();
727   sce -> self = self;
728   return self;
729 }
730
731 #endif /* SLOW_PTHREAD_SELF */