Mark ChangeLog
[official-gcc.git] / libjava / posix-threads.cc
blob125275b97cacad9d72c84bda4e46e208a34b301b
1 // posix-threads.cc - interface between libjava and POSIX threads.
3 /* Copyright (C) 1998, 1999, 2000, 2001, 2004, 2006 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 #include "posix.h"
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 */
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
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>
41 // This is used to implement thread startup.
42 struct starter
44 _Jv_ThreadStartFunc *method;
45 _Jv_Thread_t *data;
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;
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;
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;
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 */
73 // These are the flags that can appear in _Jv_Thread_t.
76 // Thread started.
77 #define FLAG_START 0x01
78 // Thread is daemon.
79 #define FLAG_DAEMON 0x02
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)
92 pthread_t self = pthread_self();
93 if (mu->owner != self)
94 return _JV_NOT_OWNER;
96 struct timespec ts;
98 if (millis > 0 || nanos > 0)
100 // Calculate the abstime corresponding to the timeout.
101 unsigned long long seconds;
102 unsigned long usec;
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;
125 ts.tv_sec = seconds;
126 if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
128 // We treat a timeout that won't fit into a struct timespec
129 // as a wait forever.
130 millis = nanos = 0;
132 else
133 /* This next statement also cannot overflow. */
134 ts.tv_nsec = (usec % 1000000) * 1000 + (nanos % 1000);
137 _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
138 java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
140 pthread_mutex_lock (&current->wait_mutex);
142 // Now that we hold the wait mutex, check if this thread has been
143 // interrupted already.
144 if (current_obj->interrupt_flag)
146 pthread_mutex_unlock (&current->wait_mutex);
147 return _JV_INTERRUPTED;
150 // Add this thread to the cv's wait set.
151 current->next = NULL;
153 if (cv->first == NULL)
154 cv->first = current;
155 else
156 for (_Jv_Thread_t *t = cv->first;; t = t->next)
158 if (t->next == NULL)
160 t->next = current;
161 break;
165 // Record the current lock depth, so it can be restored when we re-aquire it.
166 int count = mu->count;
168 // Release the monitor mutex.
169 mu->count = 0;
170 mu->owner = 0;
171 pthread_mutex_unlock (&mu->mutex);
173 int r = 0;
174 bool done_sleeping = false;
176 while (! done_sleeping)
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);
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;
190 // Check for an interrupt *before* releasing the wait mutex.
191 jboolean interrupted = current_obj->interrupt_flag;
193 pthread_mutex_unlock (&current->wait_mutex);
195 // Reaquire the monitor mutex, and restore the lock count.
196 pthread_mutex_lock (&mu->mutex);
197 mu->owner = self;
198 mu->count = count;
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)
205 _Jv_Thread_t *prev = NULL;
206 for (_Jv_Thread_t *t = cv->first; t != NULL; t = t->next)
208 if (t == current)
210 if (prev != NULL)
211 prev->next = t->next;
212 else
213 cv->first = t->next;
214 t->next = NULL;
215 break;
217 prev = t;
219 if (interrupted)
220 return _JV_INTERRUPTED;
223 return 0;
227 _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
229 if (_Jv_MutexCheckMonitor (mu))
230 return _JV_NOT_OWNER;
232 _Jv_Thread_t *target;
233 _Jv_Thread_t *prev = NULL;
235 for (target = cv->first; target != NULL; target = target->next)
237 pthread_mutex_lock (&target->wait_mutex);
239 if (target->thread_obj->interrupt_flag)
241 // Don't notify a thread that has already been interrupted.
242 pthread_mutex_unlock (&target->wait_mutex);
243 prev = target;
244 continue;
247 pthread_cond_signal (&target->wait_cond);
248 pthread_mutex_unlock (&target->wait_mutex);
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;
257 target->next = NULL;
259 break;
262 return 0;
266 _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
268 if (_Jv_MutexCheckMonitor (mu))
269 return _JV_NOT_OWNER;
271 _Jv_Thread_t *target;
272 _Jv_Thread_t *prev = NULL;
274 for (target = cv->first; target != NULL; target = target->next)
276 pthread_mutex_lock (&target->wait_mutex);
277 pthread_cond_signal (&target->wait_cond);
278 pthread_mutex_unlock (&target->wait_mutex);
280 if (prev != NULL)
281 prev->next = NULL;
282 prev = target;
284 if (prev != NULL)
285 prev->next = NULL;
287 cv->first = NULL;
289 return 0;
292 void
293 _Jv_ThreadInterrupt (_Jv_Thread_t *data)
295 pthread_mutex_lock (&data->wait_mutex);
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;
302 // Interrupt blocking system calls using a signal.
303 pthread_kill (data->thread, INTR);
305 pthread_cond_signal (&data->wait_cond);
307 pthread_mutex_unlock (&data->wait_mutex);
310 static void
311 handle_intr (int)
313 // Do nothing.
316 static void
317 block_sigchld()
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));
327 void
328 _Jv_InitThreads (void)
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;
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);
343 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
344 // signal mask.
345 block_sigchld();
347 // Check/set the thread stack size.
348 size_t min_ss = 32 * 1024;
350 if (sizeof (void *) == 8)
351 // Bigger default on 64-bit systems.
352 min_ss *= 2;
354 #ifdef PTHREAD_STACK_MIN
355 if (min_ss < PTHREAD_STACK_MIN)
356 min_ss = PTHREAD_STACK_MIN;
357 #endif
359 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
360 gcj::stack_size = min_ss;
363 _Jv_Thread_t *
364 _Jv_ThreadInitData (java::lang::Thread *obj)
366 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
367 data->flags = 0;
368 data->thread_obj = obj;
370 pthread_mutex_init (&data->wait_mutex, NULL);
371 pthread_cond_init (&data->wait_cond, NULL);
373 return data;
376 void
377 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
379 pthread_mutex_destroy (&data->wait_mutex);
380 pthread_cond_destroy (&data->wait_cond);
381 _Jv_Free ((void *)data);
384 void
385 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
387 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
388 if (data->flags & FLAG_START)
390 struct sched_param param;
392 param.sched_priority = prio;
393 pthread_setschedparam (data->thread, SCHED_OTHER, &param);
395 #endif
398 void
399 _Jv_ThreadRegister (_Jv_Thread_t *data)
401 pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
402 pthread_setspecific (_Jv_ThreadDataKey, data);
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 ();
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)
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;
423 # endif
424 // Block SIGCHLD which is used in natPosixProcess.cc.
425 block_sigchld();
428 void
429 _Jv_ThreadUnRegister ()
431 pthread_setspecific (_Jv_ThreadKey, NULL);
432 pthread_setspecific (_Jv_ThreadDataKey, NULL);
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)
441 struct starter *info = (struct starter *) x;
443 _Jv_ThreadRegister (info->data);
445 info->method (info->data->thread_obj);
447 if (! (info->data->flags & FLAG_DAEMON))
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);
456 return NULL;
459 void
460 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
461 _Jv_ThreadStartFunc *meth)
463 struct sched_param param;
464 pthread_attr_t attr;
465 struct starter *info;
467 if (data->flags & FLAG_START)
468 return;
469 data->flags |= FLAG_START;
471 // Block SIGCHLD which is used in natPosixProcess.cc.
472 // The current mask is inherited by the child thread.
473 block_sigchld();
475 param.sched_priority = thread->getPriority();
477 pthread_attr_init (&attr);
478 pthread_attr_setschedparam (&attr, &param);
479 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
481 // Set stack size if -Xss option was given.
482 if (gcj::stack_size > 0)
484 int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
485 if (e != 0)
486 JvFail (strerror (e));
489 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
490 info->method = meth;
491 info->data = data;
493 if (! thread->isDaemon())
495 pthread_mutex_lock (&daemon_mutex);
496 ++non_daemon_count;
497 pthread_mutex_unlock (&daemon_mutex);
499 else
500 data->flags |= FLAG_DAEMON;
501 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
503 pthread_attr_destroy (&attr);
505 if (r)
507 const char* msg = "Cannot create additional threads";
508 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
512 void
513 _Jv_ThreadWait (void)
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);
521 #if defined(SLOW_PTHREAD_SELF)
523 #include "sysdep/locks.h"
525 // Support for pthread_self() lookup cache.
526 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
528 _Jv_ThreadId_t
529 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
531 pthread_t self = pthread_self();
532 sce -> high_sp_bits = high_sp_bits;
533 write_barrier();
534 sce -> self = self;
535 return self;
538 #endif /* SLOW_PTHREAD_SELF */