OSDN Git Service

* cfgcleanup.c (try_crossjump_to_edge): Always split SRC2 if it
[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  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 // If we're using the Boehm GC, then we need to override some of the
17 // thread primitives.  This is fairly gross.
18 #ifdef HAVE_BOEHM_GC
19 #include <gc.h>
20 #endif /* HAVE_BOEHM_GC */
21
22 #include <stdlib.h>
23 #include <time.h>
24 #include <signal.h>
25 #include <errno.h>
26 #include <limits.h>
27 #ifdef HAVE_UNISTD_H
28 #include <unistd.h>     // To test for _POSIX_THREAD_PRIORITY_SCHEDULING
29 #endif
30
31 #include <gcj/cni.h>
32 #include <jvm.h>
33 #include <java/lang/Thread.h>
34 #include <java/lang/System.h>
35 #include <java/lang/Long.h>
36 #include <java/lang/OutOfMemoryError.h>
37 #include <java/lang/InternalError.h>
38
39 // This is used to implement thread startup.
40 struct starter
41 {
42   _Jv_ThreadStartFunc *method;
43   _Jv_Thread_t *data;
44 };
45
46 // This is the key used to map from the POSIX thread value back to the
47 // Java object representing the thread.  The key is global to all
48 // threads, so it is ok to make it a global here.
49 pthread_key_t _Jv_ThreadKey;
50
51 // This is the key used to map from the POSIX thread value back to the
52 // _Jv_Thread_t* representing the thread.
53 pthread_key_t _Jv_ThreadDataKey;
54
55 // We keep a count of all non-daemon threads which are running.  When
56 // this reaches zero, _Jv_ThreadWait returns.
57 static pthread_mutex_t daemon_mutex;
58 static pthread_cond_t daemon_cond;
59 static int non_daemon_count;
60
61 // The signal to use when interrupting a thread.
62 #if defined(LINUX_THREADS) || defined(FREEBSD_THREADS)
63   // LinuxThreads (prior to glibc 2.1) usurps both SIGUSR1 and SIGUSR2.
64   // GC on FreeBSD uses both SIGUSR1 and SIGUSR2.
65 #  define INTR SIGHUP
66 #else /* LINUX_THREADS */
67 #  define INTR SIGUSR2
68 #endif /* LINUX_THREADS */
69
70 //
71 // These are the flags that can appear in _Jv_Thread_t.
72 //
73
74 // Thread started.
75 #define FLAG_START   0x01
76 // Thread is daemon.
77 #define FLAG_DAEMON  0x02
78
79 \f
80
81 // Wait for the condition variable "CV" to be notified. 
82 // Return values:
83 // 0: the condition was notified, or the timeout expired.
84 // _JV_NOT_OWNER: the thread does not own the mutex "MU".   
85 // _JV_INTERRUPTED: the thread was interrupted. Its interrupted flag is set.   
86 int
87 _Jv_CondWait (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu,
88               jlong millis, jint nanos)
89 {
90   pthread_t self = pthread_self();
91   if (mu->owner != self)
92     return _JV_NOT_OWNER;
93
94   struct timespec ts;
95
96   if (millis > 0 || nanos > 0)
97     {
98       // Calculate the abstime corresponding to the timeout.
99       // Everything is in milliseconds.
100       //
101       // We use `unsigned long long' rather than jlong because our
102       // caller may pass up to Long.MAX_VALUE millis.  This would
103       // overflow the range of a jlong when added to the current time.
104       
105       unsigned long long startTime 
106         = (unsigned long long)java::lang::System::currentTimeMillis();
107       unsigned long long m = (unsigned long long)millis + startTime;
108       unsigned long long seconds = m / 1000; 
109
110       ts.tv_sec = seconds;
111       if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
112         {
113           // We treat a timeout that won't fit into a struct timespec
114           // as a wait forever.
115           millis = nanos = 0;
116         }
117       else
118         {
119           m %= 1000;
120           ts.tv_nsec = m * 1000000 + (unsigned long long)nanos;
121         }
122     }
123
124   _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
125   java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
126
127   pthread_mutex_lock (&current->wait_mutex);
128
129   // Now that we hold the wait mutex, check if this thread has been 
130   // interrupted already.
131   if (current_obj->interrupt_flag)
132     {
133       pthread_mutex_unlock (&current->wait_mutex);
134       return _JV_INTERRUPTED;
135     }
136
137   // Add this thread to the cv's wait set.
138   current->next = NULL;
139
140   if (cv->first == NULL)
141     cv->first = current;
142   else
143     for (_Jv_Thread_t *t = cv->first;; t = t->next)
144       {
145         if (t->next == NULL)
146           {
147             t->next = current;
148             break;
149           }
150       }
151
152   // Record the current lock depth, so it can be restored when we re-aquire it.
153   int count = mu->count;
154
155   // Release the monitor mutex.
156   mu->count = 0;
157   mu->owner = 0;
158   pthread_mutex_unlock (&mu->mutex);
159   
160   int r = 0;
161   bool done_sleeping = false;
162
163   while (! done_sleeping)
164     {
165       if (millis == 0 && nanos == 0)
166         r = pthread_cond_wait (&current->wait_cond, &current->wait_mutex);
167       else
168         r = pthread_cond_timedwait (&current->wait_cond, &current->wait_mutex, 
169                                     &ts);
170
171       // In older glibc's (prior to 2.1.3), the cond_wait functions may 
172       // spuriously wake up on a signal. Catch that here.
173       if (r != EINTR)
174         done_sleeping = true;
175     }
176   
177   // Check for an interrupt *before* releasing the wait mutex.
178   jboolean interrupted = current_obj->interrupt_flag;
179   
180   pthread_mutex_unlock (&current->wait_mutex);
181
182   //  Reaquire the monitor mutex, and restore the lock count.
183   pthread_mutex_lock (&mu->mutex);
184   mu->owner = self;
185   mu->count = count;
186
187   // If we were interrupted, or if a timeout occurred, remove ourself from
188   // the cv wait list now. (If we were notified normally, notify() will have
189   // already taken care of this)
190   if (r == ETIMEDOUT || interrupted)
191     {
192       _Jv_Thread_t *prev = NULL;
193       for (_Jv_Thread_t *t = cv->first; t != NULL; t = t->next)
194         {
195           if (t == current)
196             {
197               if (prev != NULL)
198                 prev->next = t->next;
199               else
200                 cv->first = t->next;
201               t->next = NULL;
202               break;
203             }
204           prev = t;
205         }
206       if (interrupted)
207         return _JV_INTERRUPTED;
208     }
209   
210   return 0;
211 }
212
213 int
214 _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
215 {
216   if (_Jv_MutexCheckMonitor (mu))
217     return _JV_NOT_OWNER;
218
219   _Jv_Thread_t *target;
220   _Jv_Thread_t *prev = NULL;
221
222   for (target = cv->first; target != NULL; target = target->next)
223     {
224       pthread_mutex_lock (&target->wait_mutex);
225
226       if (target->thread_obj->interrupt_flag)
227         {
228           // Don't notify a thread that has already been interrupted.
229           pthread_mutex_unlock (&target->wait_mutex);
230           prev = target;
231           continue;
232         }
233
234       pthread_cond_signal (&target->wait_cond);
235       pthread_mutex_unlock (&target->wait_mutex);
236
237       // Two concurrent notify() calls must not be delivered to the same 
238       // thread, so remove the target thread from the cv wait list now.
239       if (prev == NULL)
240         cv->first = target->next;
241       else
242         prev->next = target->next;
243                 
244       target->next = NULL;
245       
246       break;
247     }
248
249   return 0;
250 }
251
252 int
253 _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
254 {
255   if (_Jv_MutexCheckMonitor (mu))
256     return _JV_NOT_OWNER;
257
258   _Jv_Thread_t *target;
259   _Jv_Thread_t *prev = NULL;
260
261   for (target = cv->first; target != NULL; target = target->next)
262     {
263       pthread_mutex_lock (&target->wait_mutex);
264       pthread_cond_signal (&target->wait_cond);
265       pthread_mutex_unlock (&target->wait_mutex);
266
267       if (prev != NULL)
268         prev->next = NULL;
269       prev = target;
270     }
271   if (prev != NULL)
272     prev->next = NULL;
273     
274   cv->first = NULL;
275
276   return 0;
277 }
278
279 void
280 _Jv_ThreadInterrupt (_Jv_Thread_t *data)
281 {
282   pthread_mutex_lock (&data->wait_mutex);
283
284   // Set the thread's interrupted flag *after* aquiring its wait_mutex. This
285   // ensures that there are no races with the interrupt flag being set after 
286   // the waiting thread checks it and before pthread_cond_wait is entered.
287   data->thread_obj->interrupt_flag = true;
288
289   // Interrupt blocking system calls using a signal.
290   pthread_kill (data->thread, INTR);
291   
292   pthread_cond_signal (&data->wait_cond);
293   
294   pthread_mutex_unlock (&data->wait_mutex);
295 }
296
297 static void
298 handle_intr (int)
299 {
300   // Do nothing.
301 }
302
303 static void
304 block_sigchld()
305 {
306   sigset_t mask;
307   sigemptyset (&mask);
308   sigaddset (&mask, SIGCHLD);
309   int c = pthread_sigmask (SIG_BLOCK, &mask, NULL);
310   if (c != 0)
311     JvFail (strerror (c));
312 }
313
314 void
315 _Jv_InitThreads (void)
316 {
317   pthread_key_create (&_Jv_ThreadKey, NULL);
318   pthread_key_create (&_Jv_ThreadDataKey, NULL);
319   pthread_mutex_init (&daemon_mutex, NULL);
320   pthread_cond_init (&daemon_cond, 0);
321   non_daemon_count = 0;
322
323   // Arrange for the interrupt signal to interrupt system calls.
324   struct sigaction act;
325   act.sa_handler = handle_intr;
326   sigemptyset (&act.sa_mask);
327   act.sa_flags = 0;
328   sigaction (INTR, &act, NULL);
329
330   // Block SIGCHLD here to ensure that any non-Java threads inherit the new 
331   // signal mask.
332   block_sigchld();
333
334   // Check/set the thread stack size.
335   size_t min_ss = 32 * 1024;
336   
337   if (sizeof (void *) == 8)
338     // Bigger default on 64-bit systems.
339     min_ss *= 2;
340
341   if (min_ss < PTHREAD_STACK_MIN)
342     min_ss = PTHREAD_STACK_MIN;
343   
344   if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
345     gcj::stack_size = min_ss;
346 }
347
348 _Jv_Thread_t *
349 _Jv_ThreadInitData (java::lang::Thread *obj)
350 {
351   _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
352   data->flags = 0;
353   data->thread_obj = obj;
354
355   pthread_mutex_init (&data->wait_mutex, NULL);
356   pthread_cond_init (&data->wait_cond, NULL);
357
358   return data;
359 }
360
361 void
362 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
363 {
364   pthread_mutex_destroy (&data->wait_mutex);
365   pthread_cond_destroy (&data->wait_cond);
366   _Jv_Free ((void *)data);
367 }
368
369 void
370 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
371 {
372 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
373   if (data->flags & FLAG_START)
374     {
375       struct sched_param param;
376
377       param.sched_priority = prio;
378       pthread_setschedparam (data->thread, SCHED_OTHER, &param);
379     }
380 #endif
381 }
382
383 void
384 _Jv_ThreadRegister (_Jv_Thread_t *data)
385 {
386   pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
387   pthread_setspecific (_Jv_ThreadDataKey, data);
388
389   // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
390   // is called. Since it may need to be accessed from the new thread, work 
391   // around the potential race here by explicitly setting it again.
392   data->thread = pthread_self ();
393
394 # ifdef SLOW_PTHREAD_SELF
395     // Clear all self cache slots that might be needed by this thread.
396     int dummy;
397     int low_index = SC_INDEX(&dummy) + SC_CLEAR_MIN;
398     int high_index = SC_INDEX(&dummy) + SC_CLEAR_MAX;
399     for (int i = low_index; i <= high_index; ++i) 
400       {
401         int current_index = i;
402         if (current_index < 0)
403           current_index += SELF_CACHE_SIZE;
404         if (current_index >= SELF_CACHE_SIZE)
405           current_index -= SELF_CACHE_SIZE;
406         _Jv_self_cache[current_index].high_sp_bits = BAD_HIGH_SP_VALUE;
407       }
408 # endif
409   // Block SIGCHLD which is used in natPosixProcess.cc.
410   block_sigchld();
411 }
412
413 void
414 _Jv_ThreadUnRegister ()
415 {
416   pthread_setspecific (_Jv_ThreadKey, NULL);
417   pthread_setspecific (_Jv_ThreadDataKey, NULL);
418 }
419
420 // This function is called when a thread is started.  We don't arrange
421 // to call the `run' method directly, because this function must
422 // return a value.
423 static void *
424 really_start (void *x)
425 {
426   struct starter *info = (struct starter *) x;
427
428   _Jv_ThreadRegister (info->data);
429
430   info->method (info->data->thread_obj);
431
432   if (! (info->data->flags & FLAG_DAEMON))
433     {
434       pthread_mutex_lock (&daemon_mutex);
435       --non_daemon_count;
436       if (! non_daemon_count)
437         pthread_cond_signal (&daemon_cond);
438       pthread_mutex_unlock (&daemon_mutex);
439     }
440
441   return NULL;
442 }
443
444 void
445 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
446                  _Jv_ThreadStartFunc *meth)
447 {
448   struct sched_param param;
449   pthread_attr_t attr;
450   struct starter *info;
451
452   if (data->flags & FLAG_START)
453     return;
454   data->flags |= FLAG_START;
455
456   // Block SIGCHLD which is used in natPosixProcess.cc.
457   // The current mask is inherited by the child thread.
458   block_sigchld();
459
460   param.sched_priority = thread->getPriority();
461
462   pthread_attr_init (&attr);
463   pthread_attr_setschedparam (&attr, &param);
464   pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
465   
466   // Set stack size if -Xss option was given.
467   if (gcj::stack_size > 0)
468     {
469       int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
470       if (e != 0)
471         JvFail (strerror (e));
472     }
473
474   info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
475   info->method = meth;
476   info->data = data;
477
478   if (! thread->isDaemon())
479     {
480       pthread_mutex_lock (&daemon_mutex);
481       ++non_daemon_count;
482       pthread_mutex_unlock (&daemon_mutex);
483     }
484   else
485     data->flags |= FLAG_DAEMON;
486   int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
487   
488   pthread_attr_destroy (&attr);
489
490   if (r)
491     {
492       const char* msg = "Cannot create additional threads";
493       throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
494     }
495 }
496
497 void
498 _Jv_ThreadWait (void)
499 {
500   pthread_mutex_lock (&daemon_mutex);
501   if (non_daemon_count)
502     pthread_cond_wait (&daemon_cond, &daemon_mutex);
503   pthread_mutex_unlock (&daemon_mutex);
504 }
505
506 #if defined(SLOW_PTHREAD_SELF)
507
508 #include "sysdep/locks.h"
509
510 // Support for pthread_self() lookup cache.
511 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
512
513 _Jv_ThreadId_t
514 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
515 {
516   pthread_t self = pthread_self();
517   sce -> high_sp_bits = high_sp_bits;
518   write_barrier();
519   sce -> self = self;
520   return self;
521 }
522
523 #endif /* SLOW_PTHREAD_SELF */