2005-12-29 Paul Brook <paul@codesourcery.com>
[official-gcc.git] / libjava / posix-threads.cc
blob042370fc37958c87c1fe26870610204d448da5a2
1 // posix-threads.cc - interface between libjava and POSIX threads.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2004 Free Software Foundation
5 This file is part of libgcj.
7 This software is copyrighted work licensed under the terms of the
8 Libgcj License. Please consult the file "LIBGCJ_LICENSE" for
9 details. */
11 // TO DO:
12 // * Document signal handling limitations
14 #include <config.h>
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 */
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
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>
39 // This is used to implement thread startup.
40 struct starter
42 _Jv_ThreadStartFunc *method;
43 _Jv_Thread_t *data;
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;
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;
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;
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 */
71 // These are the flags that can appear in _Jv_Thread_t.
74 // Thread started.
75 #define FLAG_START 0x01
76 // Thread is daemon.
77 #define FLAG_DAEMON 0x02
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)
90 pthread_t self = pthread_self();
91 if (mu->owner != self)
92 return _JV_NOT_OWNER;
94 struct timespec ts;
96 if (millis > 0 || nanos > 0)
98 // Calculate the abstime corresponding to the timeout.
99 // Everything is in milliseconds.
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.
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;
110 ts.tv_sec = seconds;
111 if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
113 // We treat a timeout that won't fit into a struct timespec
114 // as a wait forever.
115 millis = nanos = 0;
117 else
119 m %= 1000;
120 ts.tv_nsec = m * 1000000 + (unsigned long long)nanos;
124 _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
125 java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
127 pthread_mutex_lock (&current->wait_mutex);
129 // Now that we hold the wait mutex, check if this thread has been
130 // interrupted already.
131 if (current_obj->interrupt_flag)
133 pthread_mutex_unlock (&current->wait_mutex);
134 return _JV_INTERRUPTED;
137 // Add this thread to the cv's wait set.
138 current->next = NULL;
140 if (cv->first == NULL)
141 cv->first = current;
142 else
143 for (_Jv_Thread_t *t = cv->first;; t = t->next)
145 if (t->next == NULL)
147 t->next = current;
148 break;
152 // Record the current lock depth, so it can be restored when we re-aquire it.
153 int count = mu->count;
155 // Release the monitor mutex.
156 mu->count = 0;
157 mu->owner = 0;
158 pthread_mutex_unlock (&mu->mutex);
160 int r = 0;
161 bool done_sleeping = false;
163 while (! done_sleeping)
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);
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;
177 // Check for an interrupt *before* releasing the wait mutex.
178 jboolean interrupted = current_obj->interrupt_flag;
180 pthread_mutex_unlock (&current->wait_mutex);
182 // Reaquire the monitor mutex, and restore the lock count.
183 pthread_mutex_lock (&mu->mutex);
184 mu->owner = self;
185 mu->count = count;
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)
192 _Jv_Thread_t *prev = NULL;
193 for (_Jv_Thread_t *t = cv->first; t != NULL; t = t->next)
195 if (t == current)
197 if (prev != NULL)
198 prev->next = t->next;
199 else
200 cv->first = t->next;
201 t->next = NULL;
202 break;
204 prev = t;
206 if (interrupted)
207 return _JV_INTERRUPTED;
210 return 0;
214 _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
216 if (_Jv_MutexCheckMonitor (mu))
217 return _JV_NOT_OWNER;
219 _Jv_Thread_t *target;
220 _Jv_Thread_t *prev = NULL;
222 for (target = cv->first; target != NULL; target = target->next)
224 pthread_mutex_lock (&target->wait_mutex);
226 if (target->thread_obj->interrupt_flag)
228 // Don't notify a thread that has already been interrupted.
229 pthread_mutex_unlock (&target->wait_mutex);
230 prev = target;
231 continue;
234 pthread_cond_signal (&target->wait_cond);
235 pthread_mutex_unlock (&target->wait_mutex);
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;
244 target->next = NULL;
246 break;
249 return 0;
253 _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
255 if (_Jv_MutexCheckMonitor (mu))
256 return _JV_NOT_OWNER;
258 _Jv_Thread_t *target;
259 _Jv_Thread_t *prev = NULL;
261 for (target = cv->first; target != NULL; target = target->next)
263 pthread_mutex_lock (&target->wait_mutex);
264 pthread_cond_signal (&target->wait_cond);
265 pthread_mutex_unlock (&target->wait_mutex);
267 if (prev != NULL)
268 prev->next = NULL;
269 prev = target;
271 if (prev != NULL)
272 prev->next = NULL;
274 cv->first = NULL;
276 return 0;
279 void
280 _Jv_ThreadInterrupt (_Jv_Thread_t *data)
282 pthread_mutex_lock (&data->wait_mutex);
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;
289 // Interrupt blocking system calls using a signal.
290 pthread_kill (data->thread, INTR);
292 pthread_cond_signal (&data->wait_cond);
294 pthread_mutex_unlock (&data->wait_mutex);
297 static void
298 handle_intr (int)
300 // Do nothing.
303 static void
304 block_sigchld()
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));
314 void
315 _Jv_InitThreads (void)
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;
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);
330 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
331 // signal mask.
332 block_sigchld();
334 // Check/set the thread stack size.
335 size_t min_ss = 32 * 1024;
337 if (sizeof (void *) == 8)
338 // Bigger default on 64-bit systems.
339 min_ss *= 2;
341 if (min_ss < PTHREAD_STACK_MIN)
342 min_ss = PTHREAD_STACK_MIN;
344 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
345 gcj::stack_size = min_ss;
348 _Jv_Thread_t *
349 _Jv_ThreadInitData (java::lang::Thread *obj)
351 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
352 data->flags = 0;
353 data->thread_obj = obj;
355 pthread_mutex_init (&data->wait_mutex, NULL);
356 pthread_cond_init (&data->wait_cond, NULL);
358 return data;
361 void
362 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
364 pthread_mutex_destroy (&data->wait_mutex);
365 pthread_cond_destroy (&data->wait_cond);
366 _Jv_Free ((void *)data);
369 void
370 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
372 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
373 if (data->flags & FLAG_START)
375 struct sched_param param;
377 param.sched_priority = prio;
378 pthread_setschedparam (data->thread, SCHED_OTHER, &param);
380 #endif
383 void
384 _Jv_ThreadRegister (_Jv_Thread_t *data)
386 pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
387 pthread_setspecific (_Jv_ThreadDataKey, data);
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 ();
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)
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;
408 # endif
409 // Block SIGCHLD which is used in natPosixProcess.cc.
410 block_sigchld();
413 void
414 _Jv_ThreadUnRegister ()
416 pthread_setspecific (_Jv_ThreadKey, NULL);
417 pthread_setspecific (_Jv_ThreadDataKey, NULL);
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)
426 struct starter *info = (struct starter *) x;
428 _Jv_ThreadRegister (info->data);
430 info->method (info->data->thread_obj);
432 if (! (info->data->flags & FLAG_DAEMON))
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);
441 return NULL;
444 void
445 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
446 _Jv_ThreadStartFunc *meth)
448 struct sched_param param;
449 pthread_attr_t attr;
450 struct starter *info;
452 if (data->flags & FLAG_START)
453 return;
454 data->flags |= FLAG_START;
456 // Block SIGCHLD which is used in natPosixProcess.cc.
457 // The current mask is inherited by the child thread.
458 block_sigchld();
460 param.sched_priority = thread->getPriority();
462 pthread_attr_init (&attr);
463 pthread_attr_setschedparam (&attr, &param);
464 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
466 // Set stack size if -Xss option was given.
467 if (gcj::stack_size > 0)
469 int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
470 if (e != 0)
471 JvFail (strerror (e));
474 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
475 info->method = meth;
476 info->data = data;
478 if (! thread->isDaemon())
480 pthread_mutex_lock (&daemon_mutex);
481 ++non_daemon_count;
482 pthread_mutex_unlock (&daemon_mutex);
484 else
485 data->flags |= FLAG_DAEMON;
486 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
488 pthread_attr_destroy (&attr);
490 if (r)
492 const char* msg = "Cannot create additional threads";
493 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
497 void
498 _Jv_ThreadWait (void)
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);
506 #if defined(SLOW_PTHREAD_SELF)
508 #include "sysdep/locks.h"
510 // Support for pthread_self() lookup cache.
511 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
513 _Jv_ThreadId_t
514 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
516 pthread_t self = pthread_self();
517 sce -> high_sp_bits = high_sp_bits;
518 write_barrier();
519 sce -> self = self;
520 return self;
523 #endif /* SLOW_PTHREAD_SELF */