OSDN Git Service

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