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
17 #include "posix-threads.h"
19 // If we're using the Boehm GC, then we need to override some of the
20 // thread primitives. This is fairly gross.
23 #endif /* HAVE_BOEHM_GC */
31 #include <unistd.h> // To test for _POSIX_THREAD_PRIORITY_SCHEDULING
36 #include <java/lang/Thread.h>
37 #include <java/lang/System.h>
38 #include <java/lang/Long.h>
39 #include <java/lang/OutOfMemoryError.h>
40 #include <java/lang/InternalError.h>
42 // This is used to implement thread startup.
45 _Jv_ThreadStartFunc
*method
;
49 // This is the key used to map from the POSIX thread value back to the
50 // Java object representing the thread. The key is global to all
51 // threads, so it is ok to make it a global here.
52 pthread_key_t _Jv_ThreadKey
;
54 // This is the key used to map from the POSIX thread value back to the
55 // _Jv_Thread_t* representing the thread.
56 pthread_key_t _Jv_ThreadDataKey
;
58 // We keep a count of all non-daemon threads which are running. When
59 // this reaches zero, _Jv_ThreadWait returns.
60 static pthread_mutex_t daemon_mutex
;
61 static pthread_cond_t daemon_cond
;
62 static int non_daemon_count
;
64 // The signal to use when interrupting a thread.
65 #if defined(LINUX_THREADS) || defined(FREEBSD_THREADS)
66 // LinuxThreads (prior to glibc 2.1) usurps both SIGUSR1 and SIGUSR2.
67 // GC on FreeBSD uses both SIGUSR1 and SIGUSR2.
69 #else /* LINUX_THREADS */
71 #endif /* LINUX_THREADS */
74 // These are the flags that can appear in _Jv_Thread_t.
78 #define FLAG_START 0x01
80 #define FLAG_DAEMON 0x02
85 _Jv_MutexLock (_Jv_Mutex_t
*mu
)
87 pthread_t self
= pthread_self ();
88 if (mu
->owner
== self
)
94 JvSetThreadState
holder (_Jv_ThreadCurrent(), JV_BLOCKED
);
97 int result
= pthread_mutex_lock (&mu
->mutex
);
100 fprintf(stderr
, "Pthread_mutex_lock returned %d\n", result
);
104 pthread_mutex_lock (&mu
->mutex
);
112 // Wait for the condition variable "CV" to be notified.
114 // 0: the condition was notified, or the timeout expired.
115 // _JV_NOT_OWNER: the thread does not own the mutex "MU".
116 // _JV_INTERRUPTED: the thread was interrupted. Its interrupted flag is set.
118 _Jv_CondWait (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
,
119 jlong millis
, jint nanos
)
121 pthread_t self
= pthread_self();
122 if (mu
->owner
!= self
)
123 return _JV_NOT_OWNER
;
127 JvThreadState new_state
= JV_WAITING
;
128 if (millis
> 0 || nanos
> 0)
130 // Calculate the abstime corresponding to the timeout.
131 unsigned long long seconds
;
134 // For better accuracy, should use pthread_condattr_setclock
135 // and clock_gettime.
136 #ifdef HAVE_GETTIMEOFDAY
138 gettimeofday (&tv
, NULL
);
142 unsigned long long startTime
= java::lang::System::currentTimeMillis();
143 seconds
= startTime
/ 1000;
144 /* Assume we're about half-way through this millisecond. */
145 usec
= (startTime
% 1000) * 1000 + 500;
147 /* These next two statements cannot overflow. */
148 usec
+= nanos
/ 1000;
149 usec
+= (millis
% 1000) * 1000;
150 /* These two statements could overflow only if tv.tv_sec was
152 seconds
+= millis
/ 1000;
153 seconds
+= usec
/ 1000000;
156 if (ts
.tv_sec
< 0 || (unsigned long long)ts
.tv_sec
!= seconds
)
158 // We treat a timeout that won't fit into a struct timespec
159 // as a wait forever.
163 /* This next statement also cannot overflow. */
164 ts
.tv_nsec
= (usec
% 1000000) * 1000 + (nanos
% 1000);
167 _Jv_Thread_t
*current
= _Jv_ThreadCurrentData ();
168 java::lang::Thread
*current_obj
= _Jv_ThreadCurrent ();
170 pthread_mutex_lock (¤t
->wait_mutex
);
172 // Now that we hold the wait mutex, check if this thread has been
173 // interrupted already.
174 if (current_obj
->interrupt_flag
)
176 pthread_mutex_unlock (¤t
->wait_mutex
);
177 return _JV_INTERRUPTED
;
180 // Set the thread's state.
181 JvSetThreadState
holder (current_obj
, new_state
);
183 // Add this thread to the cv's wait set.
184 current
->next
= NULL
;
186 if (cv
->first
== NULL
)
189 for (_Jv_Thread_t
*t
= cv
->first
;; t
= t
->next
)
198 // Record the current lock depth, so it can be restored when we re-aquire it.
199 int count
= mu
->count
;
201 // Release the monitor mutex.
204 pthread_mutex_unlock (&mu
->mutex
);
207 bool done_sleeping
= false;
209 while (! done_sleeping
)
211 if (millis
== 0 && nanos
== 0)
212 r
= pthread_cond_wait (¤t
->wait_cond
, ¤t
->wait_mutex
);
214 r
= pthread_cond_timedwait (¤t
->wait_cond
, ¤t
->wait_mutex
,
217 // In older glibc's (prior to 2.1.3), the cond_wait functions may
218 // spuriously wake up on a signal. Catch that here.
220 done_sleeping
= true;
223 // Check for an interrupt *before* releasing the wait mutex.
224 jboolean interrupted
= current_obj
->interrupt_flag
;
226 pthread_mutex_unlock (¤t
->wait_mutex
);
228 // Reaquire the monitor mutex, and restore the lock count.
229 pthread_mutex_lock (&mu
->mutex
);
233 // If we were interrupted, or if a timeout occurred, remove ourself from
234 // the cv wait list now. (If we were notified normally, notify() will have
235 // already taken care of this)
236 if (r
== ETIMEDOUT
|| interrupted
)
238 _Jv_Thread_t
*prev
= NULL
;
239 for (_Jv_Thread_t
*t
= cv
->first
; t
!= NULL
; t
= t
->next
)
244 prev
->next
= t
->next
;
253 return _JV_INTERRUPTED
;
260 _Jv_CondNotify (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
262 if (_Jv_MutexCheckMonitor (mu
))
263 return _JV_NOT_OWNER
;
265 _Jv_Thread_t
*target
;
266 _Jv_Thread_t
*prev
= NULL
;
268 for (target
= cv
->first
; target
!= NULL
; target
= target
->next
)
270 pthread_mutex_lock (&target
->wait_mutex
);
272 if (target
->thread_obj
->interrupt_flag
)
274 // Don't notify a thread that has already been interrupted.
275 pthread_mutex_unlock (&target
->wait_mutex
);
280 pthread_cond_signal (&target
->wait_cond
);
281 pthread_mutex_unlock (&target
->wait_mutex
);
283 // Two concurrent notify() calls must not be delivered to the same
284 // thread, so remove the target thread from the cv wait list now.
286 cv
->first
= target
->next
;
288 prev
->next
= target
->next
;
299 _Jv_CondNotifyAll (_Jv_ConditionVariable_t
*cv
, _Jv_Mutex_t
*mu
)
301 if (_Jv_MutexCheckMonitor (mu
))
302 return _JV_NOT_OWNER
;
304 _Jv_Thread_t
*target
;
305 _Jv_Thread_t
*prev
= NULL
;
307 for (target
= cv
->first
; target
!= NULL
; target
= target
->next
)
309 pthread_mutex_lock (&target
->wait_mutex
);
310 pthread_cond_signal (&target
->wait_cond
);
311 pthread_mutex_unlock (&target
->wait_mutex
);
326 _Jv_ThreadInterrupt (_Jv_Thread_t
*data
)
328 pthread_mutex_lock (&data
->wait_mutex
);
330 // Set the thread's interrupted flag *after* aquiring its wait_mutex. This
331 // ensures that there are no races with the interrupt flag being set after
332 // the waiting thread checks it and before pthread_cond_wait is entered.
333 data
->thread_obj
->interrupt_flag
= true;
335 // Interrupt blocking system calls using a signal.
336 pthread_kill (data
->thread
, INTR
);
338 pthread_cond_signal (&data
->wait_cond
);
340 pthread_mutex_unlock (&data
->wait_mutex
);
344 * Releases the block on a thread created by _Jv_ThreadPark(). This
345 * method can also be used to terminate a blockage caused by a prior
346 * call to park. This operation is unsafe, as the thread must be
347 * guaranteed to be live.
349 * @param thread the thread to unblock.
352 ParkHelper::unpark ()
354 using namespace ::java::lang
;
355 volatile obj_addr_t
*ptr
= &permit
;
357 /* If this thread is in state RUNNING, give it a permit and return
360 (ptr
, Thread::THREAD_PARK_RUNNING
, Thread::THREAD_PARK_PERMIT
))
363 /* If this thread is parked, put it into state RUNNING and send it a
366 (ptr
, Thread::THREAD_PARK_PARKED
, Thread::THREAD_PARK_RUNNING
))
369 pthread_mutex_lock (&mutex
);
370 result
= pthread_cond_signal (&cond
);
371 pthread_mutex_unlock (&mutex
);
372 JvAssert (result
== 0);
377 * Sets our state to dead.
380 ParkHelper::deactivate ()
382 permit
= ::java::lang::Thread::THREAD_PARK_DEAD
;
388 pthread_mutex_init (&mutex
, NULL
);
389 pthread_cond_init (&cond
, NULL
);
390 permit
= ::java::lang::Thread::THREAD_PARK_RUNNING
;
394 * Blocks the thread until a matching _Jv_ThreadUnpark() occurs, the
395 * thread is interrupted or the optional timeout expires. If an
396 * unpark call has already occurred, this also counts. A timeout
397 * value of zero is defined as no timeout. When isAbsolute is true,
398 * the timeout is in milliseconds relative to the epoch. Otherwise,
399 * the value is the number of nanoseconds which must occur before
400 * timeout. This call may also return spuriously (i.e. for no
403 * @param isAbsolute true if the timeout is specified in milliseconds from
405 * @param time either the number of nanoseconds to wait, or a time in
406 * milliseconds from the epoch to wait for.
409 ParkHelper::park (jboolean isAbsolute
, jlong time
)
411 using namespace ::java::lang
;
412 volatile obj_addr_t
*ptr
= &permit
;
414 /* If we have a permit, return immediately. */
416 (ptr
, Thread::THREAD_PARK_PERMIT
, Thread::THREAD_PARK_RUNNING
))
423 unsigned long long seconds
;
428 ts
.tv_sec
= time
/ 1000;
429 ts
.tv_nsec
= (time
% 1000) * 1000 * 1000;
433 // Calculate the abstime corresponding to the timeout.
437 // For better accuracy, should use pthread_condattr_setclock
438 // and clock_gettime.
439 #ifdef HAVE_GETTIMEOFDAY
441 gettimeofday (&tv
, NULL
);
445 unsigned long long startTime
446 = java::lang::System::currentTimeMillis();
447 seconds
= startTime
/ 1000;
448 /* Assume we're about half-way through this millisecond. */
449 usec
= (startTime
% 1000) * 1000 + 500;
451 /* These next two statements cannot overflow. */
452 usec
+= nanos
/ 1000;
453 usec
+= (millis
% 1000) * 1000;
454 /* These two statements could overflow only if tv.tv_sec was
456 seconds
+= millis
/ 1000;
457 seconds
+= usec
/ 1000000;
460 if (ts
.tv_sec
< 0 || (unsigned long long)ts
.tv_sec
!= seconds
)
462 // We treat a timeout that won't fit into a struct timespec
463 // as a wait forever.
467 /* This next statement also cannot overflow. */
468 ts
.tv_nsec
= (usec
% 1000000) * 1000 + (nanos
% 1000);
472 pthread_mutex_lock (&mutex
);
474 (ptr
, Thread::THREAD_PARK_RUNNING
, Thread::THREAD_PARK_PARKED
))
479 result
= pthread_cond_wait (&cond
, &mutex
);
481 result
= pthread_cond_timedwait (&cond
, &mutex
, &ts
);
483 JvAssert (result
== 0 || result
== ETIMEDOUT
);
485 /* If we were unparked by some other thread, this will already
486 be in state THREAD_PARK_RUNNING. If we timed out or were
487 interrupted, we have to do it ourself. */
488 permit
= Thread::THREAD_PARK_RUNNING
;
490 pthread_mutex_unlock (&mutex
);
504 sigaddset (&mask
, SIGCHLD
);
505 int c
= pthread_sigmask (SIG_BLOCK
, &mask
, NULL
);
507 JvFail (strerror (c
));
515 sigaddset (&mask
, SIGCHLD
);
516 int c
= pthread_sigmask (SIG_UNBLOCK
, &mask
, NULL
);
518 JvFail (strerror (c
));
522 _Jv_InitThreads (void)
524 pthread_key_create (&_Jv_ThreadKey
, NULL
);
525 pthread_key_create (&_Jv_ThreadDataKey
, NULL
);
526 pthread_mutex_init (&daemon_mutex
, NULL
);
527 pthread_cond_init (&daemon_cond
, 0);
528 non_daemon_count
= 0;
530 // Arrange for the interrupt signal to interrupt system calls.
531 struct sigaction act
;
532 act
.sa_handler
= handle_intr
;
533 sigemptyset (&act
.sa_mask
);
535 sigaction (INTR
, &act
, NULL
);
537 // Block SIGCHLD here to ensure that any non-Java threads inherit the new
541 // Check/set the thread stack size.
542 size_t min_ss
= 32 * 1024;
544 if (sizeof (void *) == 8)
545 // Bigger default on 64-bit systems.
548 #ifdef PTHREAD_STACK_MIN
549 if (min_ss
< PTHREAD_STACK_MIN
)
550 min_ss
= PTHREAD_STACK_MIN
;
553 if (gcj::stack_size
> 0 && gcj::stack_size
< min_ss
)
554 gcj::stack_size
= min_ss
;
558 _Jv_ThreadInitData (java::lang::Thread
*obj
)
560 _Jv_Thread_t
*data
= (_Jv_Thread_t
*) _Jv_Malloc (sizeof (_Jv_Thread_t
));
562 data
->thread_obj
= obj
;
564 pthread_mutex_init (&data
->wait_mutex
, NULL
);
565 pthread_cond_init (&data
->wait_cond
, NULL
);
571 _Jv_ThreadDestroyData (_Jv_Thread_t
*data
)
573 pthread_mutex_destroy (&data
->wait_mutex
);
574 pthread_cond_destroy (&data
->wait_cond
);
575 _Jv_Free ((void *)data
);
579 _Jv_ThreadSetPriority (_Jv_Thread_t
*data
, jint prio
)
581 #ifdef _POSIX_THREAD_PRIORITY_SCHEDULING
582 if (data
->flags
& FLAG_START
)
584 struct sched_param param
;
586 param
.sched_priority
= prio
;
587 pthread_setschedparam (data
->thread
, SCHED_OTHER
, ¶m
);
593 _Jv_ThreadRegister (_Jv_Thread_t
*data
)
595 pthread_setspecific (_Jv_ThreadKey
, data
->thread_obj
);
596 pthread_setspecific (_Jv_ThreadDataKey
, data
);
598 // glibc 2.1.3 doesn't set the value of `thread' until after start_routine
599 // is called. Since it may need to be accessed from the new thread, work
600 // around the potential race here by explicitly setting it again.
601 data
->thread
= pthread_self ();
603 # ifdef SLOW_PTHREAD_SELF
604 // Clear all self cache slots that might be needed by this thread.
606 int low_index
= SC_INDEX(&dummy
) + SC_CLEAR_MIN
;
607 int high_index
= SC_INDEX(&dummy
) + SC_CLEAR_MAX
;
608 for (int i
= low_index
; i
<= high_index
; ++i
)
610 int current_index
= i
;
611 if (current_index
< 0)
612 current_index
+= SELF_CACHE_SIZE
;
613 if (current_index
>= SELF_CACHE_SIZE
)
614 current_index
-= SELF_CACHE_SIZE
;
615 _Jv_self_cache
[current_index
].high_sp_bits
= BAD_HIGH_SP_VALUE
;
618 // Block SIGCHLD which is used in natPosixProcess.cc.
623 _Jv_ThreadUnRegister ()
625 pthread_setspecific (_Jv_ThreadKey
, NULL
);
626 pthread_setspecific (_Jv_ThreadDataKey
, NULL
);
629 // This function is called when a thread is started. We don't arrange
630 // to call the `run' method directly, because this function must
633 really_start (void *x
)
635 struct starter
*info
= (struct starter
*) x
;
637 _Jv_ThreadRegister (info
->data
);
639 info
->method (info
->data
->thread_obj
);
641 if (! (info
->data
->flags
& FLAG_DAEMON
))
643 pthread_mutex_lock (&daemon_mutex
);
645 if (! non_daemon_count
)
646 pthread_cond_signal (&daemon_cond
);
647 pthread_mutex_unlock (&daemon_mutex
);
654 _Jv_ThreadStart (java::lang::Thread
*thread
, _Jv_Thread_t
*data
,
655 _Jv_ThreadStartFunc
*meth
)
657 struct sched_param param
;
659 struct starter
*info
;
661 if (data
->flags
& FLAG_START
)
663 data
->flags
|= FLAG_START
;
665 // Block SIGCHLD which is used in natPosixProcess.cc.
666 // The current mask is inherited by the child thread.
669 param
.sched_priority
= thread
->getPriority();
671 pthread_attr_init (&attr
);
672 pthread_attr_setschedparam (&attr
, ¶m
);
673 pthread_attr_setdetachstate (&attr
, PTHREAD_CREATE_DETACHED
);
675 // Set stack size if -Xss option was given.
676 if (gcj::stack_size
> 0)
678 int e
= pthread_attr_setstacksize (&attr
, gcj::stack_size
);
680 JvFail (strerror (e
));
683 info
= (struct starter
*) _Jv_AllocBytes (sizeof (struct starter
));
687 if (! thread
->isDaemon())
689 pthread_mutex_lock (&daemon_mutex
);
691 pthread_mutex_unlock (&daemon_mutex
);
694 data
->flags
|= FLAG_DAEMON
;
695 int r
= pthread_create (&data
->thread
, &attr
, really_start
, (void *) info
);
697 pthread_attr_destroy (&attr
);
701 const char* msg
= "Cannot create additional threads";
702 throw new java::lang::OutOfMemoryError (JvNewStringUTF (msg
));
707 _Jv_ThreadWait (void)
709 pthread_mutex_lock (&daemon_mutex
);
710 if (non_daemon_count
)
711 pthread_cond_wait (&daemon_cond
, &daemon_mutex
);
712 pthread_mutex_unlock (&daemon_mutex
);
715 #if defined(SLOW_PTHREAD_SELF)
717 #include "sysdep/locks.h"
719 // Support for pthread_self() lookup cache.
720 volatile self_cache_entry _Jv_self_cache
[SELF_CACHE_SIZE
];
723 _Jv_ThreadSelf_out_of_line(volatile self_cache_entry
*sce
, size_t high_sp_bits
)
725 pthread_t self
= pthread_self();
726 sce
-> high_sp_bits
= high_sp_bits
;
732 #endif /* SLOW_PTHREAD_SELF */