OSDN Git Service

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