OSDN Git Service

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