OSDN Git Service

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