OSDN Git Service

2006-01-04 Krister Walfridsson <cato@df.lth.se>
[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 #ifdef PTHREAD_STACK_MIN
342   if (min_ss < PTHREAD_STACK_MIN)
343     min_ss = PTHREAD_STACK_MIN;
344 #endif
345   
346   if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
347     gcj::stack_size = min_ss;
348 }
349
350 _Jv_Thread_t *
351 _Jv_ThreadInitData (java::lang::Thread *obj)
352 {
353   _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
354   data->flags = 0;
355   data->thread_obj = obj;
356
357   pthread_mutex_init (&data->wait_mutex, NULL);
358   pthread_cond_init (&data->wait_cond, NULL);
359
360   return data;
361 }
362
363 void
364 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
365 {
366   pthread_mutex_destroy (&data->wait_mutex);
367   pthread_cond_destroy (&data->wait_cond);
368   _Jv_Free ((void *)data);
369 }
370
371 void
372 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
373 {
374 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
375   if (data->flags & FLAG_START)
376     {
377       struct sched_param param;
378
379       param.sched_priority = prio;
380       pthread_setschedparam (data->thread, SCHED_OTHER, &param);
381     }
382 #endif
383 }
384
385 void
386 _Jv_ThreadRegister (_Jv_Thread_t *data)
387 {
388   pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
389   pthread_setspecific (_Jv_ThreadDataKey, data);
390
391   // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
392   // is called. Since it may need to be accessed from the new thread, work 
393   // around the potential race here by explicitly setting it again.
394   data->thread = pthread_self ();
395
396 # ifdef SLOW_PTHREAD_SELF
397     // Clear all self cache slots that might be needed by this thread.
398     int dummy;
399     int low_index = SC_INDEX(&dummy) + SC_CLEAR_MIN;
400     int high_index = SC_INDEX(&dummy) + SC_CLEAR_MAX;
401     for (int i = low_index; i <= high_index; ++i) 
402       {
403         int current_index = i;
404         if (current_index < 0)
405           current_index += SELF_CACHE_SIZE;
406         if (current_index >= SELF_CACHE_SIZE)
407           current_index -= SELF_CACHE_SIZE;
408         _Jv_self_cache[current_index].high_sp_bits = BAD_HIGH_SP_VALUE;
409       }
410 # endif
411   // Block SIGCHLD which is used in natPosixProcess.cc.
412   block_sigchld();
413 }
414
415 void
416 _Jv_ThreadUnRegister ()
417 {
418   pthread_setspecific (_Jv_ThreadKey, NULL);
419   pthread_setspecific (_Jv_ThreadDataKey, NULL);
420 }
421
422 // This function is called when a thread is started.  We don't arrange
423 // to call the `run' method directly, because this function must
424 // return a value.
425 static void *
426 really_start (void *x)
427 {
428   struct starter *info = (struct starter *) x;
429
430   _Jv_ThreadRegister (info->data);
431
432   info->method (info->data->thread_obj);
433
434   if (! (info->data->flags & FLAG_DAEMON))
435     {
436       pthread_mutex_lock (&daemon_mutex);
437       --non_daemon_count;
438       if (! non_daemon_count)
439         pthread_cond_signal (&daemon_cond);
440       pthread_mutex_unlock (&daemon_mutex);
441     }
442
443   return NULL;
444 }
445
446 void
447 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
448                  _Jv_ThreadStartFunc *meth)
449 {
450   struct sched_param param;
451   pthread_attr_t attr;
452   struct starter *info;
453
454   if (data->flags & FLAG_START)
455     return;
456   data->flags |= FLAG_START;
457
458   // Block SIGCHLD which is used in natPosixProcess.cc.
459   // The current mask is inherited by the child thread.
460   block_sigchld();
461
462   param.sched_priority = thread->getPriority();
463
464   pthread_attr_init (&attr);
465   pthread_attr_setschedparam (&attr, &param);
466   pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
467   
468   // Set stack size if -Xss option was given.
469   if (gcj::stack_size > 0)
470     {
471       int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
472       if (e != 0)
473         JvFail (strerror (e));
474     }
475
476   info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
477   info->method = meth;
478   info->data = data;
479
480   if (! thread->isDaemon())
481     {
482       pthread_mutex_lock (&daemon_mutex);
483       ++non_daemon_count;
484       pthread_mutex_unlock (&daemon_mutex);
485     }
486   else
487     data->flags |= FLAG_DAEMON;
488   int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
489   
490   pthread_attr_destroy (&attr);
491
492   if (r)
493     {
494       const char* msg = "Cannot create additional threads";
495       throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
496     }
497 }
498
499 void
500 _Jv_ThreadWait (void)
501 {
502   pthread_mutex_lock (&daemon_mutex);
503   if (non_daemon_count)
504     pthread_cond_wait (&daemon_cond, &daemon_mutex);
505   pthread_mutex_unlock (&daemon_mutex);
506 }
507
508 #if defined(SLOW_PTHREAD_SELF)
509
510 #include "sysdep/locks.h"
511
512 // Support for pthread_self() lookup cache.
513 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
514
515 _Jv_ThreadId_t
516 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
517 {
518   pthread_t self = pthread_self();
519   sce -> high_sp_bits = high_sp_bits;
520   write_barrier();
521   sce -> self = self;
522   return self;
523 }
524
525 #endif /* SLOW_PTHREAD_SELF */