Mark ChangeLog
[official-gcc.git] / libjava / posix-threads.cc
blob6ef50bda8e4b777393d52cb6382cf9da85f53c9f
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 #ifdef PTHREAD_STACK_MIN
342 if (min_ss < PTHREAD_STACK_MIN)
343 min_ss = PTHREAD_STACK_MIN;
344 #endif
346 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
347 gcj::stack_size = min_ss;
350 _Jv_Thread_t *
351 _Jv_ThreadInitData (java::lang::Thread *obj)
353 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
354 data->flags = 0;
355 data->thread_obj = obj;
357 pthread_mutex_init (&data->wait_mutex, NULL);
358 pthread_cond_init (&data->wait_cond, NULL);
360 return data;
363 void
364 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
366 pthread_mutex_destroy (&data->wait_mutex);
367 pthread_cond_destroy (&data->wait_cond);
368 _Jv_Free ((void *)data);
371 void
372 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
374 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
375 if (data->flags & FLAG_START)
377 struct sched_param param;
379 param.sched_priority = prio;
380 pthread_setschedparam (data->thread, SCHED_OTHER, &param);
382 #endif
385 void
386 _Jv_ThreadRegister (_Jv_Thread_t *data)
388 pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
389 pthread_setspecific (_Jv_ThreadDataKey, data);
391 // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
392 // is called. Since it may need to be accessed from the new thread, work
393 // around the potential race here by explicitly setting it again.
394 data->thread = pthread_self ();
396 # ifdef SLOW_PTHREAD_SELF
397 // Clear all self cache slots that might be needed by this thread.
398 int dummy;
399 int low_index = SC_INDEX(&dummy) + SC_CLEAR_MIN;
400 int high_index = SC_INDEX(&dummy) + SC_CLEAR_MAX;
401 for (int i = low_index; i <= high_index; ++i)
403 int current_index = i;
404 if (current_index < 0)
405 current_index += SELF_CACHE_SIZE;
406 if (current_index >= SELF_CACHE_SIZE)
407 current_index -= SELF_CACHE_SIZE;
408 _Jv_self_cache[current_index].high_sp_bits = BAD_HIGH_SP_VALUE;
410 # endif
411 // Block SIGCHLD which is used in natPosixProcess.cc.
412 block_sigchld();
415 void
416 _Jv_ThreadUnRegister ()
418 pthread_setspecific (_Jv_ThreadKey, NULL);
419 pthread_setspecific (_Jv_ThreadDataKey, NULL);
422 // This function is called when a thread is started. We don't arrange
423 // to call the `run' method directly, because this function must
424 // return a value.
425 static void *
426 really_start (void *x)
428 struct starter *info = (struct starter *) x;
430 _Jv_ThreadRegister (info->data);
432 info->method (info->data->thread_obj);
434 if (! (info->data->flags & FLAG_DAEMON))
436 pthread_mutex_lock (&daemon_mutex);
437 --non_daemon_count;
438 if (! non_daemon_count)
439 pthread_cond_signal (&daemon_cond);
440 pthread_mutex_unlock (&daemon_mutex);
443 return NULL;
446 void
447 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
448 _Jv_ThreadStartFunc *meth)
450 struct sched_param param;
451 pthread_attr_t attr;
452 struct starter *info;
454 if (data->flags & FLAG_START)
455 return;
456 data->flags |= FLAG_START;
458 // Block SIGCHLD which is used in natPosixProcess.cc.
459 // The current mask is inherited by the child thread.
460 block_sigchld();
462 param.sched_priority = thread->getPriority();
464 pthread_attr_init (&attr);
465 pthread_attr_setschedparam (&attr, &param);
466 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
468 // Set stack size if -Xss option was given.
469 if (gcj::stack_size > 0)
471 int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
472 if (e != 0)
473 JvFail (strerror (e));
476 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
477 info->method = meth;
478 info->data = data;
480 if (! thread->isDaemon())
482 pthread_mutex_lock (&daemon_mutex);
483 ++non_daemon_count;
484 pthread_mutex_unlock (&daemon_mutex);
486 else
487 data->flags |= FLAG_DAEMON;
488 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
490 pthread_attr_destroy (&attr);
492 if (r)
494 const char* msg = "Cannot create additional threads";
495 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
499 void
500 _Jv_ThreadWait (void)
502 pthread_mutex_lock (&daemon_mutex);
503 if (non_daemon_count)
504 pthread_cond_wait (&daemon_cond, &daemon_mutex);
505 pthread_mutex_unlock (&daemon_mutex);
508 #if defined(SLOW_PTHREAD_SELF)
510 #include "sysdep/locks.h"
512 // Support for pthread_self() lookup cache.
513 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
515 _Jv_ThreadId_t
516 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
518 pthread_t self = pthread_self();
519 sce -> high_sp_bits = high_sp_bits;
520 write_barrier();
521 sce -> self = self;
522 return self;
525 #endif /* SLOW_PTHREAD_SELF */