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
12 // * Document signal handling limitations
18 // If we're using the Boehm GC, then we need to override some of the
19 // thread primitives. This is fairly gross.
22 #endif /* HAVE_BOEHM_GC */
30 #include <unistd.h> // To test for _POSIX_THREAD_PRIORITY_SCHEDULING
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.
44 _Jv_ThreadStartFunc *method;
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.
68 #else /* LINUX_THREADS */
70 #endif /* LINUX_THREADS */
73 // These are the flags that can appear in _Jv_Thread_t.
77 #define FLAG_START 0x01
79 #define FLAG_DAEMON 0x02
84 _Jv_MutexLock (_Jv_Mutex_t *mu)
86 pthread_t self = pthread_self ();
87 if (mu->owner == self)
93 JvSetThreadState holder (_Jv_ThreadCurrent(), JV_BLOCKED);
96 int result = pthread_mutex_lock (&mu->mutex);
99 fprintf(stderr, "Pthread_mutex_lock returned %d\n", result);
103 pthread_mutex_lock (&mu->mutex);
111 // Wait for the condition variable "CV" to be notified.
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;
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;
133 // For better accuracy, should use pthread_condattr_setclock
134 // and clock_gettime.
135 #ifdef HAVE_GETTIMEOFDAY
137 gettimeofday (&tv, NULL);
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;
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
151 seconds += millis / 1000;
152 seconds += usec / 1000000;
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.
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 (¤t->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 (¤t->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)
188 for (_Jv_Thread_t *t = cv->first;; t = t->next)
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.
203 pthread_mutex_unlock (&mu->mutex);
206 bool done_sleeping = false;
208 while (! done_sleeping)
210 if (millis == 0 && nanos == 0)
211 r = pthread_cond_wait (¤t->wait_cond, ¤t->wait_mutex);
213 r = pthread_cond_timedwait (¤t->wait_cond, ¤t->wait_mutex,
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.
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 (¤t->wait_mutex);
227 // Reaquire the monitor mutex, and restore the lock count.
228 pthread_mutex_lock (&mu->mutex);
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)
243 prev->next = t->next;
252 return _JV_INTERRUPTED;
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);
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.
285 cv->first = target->next;
287 prev->next = target->next;
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);
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.
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
359 (ptr, Thread::THREAD_PARK_RUNNING, Thread::THREAD_PARK_PERMIT))
362 /* If this thread is parked, put it into state RUNNING and send it a
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.
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
392 * @param isAbsolute true if the timeout is specified in milliseconds from
394 * @param time either the number of nanoseconds to wait, or a time in
395 * milliseconds from the epoch to wait for.
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. */
405 (ptr, Thread::THREAD_PARK_PERMIT, Thread::THREAD_PARK_RUNNING))
409 jlong millis = 0, nanos = 0;
420 millis = java::lang::System::currentTimeMillis();
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;
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.
446 ts.tv_nsec = m * 1000000 + (unsigned long long)nanos;
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);
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
465 (ptr, Thread::THREAD_PARK_PARKED, Thread::THREAD_PARK_RUNNING);
480 sigaddset (&mask, SIGCHLD);
481 int c = pthread_sigmask (SIG_BLOCK, &mask, NULL);
483 JvFail (strerror (c));
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);
500 sigaction (INTR, &act, NULL);
502 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
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.
513 #ifdef PTHREAD_STACK_MIN
514 if (min_ss < PTHREAD_STACK_MIN)
515 min_ss = PTHREAD_STACK_MIN;
518 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
519 gcj::stack_size = min_ss;
523 _Jv_ThreadInitData (java::lang::Thread *obj)
525 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
527 data->thread_obj = obj;
529 pthread_mutex_init (&data->wait_mutex, NULL);
530 pthread_cond_init (&data->wait_cond, NULL);
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);
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, ¶m);
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.
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;
583 // Block SIGCHLD which is used in natPosixProcess.cc.
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
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);
610 if (! non_daemon_count)
611 pthread_cond_signal (&daemon_cond);
612 pthread_mutex_unlock (&daemon_mutex);
619 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
620 _Jv_ThreadStartFunc *meth)
622 struct sched_param param;
624 struct starter *info;
626 if (data->flags & FLAG_START)
628 data->flags |= FLAG_START;
630 // Block SIGCHLD which is used in natPosixProcess.cc.
631 // The current mask is inherited by the child thread.
634 param.sched_priority = thread->getPriority();
636 pthread_attr_init (&attr);
637 pthread_attr_setschedparam (&attr, ¶m);
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);
645 JvFail (strerror (e));
648 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
652 if (! thread->isDaemon())
654 pthread_mutex_lock (&daemon_mutex);
656 pthread_mutex_unlock (&daemon_mutex);
659 data->flags |= FLAG_DAEMON;
660 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
662 pthread_attr_destroy (&attr);
666 const char* msg = "Cannot create additional threads";
667 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
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];
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;
697 #endif /* SLOW_PTHREAD_SELF */