* ChangeLog: Whitespace fixes.
[official-gcc.git] / libjava / posix-threads.cc
blob6ea724b3be8f51fdc2dd6801ed8f8e19bdf5b2a3
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 int
84 _Jv_MutexLock (_Jv_Mutex_t *mu)
86 pthread_t self = pthread_self ();
87 if (mu->owner == self)
89 mu->count++;
91 else
93 JvSetThreadState holder (_Jv_ThreadCurrent(), JV_BLOCKED);
95 # ifdef LOCK_DEBUG
96 int result = pthread_mutex_lock (&mu->mutex);
97 if (0 != result)
99 fprintf(stderr, "Pthread_mutex_lock returned %d\n", result);
100 for (;;) {}
102 # else
103 pthread_mutex_lock (&mu->mutex);
104 # endif
105 mu->count = 1;
106 mu->owner = self;
108 return 0;
111 // Wait for the condition variable "CV" to be notified.
112 // Return values:
113 // 0: the condition was notified, or the timeout expired.
114 // _JV_NOT_OWNER: the thread does not own the mutex "MU".
115 // _JV_INTERRUPTED: the thread was interrupted. Its interrupted flag is set.
117 _Jv_CondWait (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu,
118 jlong millis, jint nanos)
120 pthread_t self = pthread_self();
121 if (mu->owner != self)
122 return _JV_NOT_OWNER;
124 struct timespec ts;
126 JvThreadState new_state = JV_WAITING;
127 if (millis > 0 || nanos > 0)
129 // Calculate the abstime corresponding to the timeout.
130 unsigned long long seconds;
131 unsigned long usec;
133 // For better accuracy, should use pthread_condattr_setclock
134 // and clock_gettime.
135 #ifdef HAVE_GETTIMEOFDAY
136 timeval tv;
137 gettimeofday (&tv, NULL);
138 usec = tv.tv_usec;
139 seconds = tv.tv_sec;
140 #else
141 unsigned long long startTime = java::lang::System::currentTimeMillis();
142 seconds = startTime / 1000;
143 /* Assume we're about half-way through this millisecond. */
144 usec = (startTime % 1000) * 1000 + 500;
145 #endif
146 /* These next two statements cannot overflow. */
147 usec += nanos / 1000;
148 usec += (millis % 1000) * 1000;
149 /* These two statements could overflow only if tv.tv_sec was
150 insanely large. */
151 seconds += millis / 1000;
152 seconds += usec / 1000000;
154 ts.tv_sec = seconds;
155 if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
157 // We treat a timeout that won't fit into a struct timespec
158 // as a wait forever.
159 millis = nanos = 0;
161 else
162 /* This next statement also cannot overflow. */
163 ts.tv_nsec = (usec % 1000000) * 1000 + (nanos % 1000);
166 _Jv_Thread_t *current = _Jv_ThreadCurrentData ();
167 java::lang::Thread *current_obj = _Jv_ThreadCurrent ();
169 pthread_mutex_lock (&current->wait_mutex);
171 // Now that we hold the wait mutex, check if this thread has been
172 // interrupted already.
173 if (current_obj->interrupt_flag)
175 pthread_mutex_unlock (&current->wait_mutex);
176 return _JV_INTERRUPTED;
179 // Set the thread's state.
180 JvSetThreadState holder (current_obj, new_state);
182 // Add this thread to the cv's wait set.
183 current->next = NULL;
185 if (cv->first == NULL)
186 cv->first = current;
187 else
188 for (_Jv_Thread_t *t = cv->first;; t = t->next)
190 if (t->next == NULL)
192 t->next = current;
193 break;
197 // Record the current lock depth, so it can be restored when we re-aquire it.
198 int count = mu->count;
200 // Release the monitor mutex.
201 mu->count = 0;
202 mu->owner = 0;
203 pthread_mutex_unlock (&mu->mutex);
205 int r = 0;
206 bool done_sleeping = false;
208 while (! done_sleeping)
210 if (millis == 0 && nanos == 0)
211 r = pthread_cond_wait (&current->wait_cond, &current->wait_mutex);
212 else
213 r = pthread_cond_timedwait (&current->wait_cond, &current->wait_mutex,
214 &ts);
216 // In older glibc's (prior to 2.1.3), the cond_wait functions may
217 // spuriously wake up on a signal. Catch that here.
218 if (r != EINTR)
219 done_sleeping = true;
222 // Check for an interrupt *before* releasing the wait mutex.
223 jboolean interrupted = current_obj->interrupt_flag;
225 pthread_mutex_unlock (&current->wait_mutex);
227 // Reaquire the monitor mutex, and restore the lock count.
228 pthread_mutex_lock (&mu->mutex);
229 mu->owner = self;
230 mu->count = count;
232 // If we were interrupted, or if a timeout occurred, remove ourself from
233 // the cv wait list now. (If we were notified normally, notify() will have
234 // already taken care of this)
235 if (r == ETIMEDOUT || interrupted)
237 _Jv_Thread_t *prev = NULL;
238 for (_Jv_Thread_t *t = cv->first; t != NULL; t = t->next)
240 if (t == current)
242 if (prev != NULL)
243 prev->next = t->next;
244 else
245 cv->first = t->next;
246 t->next = NULL;
247 break;
249 prev = t;
251 if (interrupted)
252 return _JV_INTERRUPTED;
255 return 0;
259 _Jv_CondNotify (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
261 if (_Jv_MutexCheckMonitor (mu))
262 return _JV_NOT_OWNER;
264 _Jv_Thread_t *target;
265 _Jv_Thread_t *prev = NULL;
267 for (target = cv->first; target != NULL; target = target->next)
269 pthread_mutex_lock (&target->wait_mutex);
271 if (target->thread_obj->interrupt_flag)
273 // Don't notify a thread that has already been interrupted.
274 pthread_mutex_unlock (&target->wait_mutex);
275 prev = target;
276 continue;
279 pthread_cond_signal (&target->wait_cond);
280 pthread_mutex_unlock (&target->wait_mutex);
282 // Two concurrent notify() calls must not be delivered to the same
283 // thread, so remove the target thread from the cv wait list now.
284 if (prev == NULL)
285 cv->first = target->next;
286 else
287 prev->next = target->next;
289 target->next = NULL;
291 break;
294 return 0;
298 _Jv_CondNotifyAll (_Jv_ConditionVariable_t *cv, _Jv_Mutex_t *mu)
300 if (_Jv_MutexCheckMonitor (mu))
301 return _JV_NOT_OWNER;
303 _Jv_Thread_t *target;
304 _Jv_Thread_t *prev = NULL;
306 for (target = cv->first; target != NULL; target = target->next)
308 pthread_mutex_lock (&target->wait_mutex);
309 pthread_cond_signal (&target->wait_cond);
310 pthread_mutex_unlock (&target->wait_mutex);
312 if (prev != NULL)
313 prev->next = NULL;
314 prev = target;
316 if (prev != NULL)
317 prev->next = NULL;
319 cv->first = NULL;
321 return 0;
324 void
325 _Jv_ThreadInterrupt (_Jv_Thread_t *data)
327 pthread_mutex_lock (&data->wait_mutex);
329 // Set the thread's interrupted flag *after* aquiring its wait_mutex. This
330 // ensures that there are no races with the interrupt flag being set after
331 // the waiting thread checks it and before pthread_cond_wait is entered.
332 data->thread_obj->interrupt_flag = true;
334 // Interrupt blocking system calls using a signal.
335 pthread_kill (data->thread, INTR);
337 pthread_cond_signal (&data->wait_cond);
339 pthread_mutex_unlock (&data->wait_mutex);
343 * Releases the block on a thread created by _Jv_ThreadPark(). This
344 * method can also be used to terminate a blockage caused by a prior
345 * call to park. This operation is unsafe, as the thread must be
346 * guaranteed to be live.
348 * @param thread the thread to unblock.
350 void
351 ParkHelper::unpark ()
353 using namespace ::java::lang;
354 volatile obj_addr_t *ptr = &permit;
356 /* If this thread is in state RUNNING, give it a permit and return
357 immediately. */
358 if (compare_and_swap
359 (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PERMIT))
360 return;
362 /* If this thread is parked, put it into state RUNNING and send it a
363 signal. */
364 if (compare_and_swap
365 (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING))
367 pthread_mutex_lock (&mutex);
368 pthread_cond_signal (&cond);
369 pthread_mutex_unlock (&mutex);
374 * Sets our state to dead.
376 void
377 ParkHelper::deactivate ()
379 permit = ::java::lang::Thread::THREAD_PARK_DEAD;
383 * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
384 * thread is interrupted or the optional timeout expires. If an
385 * unpark call has already occurred, this also counts. A timeout
386 * value of zero is defined as no timeout. When isAbsolute is true,
387 * the timeout is in milliseconds relative to the epoch. Otherwise,
388 * the value is the number of nanoseconds which must occur before
389 * timeout. This call may also return spuriously (i.e. for no
390 * apparent reason).
392 * @param isAbsolute true if the timeout is specified in milliseconds from
393 * the epoch.
394 * @param time either the number of nanoseconds to wait, or a time in
395 * milliseconds from the epoch to wait for.
397 void
398 ParkHelper::park (jboolean isAbsolute, jlong time)
400 using namespace ::java::lang;
401 volatile obj_addr_t *ptr = &permit;
403 /* If we have a permit, return immediately. */
404 if (compare_and_swap
405 (ptr, Thread::THREAD_PARK_PERMIT, Thread::THREAD_PARK_RUNNING))
406 return;
408 struct timespec ts;
409 jlong millis = 0, nanos = 0;
411 if (time)
413 if (isAbsolute)
415 millis = time;
416 nanos = 0;
418 else
420 millis = java::lang::System::currentTimeMillis();
421 nanos = time;
424 if (millis > 0 || nanos > 0)
426 // Calculate the abstime corresponding to the timeout.
427 // Everything is in milliseconds.
429 // We use `unsigned long long' rather than jlong because our
430 // caller may pass up to Long.MAX_VALUE millis. This would
431 // overflow the range of a timespec.
433 unsigned long long m = (unsigned long long)millis;
434 unsigned long long seconds = m / 1000;
436 ts.tv_sec = seconds;
437 if (ts.tv_sec < 0 || (unsigned long long)ts.tv_sec != seconds)
439 // We treat a timeout that won't fit into a struct timespec
440 // as a wait forever.
441 millis = nanos = 0;
443 else
445 m %= 1000;
446 ts.tv_nsec = m * 1000000 + (unsigned long long)nanos;
451 if (compare_and_swap
452 (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PARKED))
454 pthread_mutex_lock (&mutex);
455 if (millis == 0 && nanos == 0)
456 pthread_cond_wait (&cond, &mutex);
457 else
458 pthread_cond_timedwait (&cond, &mutex, &ts);
459 pthread_mutex_unlock (&mutex);
461 /* If we were unparked by some other thread, this will already
462 be in state THREAD_PARK_RUNNING. If we timed out, we have to
463 do it ourself. */
464 compare_and_swap
465 (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING);
469 static void
470 handle_intr (int)
472 // Do nothing.
475 static void
476 block_sigchld()
478 sigset_t mask;
479 sigemptyset (&mask);
480 sigaddset (&mask, SIGCHLD);
481 int c = pthread_sigmask (SIG_BLOCK, &mask, NULL);
482 if (c != 0)
483 JvFail (strerror (c));
486 void
487 _Jv_InitThreads (void)
489 pthread_key_create (&_Jv_ThreadKey, NULL);
490 pthread_key_create (&_Jv_ThreadDataKey, NULL);
491 pthread_mutex_init (&daemon_mutex, NULL);
492 pthread_cond_init (&daemon_cond, 0);
493 non_daemon_count = 0;
495 // Arrange for the interrupt signal to interrupt system calls.
496 struct sigaction act;
497 act.sa_handler = handle_intr;
498 sigemptyset (&act.sa_mask);
499 act.sa_flags = 0;
500 sigaction (INTR, &act, NULL);
502 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
503 // signal mask.
504 block_sigchld();
506 // Check/set the thread stack size.
507 size_t min_ss = 32 * 1024;
509 if (sizeof (void *) == 8)
510 // Bigger default on 64-bit systems.
511 min_ss *= 2;
513 #ifdef PTHREAD_STACK_MIN
514 if (min_ss < PTHREAD_STACK_MIN)
515 min_ss = PTHREAD_STACK_MIN;
516 #endif
518 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
519 gcj::stack_size = min_ss;
522 _Jv_Thread_t *
523 _Jv_ThreadInitData (java::lang::Thread *obj)
525 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
526 data->flags = 0;
527 data->thread_obj = obj;
529 pthread_mutex_init (&data->wait_mutex, NULL);
530 pthread_cond_init (&data->wait_cond, NULL);
532 return data;
535 void
536 _Jv_ThreadDestroyData (_Jv_Thread_t *data)
538 pthread_mutex_destroy (&data->wait_mutex);
539 pthread_cond_destroy (&data->wait_cond);
540 _Jv_Free ((void *)data);
543 void
544 _Jv_ThreadSetPriority (_Jv_Thread_t *data, jint prio)
546 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
547 if (data->flags & FLAG_START)
549 struct sched_param param;
551 param.sched_priority = prio;
552 pthread_setschedparam (data->thread, SCHED_OTHER, &param);
554 #endif
557 void
558 _Jv_ThreadRegister (_Jv_Thread_t *data)
560 pthread_setspecific (_Jv_ThreadKey, data->thread_obj);
561 pthread_setspecific (_Jv_ThreadDataKey, data);
563 // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
564 // is called. Since it may need to be accessed from the new thread, work
565 // around the potential race here by explicitly setting it again.
566 data->thread = pthread_self ();
568 # ifdef SLOW_PTHREAD_SELF
569 // Clear all self cache slots that might be needed by this thread.
570 int dummy;
571 int low_index = SC_INDEX(&dummy) + SC_CLEAR_MIN;
572 int high_index = SC_INDEX(&dummy) + SC_CLEAR_MAX;
573 for (int i = low_index; i <= high_index; ++i)
575 int current_index = i;
576 if (current_index < 0)
577 current_index += SELF_CACHE_SIZE;
578 if (current_index >= SELF_CACHE_SIZE)
579 current_index -= SELF_CACHE_SIZE;
580 _Jv_self_cache[current_index].high_sp_bits = BAD_HIGH_SP_VALUE;
582 # endif
583 // Block SIGCHLD which is used in natPosixProcess.cc.
584 block_sigchld();
587 void
588 _Jv_ThreadUnRegister ()
590 pthread_setspecific (_Jv_ThreadKey, NULL);
591 pthread_setspecific (_Jv_ThreadDataKey, NULL);
594 // This function is called when a thread is started. We don't arrange
595 // to call the `run' method directly, because this function must
596 // return a value.
597 static void *
598 really_start (void *x)
600 struct starter *info = (struct starter *) x;
602 _Jv_ThreadRegister (info->data);
604 info->method (info->data->thread_obj);
606 if (! (info->data->flags & FLAG_DAEMON))
608 pthread_mutex_lock (&daemon_mutex);
609 --non_daemon_count;
610 if (! non_daemon_count)
611 pthread_cond_signal (&daemon_cond);
612 pthread_mutex_unlock (&daemon_mutex);
615 return NULL;
618 void
619 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
620 _Jv_ThreadStartFunc *meth)
622 struct sched_param param;
623 pthread_attr_t attr;
624 struct starter *info;
626 if (data->flags & FLAG_START)
627 return;
628 data->flags |= FLAG_START;
630 // Block SIGCHLD which is used in natPosixProcess.cc.
631 // The current mask is inherited by the child thread.
632 block_sigchld();
634 param.sched_priority = thread->getPriority();
636 pthread_attr_init (&attr);
637 pthread_attr_setschedparam (&attr, &param);
638 pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
640 // Set stack size if -Xss option was given.
641 if (gcj::stack_size > 0)
643 int e = pthread_attr_setstacksize (&attr, gcj::stack_size);
644 if (e != 0)
645 JvFail (strerror (e));
648 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
649 info->method = meth;
650 info->data = data;
652 if (! thread->isDaemon())
654 pthread_mutex_lock (&daemon_mutex);
655 ++non_daemon_count;
656 pthread_mutex_unlock (&daemon_mutex);
658 else
659 data->flags |= FLAG_DAEMON;
660 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
662 pthread_attr_destroy (&attr);
664 if (r)
666 const char* msg = "Cannot create additional threads";
667 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
671 void
672 _Jv_ThreadWait (void)
674 pthread_mutex_lock (&daemon_mutex);
675 if (non_daemon_count)
676 pthread_cond_wait (&daemon_cond, &daemon_mutex);
677 pthread_mutex_unlock (&daemon_mutex);
680 #if defined(SLOW_PTHREAD_SELF)
682 #include "sysdep/locks.h"
684 // Support for pthread_self() lookup cache.
685 volatile self_cache_entry _Jv_self_cache[SELF_CACHE_SIZE];
687 _Jv_ThreadId_t
688 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry *sce, size_t high_sp_bits)
690 pthread_t self = pthread_self();
691 sce -> high_sp_bits = high_sp_bits;
692 write_barrier();
693 sce -> self = self;
694 return self;
697 #endif /* SLOW_PTHREAD_SELF */