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
83 // Wait for the condition variable "CV" to be notified.
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.
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)
98 if (millis > 0 || nanos > 0)
100 // Calculate the abstime corresponding to the timeout.
101 unsigned long long seconds;
104 // For better accuracy, should use pthread_condattr_setclock
105 // and clock_gettime.
106 #ifdef HAVE_GETTIMEOFDAY
108 gettimeofday (&tv, NULL);
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;
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
122 seconds += millis / 1000;
123 seconds += usec / 1000000;
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.
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 (¤t->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 (¤t->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)
156 for (_Jv_Thread_t *t = cv->first;; t = t->next)
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.
171 pthread_mutex_unlock (&mu->mutex);
174 bool done_sleeping = false;
176 while (! done_sleeping)
178 if (millis == 0 && nanos == 0)
179 r = pthread_cond_wait (¤t->wait_cond, ¤t->wait_mutex);
181 r = pthread_cond_timedwait (¤t->wait_cond, ¤t->wait_mutex,
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.
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 (¤t->wait_mutex);
195 // Reaquire the monitor mutex, and restore the lock count.
196 pthread_mutex_lock (&mu->mutex);
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)
211 prev->next = t->next;
220 return _JV_INTERRUPTED;
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);
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.
253 cv->first = target->next;
255 prev->next = target->next;
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);
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);
321 sigaddset (&mask, SIGCHLD);
322 int c = pthread_sigmask (SIG_BLOCK, &mask, NULL);
324 JvFail (strerror (c));
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);
341 sigaction (INTR, &act, NULL);
343 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
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.
354 #ifdef PTHREAD_STACK_MIN
355 if (min_ss < PTHREAD_STACK_MIN)
356 min_ss = PTHREAD_STACK_MIN;
359 if (gcj::stack_size > 0 && gcj::stack_size < min_ss)
360 gcj::stack_size = min_ss;
364 _Jv_ThreadInitData (java::lang::Thread *obj)
366 _Jv_Thread_t *data = (_Jv_Thread_t *) _Jv_Malloc (sizeof (_Jv_Thread_t));
368 data->thread_obj = obj;
370 pthread_mutex_init (&data->wait_mutex, NULL);
371 pthread_cond_init (&data->wait_cond, NULL);
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);
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, ¶m);
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.
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;
424 // Block SIGCHLD which is used in natPosixProcess.cc.
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
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);
451 if (! non_daemon_count)
452 pthread_cond_signal (&daemon_cond);
453 pthread_mutex_unlock (&daemon_mutex);
460 _Jv_ThreadStart (java::lang::Thread *thread, _Jv_Thread_t *data,
461 _Jv_ThreadStartFunc *meth)
463 struct sched_param param;
465 struct starter *info;
467 if (data->flags & FLAG_START)
469 data->flags |= FLAG_START;
471 // Block SIGCHLD which is used in natPosixProcess.cc.
472 // The current mask is inherited by the child thread.
475 param.sched_priority = thread->getPriority();
477 pthread_attr_init (&attr);
478 pthread_attr_setschedparam (&attr, ¶m);
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);
486 JvFail (strerror (e));
489 info = (struct starter *) _Jv_AllocBytes (sizeof (struct starter));
493 if (! thread->isDaemon())
495 pthread_mutex_lock (&daemon_mutex);
497 pthread_mutex_unlock (&daemon_mutex);
500 data->flags |= FLAG_DAEMON;
501 int r = pthread_create (&data->thread, &attr, really_start, (void *) info);
503 pthread_attr_destroy (&attr);
507 const char* msg = "Cannot create additional threads";
508 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg));
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];
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;
538 #endif /* SLOW_PTHREAD_SELF */