boehm-gc: revert all CACAO-specific modifications; this is now an exact copy of the...
[cacao.git] / src / mm / boehm-gc / pthread_support.c
1 /* 
2  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
3  * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
4  * Copyright (c) 1998 by Fergus Henderson.  All rights reserved.
5  * Copyright (c) 2000-2005 by Hewlett-Packard Company.  All rights reserved.
6  *
7  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
9  *
10  * Permission is hereby granted to use or copy this program
11  * for any purpose,  provided the above notices are retained on all copies.
12  * Permission to modify the code and to distribute modified code is granted,
13  * provided the above notices are retained, and a notice that the code was
14  * modified is included with the above copyright notice.
15  */
16 /*
17  * Support code originally for LinuxThreads, the clone()-based kernel
18  * thread package for Linux which is included in libc6.
19  *
20  * This code no doubt makes some assumptions beyond what is
21  * guaranteed by the pthread standard, though it now does
22  * very little of that.  It now also supports NPTL, and many
23  * other Posix thread implementations.  We are trying to merge
24  * all flavors of pthread support code into this file.
25  */
26  /* DG/UX ix86 support <takis@xfree86.org> */
27 /*
28  * Linux_threads.c now also includes some code to support HPUX and
29  * OSF1 (Compaq Tru64 Unix, really).  The OSF1 support is based on Eric Benson's
30  * patch.
31  *
32  * Eric also suggested an alternate basis for a lock implementation in
33  * his code:
34  * + #elif defined(OSF1)
35  * +    unsigned long GC_allocate_lock = 0;
36  * +    msemaphore GC_allocate_semaphore;
37  * + #  define GC_TRY_LOCK() \
38  * +    ((msem_lock(&GC_allocate_semaphore, MSEM_IF_NOWAIT) == 0) \
39  * +     ? (GC_allocate_lock = 1) \
40  * +     : 0)
41  * + #  define GC_LOCK_TAKEN GC_allocate_lock
42  */
43
44 /*#define DEBUG_THREADS 1*/
45
46 # include "private/pthread_support.h"
47
48 # if defined(GC_PTHREADS) && !defined(GC_WIN32_THREADS)
49
50 # if defined(GC_DGUX386_THREADS) && !defined(_POSIX4A_DRAFT10_SOURCE)
51 #   define _POSIX4A_DRAFT10_SOURCE 1
52 # endif
53
54 # if defined(GC_DGUX386_THREADS) && !defined(_USING_POSIX4A_DRAFT10)
55 #   define _USING_POSIX4A_DRAFT10 1
56 # endif
57
58 # include <stdlib.h>
59 # include <pthread.h>
60 # include <sched.h>
61 # include <time.h>
62 # include <errno.h>
63 # include <unistd.h>
64 # include <sys/mman.h>
65 # include <sys/time.h>
66 # include <sys/types.h>
67 # include <sys/stat.h>
68 # include <fcntl.h>
69 # include <signal.h>
70
71 # include "gc_inline.h"
72
73 #if defined(GC_DARWIN_THREADS)
74 # include "private/darwin_semaphore.h"
75 #else
76 # include <semaphore.h>
77 #endif /* !GC_DARWIN_THREADS */
78
79 #if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
80 # include <sys/sysctl.h>
81 #endif /* GC_DARWIN_THREADS */
82
83 #if defined(GC_NETBSD_THREADS)
84 # include <sys/param.h>
85 # include <sys/sysctl.h>
86 #endif        /* GC_NETBSD_THREADS */
87
88 /* Allocator lock definitions.          */
89 #if !defined(USE_SPIN_LOCK)
90   pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER;
91 #endif
92 unsigned long GC_lock_holder = NO_THREAD;
93                 /* Used only for assertions, and to prevent      */
94                 /* recursive reentry in the system call wrapper. */
95
96 #if defined(GC_DGUX386_THREADS)
97 # include <sys/dg_sys_info.h>
98 # include <sys/_int_psem.h>
99   /* sem_t is an uint in DG/UX */
100   typedef unsigned int  sem_t;
101 #endif /* GC_DGUX386_THREADS */
102
103 #ifndef __GNUC__
104 #   define __inline__
105 #endif
106
107 /* Undefine macros used to redirect pthread primitives. */
108 # undef pthread_create
109 # if !defined(GC_DARWIN_THREADS)
110 #   undef pthread_sigmask
111 # endif
112 # undef pthread_join
113 # undef pthread_detach
114 # if defined(GC_OSF1_THREADS) && defined(_PTHREAD_USE_MANGLED_NAMES_) \
115      && !defined(_PTHREAD_USE_PTDNAM_)
116   /* Restore the original mangled names on Tru64 UNIX.  */
117 #   define pthread_create __pthread_create
118 #   define pthread_join __pthread_join
119 #   define pthread_detach __pthread_detach
120 # endif
121
122 #ifdef GC_USE_LD_WRAP
123 #   define WRAP_FUNC(f) __wrap_##f
124 #   define REAL_FUNC(f) __real_##f
125 #else
126 #   ifdef GC_USE_DLOPEN_WRAP
127 #     include <dlfcn.h>
128 #     define WRAP_FUNC(f) f
129 #     define REAL_FUNC(f) GC_real_##f
130       /* We define both GC_f and plain f to be the wrapped function.    */
131       /* In that way plain calls work, as do calls from files that      */
132       /* included gc.h, wich redefined f to GC_f.                       */
133       /* FIXME: Needs work for DARWIN and True64 (OSF1) */
134       typedef int (* GC_pthread_create_t)(pthread_t *, const pthread_attr_t *,
135                                           void * (*)(void *), void *);
136       static GC_pthread_create_t GC_real_pthread_create;
137       typedef int (* GC_pthread_sigmask_t)(int, const sigset_t *, sigset_t *);
138       static GC_pthread_sigmask_t GC_real_pthread_sigmask;
139       typedef int (* GC_pthread_join_t)(pthread_t, void **);
140       static GC_pthread_join_t GC_real_pthread_join;
141       typedef int (* GC_pthread_detach_t)(pthread_t);
142       static GC_pthread_detach_t GC_real_pthread_detach;
143 #   else
144 #     define WRAP_FUNC(f) GC_##f
145 #     if !defined(GC_DGUX386_THREADS)
146 #       define REAL_FUNC(f) f
147 #     else /* GC_DGUX386_THREADS */
148 #       define REAL_FUNC(f) __d10_##f
149 #     endif /* GC_DGUX386_THREADS */
150 #   endif
151 #endif
152
153 #if defined(GC_USE_DL_WRAP) || defined(GC_USE_DLOPEN_WRAP)
154 /* Define GC_ functions as aliases for the plain ones, which will       */
155 /* be intercepted.  This allows files which include gc.h, and hence     */
156 /* generate references to the GC_ symbols, to see the right symbols.    */
157       int GC_pthread_create(pthread_t * t, const pthread_attr_t * a,
158                          void * (* fn)(void *), void * arg) {
159           return pthread_create(t, a, fn, arg);
160       }
161       int GC_pthread_sigmask(int how, const sigset_t *mask, sigset_t *old) {
162           return pthread_sigmask(how, mask, old);
163       }
164       int GC_pthread_join(pthread_t t, void **res) {
165           return pthread_join(t, res);
166       }
167       int GC_pthread_detach(pthread_t t) {
168           return pthread_detach(t);
169       }
170 #endif /* Linker-based interception. */
171
172 #ifdef GC_USE_DLOPEN_WRAP
173   static GC_bool GC_syms_initialized = FALSE;
174
175   STATIC void GC_init_real_syms(void)
176   {
177     void *dl_handle;
178 #   define LIBPTHREAD_NAME "libpthread.so.0"
179 #   define LIBPTHREAD_NAME_LEN 16 /* incl. trailing 0 */
180     size_t len = LIBPTHREAD_NAME_LEN - 1;
181     char namebuf[LIBPTHREAD_NAME_LEN];
182     static char *libpthread_name = LIBPTHREAD_NAME;
183
184     if (GC_syms_initialized) return;
185 #   ifdef RTLD_NEXT
186       dl_handle = RTLD_NEXT;
187 #   else
188       dl_handle = dlopen(libpthread_name, RTLD_LAZY);
189       if (NULL == dl_handle) {
190         while (isdigit(libpthread_name[len-1])) --len;
191         if (libpthread_name[len-1] == '.') --len;
192         memcpy(namebuf, libpthread_name, len);
193         namebuf[len] = '\0';
194         dl_handle = dlopen(namebuf, RTLD_LAZY);
195       }
196       if (NULL == dl_handle) ABORT("Couldn't open libpthread\n");
197 #   endif
198     GC_real_pthread_create = (GC_pthread_create_t)
199                                 dlsym(dl_handle, "pthread_create");
200     GC_real_pthread_sigmask = (GC_pthread_sigmask_t)
201                                 dlsym(dl_handle, "pthread_sigmask");
202     GC_real_pthread_join = (GC_pthread_join_t)
203                                 dlsym(dl_handle, "pthread_join");
204     GC_real_pthread_detach = (GC_pthread_detach_t)
205                                 dlsym(dl_handle, "pthread_detach");
206     GC_syms_initialized = TRUE;
207   }
208
209 # define INIT_REAL_SYMS() if (!GC_syms_initialized) GC_init_real_syms();
210 #else
211 # define INIT_REAL_SYMS()
212 #endif
213
214 void GC_thr_init(void);
215
216 static GC_bool parallel_initialized = FALSE;
217
218 GC_bool GC_need_to_lock = FALSE;
219
220 void GC_init_parallel(void);
221
222 STATIC long GC_nprocs = 1;
223                         /* Number of processors.  We may not have       */
224                         /* access to all of them, but this is as good   */
225                         /* a guess as any ...                           */
226
227 #ifdef THREAD_LOCAL_ALLOC
228 /* We must explicitly mark ptrfree and gcj free lists, since the free   */
229 /* list links wouldn't otherwise be found.  We also set them in the     */
230 /* normal free lists, since that involves touching less memory than if  */
231 /* we scanned them normally.                                            */
232 void GC_mark_thread_local_free_lists(void)
233 {
234     int i;
235     GC_thread p;
236     
237     for (i = 0; i < THREAD_TABLE_SZ; ++i) {
238       for (p = GC_threads[i]; 0 != p; p = p -> next) {
239         GC_mark_thread_local_fls_for(&(p->tlfs));
240       }
241     }
242 }
243
244 #if defined(GC_ASSERTIONS)
245     void GC_check_tls_for(GC_tlfs p);
246 #   if defined(USE_CUSTOM_SPECIFIC)
247       void GC_check_tsd_marks(tsd *key);
248 #   endif 
249     /* Check that all thread-local free-lists are completely marked.    */
250     /* also check that thread-specific-data structures are marked.      */
251     void GC_check_tls(void) {
252         int i;
253         GC_thread p;
254         
255         for (i = 0; i < THREAD_TABLE_SZ; ++i) {
256           for (p = GC_threads[i]; 0 != p; p = p -> next) {
257             GC_check_tls_for(&(p->tlfs));
258           }
259         }
260 #       if defined(USE_CUSTOM_SPECIFIC)
261           if (GC_thread_key != 0)
262             GC_check_tsd_marks(GC_thread_key);
263 #       endif 
264     }
265 #endif /* GC_ASSERTIONS */
266
267 #endif /* Thread_local_alloc */
268
269 #ifdef PARALLEL_MARK
270
271 # ifndef MAX_MARKERS
272 #   define MAX_MARKERS 16
273 # endif
274
275 static ptr_t marker_sp[MAX_MARKERS - 1] = {0};
276 #ifdef IA64
277   static ptr_t marker_bsp[MAX_MARKERS - 1] = {0};
278 #endif
279
280 STATIC void * GC_mark_thread(void * id)
281 {
282   word my_mark_no = 0;
283
284   marker_sp[(word)id] = GC_approx_sp();
285 # ifdef IA64
286     marker_bsp[(word)id] = GC_save_regs_in_stack();
287 # endif
288
289   if ((word)id == (word)-1) return 0; /* to make compiler happy */
290
291   for (;; ++my_mark_no) {
292     /* GC_mark_no is passed only to allow GC_help_marker to terminate   */
293     /* promptly.  This is important if it were called from the signal   */
294     /* handler or from the GC lock acquisition code.  Under Linux, it's */
295     /* not safe to call it from a signal handler, since it uses mutexes */
296     /* and condition variables.  Since it is called only here, the      */
297     /* argument is unnecessary.                                         */
298     if (my_mark_no < GC_mark_no || my_mark_no > GC_mark_no + 2) {
299         /* resynchronize if we get far off, e.g. because GC_mark_no     */
300         /* wrapped.                                                     */
301         my_mark_no = GC_mark_no;
302     }
303 #   ifdef DEBUG_THREADS
304         GC_printf("Starting mark helper for mark number %lu\n",
305                 (unsigned long)my_mark_no);
306 #   endif
307     GC_help_marker(my_mark_no);
308   }
309 }
310
311 extern long GC_markers;         /* Number of mark threads we would      */
312                                 /* like to have.  Includes the          */
313                                 /* initiating thread.                   */
314
315 pthread_t GC_mark_threads[MAX_MARKERS];
316
317 #define PTHREAD_CREATE REAL_FUNC(pthread_create)
318
319 static void start_mark_threads(void)
320 {
321     unsigned i;
322     pthread_attr_t attr;
323
324     if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed");
325         
326     if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
327         ABORT("pthread_attr_setdetachstate failed");
328
329 #   if defined(HPUX) || defined(GC_DGUX386_THREADS)
330       /* Default stack size is usually too small: fix it. */
331       /* Otherwise marker threads or GC may run out of    */
332       /* space.                                           */
333 #     define MIN_STACK_SIZE (8*HBLKSIZE*sizeof(word))
334       {
335         size_t old_size;
336         int code;
337
338         if (pthread_attr_getstacksize(&attr, &old_size) != 0)
339           ABORT("pthread_attr_getstacksize failed\n");
340         if (old_size < MIN_STACK_SIZE) {
341           if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0)
342                   ABORT("pthread_attr_setstacksize failed\n");
343         }
344       }
345 #   endif /* HPUX || GC_DGUX386_THREADS */
346     if (GC_print_stats) {
347         GC_log_printf("Starting %ld marker threads\n", GC_markers - 1);
348     }
349     for (i = 0; i < GC_markers - 1; ++i) {
350       if (0 != PTHREAD_CREATE(GC_mark_threads + i, &attr,
351                               GC_mark_thread, (void *)(word)i)) {
352         WARN("Marker thread creation failed, errno = %ld.\n", errno);
353       }
354     }
355     pthread_attr_destroy(&attr);
356 }
357
358 #endif /* PARALLEL_MARK */
359
360 GC_bool GC_thr_initialized = FALSE;
361
362 volatile GC_thread GC_threads[THREAD_TABLE_SZ];
363
364 void GC_push_thread_structures(void)
365 {
366     GC_ASSERT(I_HOLD_LOCK());
367     GC_push_all((ptr_t)(GC_threads), (ptr_t)(GC_threads)+sizeof(GC_threads));
368 #   if defined(THREAD_LOCAL_ALLOC)
369       GC_push_all((ptr_t)(&GC_thread_key),
370           (ptr_t)(&GC_thread_key)+sizeof(&GC_thread_key));
371 #   endif
372 }
373
374 /* It may not be safe to allocate when we register the first thread.    */
375 static struct GC_Thread_Rep first_thread;
376
377 /* Add a thread to GC_threads.  We assume it wasn't already there.      */
378 /* Caller holds allocation lock.                                        */
379 STATIC GC_thread GC_new_thread(pthread_t id)
380 {
381     int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
382     GC_thread result;
383     static GC_bool first_thread_used = FALSE;
384     
385     GC_ASSERT(I_HOLD_LOCK());
386     if (!first_thread_used) {
387         result = &first_thread;
388         first_thread_used = TRUE;
389     } else {
390         result = (struct GC_Thread_Rep *)
391                  GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
392         if (result == 0) return(0);
393     }
394     result -> id = id;
395     result -> next = GC_threads[hv];
396     GC_threads[hv] = result;
397     GC_ASSERT(result -> flags == 0 && result -> thread_blocked == 0);
398     return(result);
399 }
400
401 /* Delete a thread from GC_threads.  We assume it is there.     */
402 /* (The code intentionally traps if it wasn't.)                 */
403 STATIC void GC_delete_thread(pthread_t id)
404 {
405     int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
406     register GC_thread p = GC_threads[hv];
407     register GC_thread prev = 0;
408     
409     GC_ASSERT(I_HOLD_LOCK());
410     while (!THREAD_EQUAL(p -> id, id)) {
411         prev = p;
412         p = p -> next;
413     }
414     if (prev == 0) {
415         GC_threads[hv] = p -> next;
416     } else {
417         prev -> next = p -> next;
418     }
419 #   ifdef GC_DARWIN_THREADS
420         mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
421 #   endif
422     GC_INTERNAL_FREE(p);
423 }
424
425 /* If a thread has been joined, but we have not yet             */
426 /* been notified, then there may be more than one thread        */
427 /* in the table with the same pthread id.                       */
428 /* This is OK, but we need a way to delete a specific one.      */
429 STATIC void GC_delete_gc_thread(GC_thread gc_id)
430 {
431     pthread_t id = gc_id -> id;
432     int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
433     register GC_thread p = GC_threads[hv];
434     register GC_thread prev = 0;
435
436     GC_ASSERT(I_HOLD_LOCK());
437     while (p != gc_id) {
438         prev = p;
439         p = p -> next;
440     }
441     if (prev == 0) {
442         GC_threads[hv] = p -> next;
443     } else {
444         prev -> next = p -> next;
445     }
446 #   ifdef GC_DARWIN_THREADS
447         mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
448 #   endif
449     GC_INTERNAL_FREE(p);
450 }
451
452 /* Return a GC_thread corresponding to a given pthread_t.       */
453 /* Returns 0 if it's not there.                                 */
454 /* Caller holds  allocation lock or otherwise inhibits          */
455 /* updates.                                                     */
456 /* If there is more than one thread with the given id we        */
457 /* return the most recent one.                                  */
458 GC_thread GC_lookup_thread(pthread_t id)
459 {
460     int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ;
461     register GC_thread p = GC_threads[hv];
462     
463     while (p != 0 && !THREAD_EQUAL(p -> id, id)) p = p -> next;
464     return(p);
465 }
466
467 #ifdef HANDLE_FORK
468 /* Remove all entries from the GC_threads table, except the     */
469 /* one for the current thread.  We need to do this in the child */
470 /* process after a fork(), since only the current thread        */
471 /* survives in the child.                                       */
472 STATIC void GC_remove_all_threads_but_me(void)
473 {
474     pthread_t self = pthread_self();
475     int hv;
476     GC_thread p, next, me;
477
478     for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
479       me = 0;
480       for (p = GC_threads[hv]; 0 != p; p = next) {
481         next = p -> next;
482         if (THREAD_EQUAL(p -> id, self)) {
483           me = p;
484           p -> next = 0;
485         } else {
486 #         ifdef THREAD_LOCAL_ALLOC
487             if (!(p -> flags & FINISHED)) {
488               GC_destroy_thread_local(&(p->tlfs));
489             }
490 #         endif /* THREAD_LOCAL_ALLOC */
491           if (p != &first_thread) GC_INTERNAL_FREE(p);
492         }
493       }
494       GC_threads[hv] = me;
495     }
496 }
497 #endif /* HANDLE_FORK */
498
499 #ifdef USE_PROC_FOR_LIBRARIES
500 GC_bool GC_segment_is_thread_stack(ptr_t lo, ptr_t hi)
501 {
502     int i;
503     GC_thread p;
504     
505     GC_ASSERT(I_HOLD_LOCK());
506 #   ifdef PARALLEL_MARK
507       for (i = 0; i < GC_markers - 1; ++i) {
508         if (marker_sp[i] > lo & marker_sp[i] < hi) return TRUE;
509 #       ifdef IA64
510           if (marker_bsp[i] > lo & marker_bsp[i] < hi) return TRUE;
511 #       endif
512       }
513 #   endif
514     for (i = 0; i < THREAD_TABLE_SZ; i++) {
515       for (p = GC_threads[i]; p != 0; p = p -> next) {
516         if (0 != p -> stack_end) {
517 #         ifdef STACK_GROWS_UP
518             if (p -> stack_end >= lo && p -> stack_end < hi) return TRUE;
519 #         else /* STACK_GROWS_DOWN */
520             if (p -> stack_end > lo && p -> stack_end <= hi) return TRUE;
521 #         endif
522         }
523       }
524     }
525     return FALSE;
526 }
527 #endif /* USE_PROC_FOR_LIBRARIES */
528
529 #ifdef IA64
530 /* Find the largest stack_base smaller than bound.  May be used */
531 /* to find the boundary between a register stack and adjacent   */
532 /* immediately preceding memory stack.                          */
533 ptr_t GC_greatest_stack_base_below(ptr_t bound)
534 {
535     int i;
536     GC_thread p;
537     ptr_t result = 0;
538     
539     GC_ASSERT(I_HOLD_LOCK());
540 #   ifdef PARALLEL_MARK
541       for (i = 0; i < GC_markers - 1; ++i) {
542         if (marker_sp[i] > result && marker_sp[i] < bound)
543           result = marker_sp[i];
544       }
545 #   endif
546     for (i = 0; i < THREAD_TABLE_SZ; i++) {
547       for (p = GC_threads[i]; p != 0; p = p -> next) {
548         if (p -> stack_end > result && p -> stack_end < bound) {
549           result = p -> stack_end;
550         }
551       }
552     }
553     return result;
554 }
555 #endif /* IA64 */
556
557 #ifdef GC_LINUX_THREADS
558 /* Return the number of processors, or i<= 0 if it can't be determined. */
559 STATIC int GC_get_nprocs(void)
560 {
561     /* Should be "return sysconf(_SC_NPROCESSORS_ONLN);" but that       */
562     /* appears to be buggy in many cases.                               */
563     /* We look for lines "cpu<n>" in /proc/stat.                        */
564 #   define STAT_BUF_SIZE 4096
565 #   define STAT_READ read
566         /* If read is wrapped, this may need to be redefined to call    */
567         /* the real one.                                                */
568     char stat_buf[STAT_BUF_SIZE];
569     int f;
570     word result = 1;
571         /* Some old kernels only have a single "cpu nnnn ..."   */
572         /* entry in /proc/stat.  We identify those as           */
573         /* uniprocessors.                                       */
574     size_t i, len = 0;
575
576     f = open("/proc/stat", O_RDONLY);
577     if (f < 0 || (len = STAT_READ(f, stat_buf, STAT_BUF_SIZE)) < 100) {
578         WARN("Couldn't read /proc/stat\n", 0);
579         return -1;
580     }
581     for (i = 0; i < len - 100; ++i) {
582         if (stat_buf[i] == '\n' && stat_buf[i+1] == 'c'
583             && stat_buf[i+2] == 'p' && stat_buf[i+3] == 'u') {
584             int cpu_no = atoi(stat_buf + i + 4);
585             if (cpu_no >= result) result = cpu_no + 1;
586         }
587     }
588     close(f);
589     return result;
590 }
591 #endif /* GC_LINUX_THREADS */
592
593 /* We hold the GC lock.  Wait until an in-progress GC has finished.     */
594 /* Repeatedly RELEASES GC LOCK in order to wait.                        */
595 /* If wait_for_all is true, then we exit with the GC lock held and no   */
596 /* collection in progress; otherwise we just wait for the current GC    */
597 /* to finish.                                                           */
598 extern GC_bool GC_collection_in_progress(void);
599 STATIC void GC_wait_for_gc_completion(GC_bool wait_for_all)
600 {
601     GC_ASSERT(I_HOLD_LOCK());
602     if (GC_incremental && GC_collection_in_progress()) {
603         int old_gc_no = GC_gc_no;
604
605         /* Make sure that no part of our stack is still on the mark stack, */
606         /* since it's about to be unmapped.                                */
607         while (GC_incremental && GC_collection_in_progress()
608                && (wait_for_all || old_gc_no == GC_gc_no)) {
609             ENTER_GC();
610             GC_in_thread_creation = TRUE;
611             GC_collect_a_little_inner(1);
612             GC_in_thread_creation = FALSE;
613             EXIT_GC();
614             UNLOCK();
615             sched_yield();
616             LOCK();
617         }
618     }
619 }
620
621 #ifdef HANDLE_FORK
622 /* Procedures called before and after a fork.  The goal here is to make */
623 /* it safe to call GC_malloc() in a forked child.  It's unclear that is */
624 /* attainable, since the single UNIX spec seems to imply that one       */
625 /* should only call async-signal-safe functions, and we probably can't  */
626 /* quite guarantee that.  But we give it our best shot.  (That same     */
627 /* spec also implies that it's not safe to call the system malloc       */
628 /* between fork() and exec().  Thus we're doing no worse than it.       */
629
630 /* Called before a fork()               */
631 STATIC void GC_fork_prepare_proc(void)
632 {
633     /* Acquire all relevant locks, so that after releasing the locks    */
634     /* the child will see a consistent state in which monitor           */
635     /* invariants hold.  Unfortunately, we can't acquire libc locks     */
636     /* we might need, and there seems to be no guarantee that libc      */
637     /* must install a suitable fork handler.                            */
638     /* Wait for an ongoing GC to finish, since we can't finish it in    */
639     /* the (one remaining thread in) the child.                         */
640       LOCK();
641 #     if defined(PARALLEL_MARK)
642         if (GC_parallel)
643           GC_wait_for_reclaim();
644 #     endif
645       GC_wait_for_gc_completion(TRUE);
646 #     if defined(PARALLEL_MARK)
647         if (GC_parallel)
648           GC_acquire_mark_lock();
649 #     endif
650 }
651
652 /* Called in parent after a fork()      */
653 STATIC void GC_fork_parent_proc(void)
654 {
655 #   if defined(PARALLEL_MARK)
656       if (GC_parallel)
657         GC_release_mark_lock();
658 #   endif
659     UNLOCK();
660 }
661
662 /* Called in child after a fork()       */
663 STATIC void GC_fork_child_proc(void)
664 {
665     /* Clean up the thread table, so that just our thread is left. */
666 #   if defined(PARALLEL_MARK)
667       if (GC_parallel)
668         GC_release_mark_lock();
669 #   endif
670     GC_remove_all_threads_but_me();
671 #   ifdef PARALLEL_MARK
672       /* Turn off parallel marking in the child, since we are probably  */
673       /* just going to exec, and we would have to restart mark threads. */
674         GC_markers = 1;
675         GC_parallel = FALSE;
676 #   endif /* PARALLEL_MARK */
677     UNLOCK();
678 }
679 #endif /* HANDLE_FORK */
680
681 #if defined(GC_DGUX386_THREADS)
682 /* Return the number of processors, or i<= 0 if it can't be determined. */
683 STATIC int GC_get_nprocs(void)
684 {
685     /* <takis@XFree86.Org> */
686     int numCpus;
687     struct dg_sys_info_pm_info pm_sysinfo;
688     int status =0;
689
690     status = dg_sys_info((long int *) &pm_sysinfo,
691         DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION);
692     if (status < 0)
693        /* set -1 for error */
694        numCpus = -1;
695     else
696       /* Active CPUs */
697       numCpus = pm_sysinfo.idle_vp_count;
698
699 #  ifdef DEBUG_THREADS
700     GC_printf("Number of active CPUs in this system: %d\n", numCpus);
701 #  endif
702     return(numCpus);
703 }
704 #endif /* GC_DGUX386_THREADS */
705
706 #if defined(GC_NETBSD_THREADS)
707 static int get_ncpu(void)
708 {
709     int mib[] = {CTL_HW,HW_NCPU};
710     int res;
711     size_t len = sizeof(res);
712
713     sysctl(mib, sizeof(mib)/sizeof(int), &res, &len, NULL, 0);
714     return res;
715 }
716 #endif  /* GC_NETBSD_THREADS */
717
718 # if defined(GC_LINUX_THREADS) && defined(INCLUDE_LINUX_THREAD_DESCR)
719 __thread int dummy_thread_local;
720 # endif
721
722 /* We hold the allocation lock. */
723 void GC_thr_init(void)
724 {
725 #   ifndef GC_DARWIN_THREADS
726         int dummy;
727 #   endif
728     GC_thread t;
729
730     if (GC_thr_initialized) return;
731     GC_thr_initialized = TRUE;
732     
733 #   ifdef HANDLE_FORK
734       /* Prepare for a possible fork.   */
735         pthread_atfork(GC_fork_prepare_proc, GC_fork_parent_proc,
736                        GC_fork_child_proc);
737 #   endif /* HANDLE_FORK */
738 #   if defined(INCLUDE_LINUX_THREAD_DESCR)
739       /* Explicitly register the region including the address           */
740       /* of a thread local variable.  This should include thread        */
741       /* locals for the main thread, except for those allocated         */
742       /* in response to dlopen calls.                                   */  
743         {
744           ptr_t thread_local_addr = (ptr_t)(&dummy_thread_local);
745           ptr_t main_thread_start, main_thread_end;
746           if (!GC_enclosing_mapping(thread_local_addr, &main_thread_start,
747                                     &main_thread_end)) {
748             ABORT("Failed to find mapping for main thread thread locals");
749           }
750           GC_add_roots_inner(main_thread_start, main_thread_end, FALSE);
751         }
752 #   endif
753     /* Add the initial thread, so we can stop it.       */
754       t = GC_new_thread(pthread_self());
755 #     ifdef GC_DARWIN_THREADS
756          t -> stop_info.mach_thread = mach_thread_self();
757 #     else
758          t -> stop_info.stack_ptr = (ptr_t)(&dummy);
759 #     endif
760       t -> flags = DETACHED | MAIN_THREAD;
761
762     GC_stop_init();
763
764     /* Set GC_nprocs.  */
765       {
766         char * nprocs_string = GETENV("GC_NPROCS");
767         GC_nprocs = -1;
768         if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string);
769       }
770       if (GC_nprocs <= 0) {
771 #       if defined(GC_HPUX_THREADS)
772           GC_nprocs = pthread_num_processors_np();
773 #       endif
774 #       if defined(GC_OSF1_THREADS) || defined(GC_AIX_THREADS) \
775            || defined(GC_SOLARIS_THREADS) || defined(GC_GNU_THREADS)
776           GC_nprocs = sysconf(_SC_NPROCESSORS_ONLN);
777           if (GC_nprocs <= 0) GC_nprocs = 1;
778 #       endif
779 #       if defined(GC_IRIX_THREADS)
780           GC_nprocs = sysconf(_SC_NPROC_ONLN);
781           if (GC_nprocs <= 0) GC_nprocs = 1;
782 #       endif
783 #       if defined(GC_NETBSD_THREADS)
784           GC_nprocs = get_ncpu();
785 #       endif
786 #       if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
787           int ncpus = 1;
788           size_t len = sizeof(ncpus);
789           sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0);
790           GC_nprocs = ncpus;
791 #       endif
792 #       if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS)
793           GC_nprocs = GC_get_nprocs();
794 #       endif
795       }
796       if (GC_nprocs <= 0) {
797         WARN("GC_get_nprocs() returned %ld\n", GC_nprocs);
798         GC_nprocs = 2;
799 #       ifdef PARALLEL_MARK
800           GC_markers = 1;
801 #       endif
802       } else {
803 #       ifdef PARALLEL_MARK
804           {
805             char * markers_string = GETENV("GC_MARKERS");
806             if (markers_string != NULL) {
807               GC_markers = atoi(markers_string);
808               if (GC_markers > MAX_MARKERS) {
809                 WARN("Limiting number of mark threads\n", 0);
810                 GC_markers = MAX_MARKERS;
811               }
812             } else {
813               GC_markers = GC_nprocs;
814               if (GC_markers >= MAX_MARKERS)
815                 GC_markers = MAX_MARKERS; /* silently limit GC_markers value */
816             }
817           }
818 #       endif
819       }
820 #   ifdef PARALLEL_MARK
821       if (GC_print_stats) {
822           GC_log_printf("Number of processors = %ld, "
823                  "number of marker threads = %ld\n", GC_nprocs, GC_markers);
824       }
825       if (GC_markers <= 1) {
826         GC_parallel = FALSE;
827         if (GC_print_stats) {
828             GC_log_printf(
829                 "Single marker thread, turning off parallel marking\n");
830         }
831       } else {
832         GC_parallel = TRUE;
833         /* Disable true incremental collection, but generational is OK. */
834         GC_time_limit = GC_TIME_UNLIMITED;
835       }
836       /* If we are using a parallel marker, actually start helper threads.  */
837         if (GC_parallel) start_mark_threads();
838 #   endif
839 }
840
841
842 /* Perform all initializations, including those that    */
843 /* may require allocation.                              */
844 /* Called without allocation lock.                      */
845 /* Must be called before a second thread is created.    */
846 /* Did we say it's called without the allocation lock?  */
847 void GC_init_parallel(void)
848 {
849     if (parallel_initialized) return;
850     parallel_initialized = TRUE;
851
852     /* GC_init() calls us back, so set flag first.      */
853     if (!GC_is_initialized) GC_init();
854     /* Initialize thread local free lists if used.      */
855 #   if defined(THREAD_LOCAL_ALLOC)
856       LOCK();
857       GC_init_thread_local(&(GC_lookup_thread(pthread_self())->tlfs));
858       UNLOCK();
859 #   endif
860 }
861
862
863 #if !defined(GC_DARWIN_THREADS)
864 int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, sigset_t *oset)
865 {
866     sigset_t fudged_set;
867     
868     INIT_REAL_SYMS();
869     if (set != NULL && (how == SIG_BLOCK || how == SIG_SETMASK)) {
870         fudged_set = *set;
871         sigdelset(&fudged_set, SIG_SUSPEND);
872         set = &fudged_set;
873     }
874     return(REAL_FUNC(pthread_sigmask)(how, set, oset));
875 }
876 #endif /* !GC_DARWIN_THREADS */
877
878 /* Wrapper for functions that are likely to block for an appreciable    */
879 /* length of time.                                                      */
880
881 struct blocking_data {
882     void (GC_CALLBACK *fn)(void *);
883     void *arg;
884 };
885
886 /*ARGSUSED*/
887 static void GC_do_blocking_inner(ptr_t data, void * context) {
888     struct blocking_data * d = (struct blocking_data *) data;
889     GC_thread me;
890     LOCK();
891     me = GC_lookup_thread(pthread_self());
892     GC_ASSERT(!(me -> thread_blocked));
893 #   ifdef SPARC
894         me -> stop_info.stack_ptr = GC_save_regs_in_stack();
895 #   elif !defined(GC_DARWIN_THREADS)
896         me -> stop_info.stack_ptr = GC_approx_sp();
897 #   endif
898 #   ifdef IA64
899         me -> backing_store_ptr = GC_save_regs_in_stack();
900 #   endif
901     me -> thread_blocked = TRUE;
902     /* Save context here if we want to support precise stack marking */
903     UNLOCK();
904     (d -> fn)(d -> arg);
905     LOCK();   /* This will block if the world is stopped.       */
906     me -> thread_blocked = FALSE;
907     UNLOCK();
908 }
909
910 void GC_CALL GC_do_blocking(void (GC_CALLBACK *fn)(void *), void *arg) {
911     struct blocking_data my_data;
912
913     my_data.fn = fn;
914     my_data.arg = arg;
915     GC_with_callee_saves_pushed(GC_do_blocking_inner, (ptr_t)(&my_data));
916 }
917     
918 struct start_info {
919     void *(*start_routine)(void *);
920     void *arg;
921     word flags;
922     sem_t registered;           /* 1 ==> in our thread table, but       */
923                                 /* parent hasn't yet noticed.           */
924 };
925
926 GC_API int GC_CALL GC_unregister_my_thread(void)
927 {
928     GC_thread me;
929
930     LOCK();
931     /* Wait for any GC that may be marking from our stack to    */
932     /* complete before we remove this thread.                   */
933     GC_wait_for_gc_completion(FALSE);
934     me = GC_lookup_thread(pthread_self());
935 #   if defined(THREAD_LOCAL_ALLOC)
936       GC_destroy_thread_local(&(me->tlfs));
937 #   endif
938     if (me -> flags & DETACHED) {
939         GC_delete_thread(pthread_self());
940     } else {
941         me -> flags |= FINISHED;
942     }
943 #   if defined(THREAD_LOCAL_ALLOC)
944       GC_remove_specific(GC_thread_key);
945 #   endif
946     UNLOCK();
947     return GC_SUCCESS;
948 }
949
950 /* Called at thread exit.                               */
951 /* Never called for main thread.  That's OK, since it   */
952 /* results in at most a tiny one-time leak.  And        */
953 /* linuxthreads doesn't reclaim the main threads        */
954 /* resources or id anyway.                              */
955 STATIC void GC_thread_exit_proc(void *arg)
956 {
957     GC_unregister_my_thread();
958 }
959
960 int WRAP_FUNC(pthread_join)(pthread_t thread, void **retval)
961 {
962     int result;
963     GC_thread thread_gc_id;
964     
965     INIT_REAL_SYMS();
966     LOCK();
967     thread_gc_id = GC_lookup_thread(thread);
968     /* This is guaranteed to be the intended one, since the thread id   */
969     /* cant have been recycled by pthreads.                             */
970     UNLOCK();
971     result = REAL_FUNC(pthread_join)(thread, retval);
972 # if defined (GC_FREEBSD_THREADS)
973     /* On FreeBSD, the wrapped pthread_join() sometimes returns (what
974        appears to be) a spurious EINTR which caused the test and real code
975        to gratuitously fail.  Having looked at system pthread library source
976        code, I see how this return code may be generated.  In one path of
977        code, pthread_join() just returns the errno setting of the thread
978        being joined.  This does not match the POSIX specification or the
979        local man pages thus I have taken the liberty to catch this one
980        spurious return value properly conditionalized on GC_FREEBSD_THREADS. */
981     if (result == EINTR) result = 0;
982 # endif
983     if (result == 0) {
984         LOCK();
985         /* Here the pthread thread id may have been recycled. */
986         GC_delete_gc_thread(thread_gc_id);
987         UNLOCK();
988     }
989     return result;
990 }
991
992 int
993 WRAP_FUNC(pthread_detach)(pthread_t thread)
994 {
995     int result;
996     GC_thread thread_gc_id;
997     
998     INIT_REAL_SYMS();
999     LOCK();
1000     thread_gc_id = GC_lookup_thread(thread);
1001     UNLOCK();
1002     result = REAL_FUNC(pthread_detach)(thread);
1003     if (result == 0) {
1004       LOCK();
1005       thread_gc_id -> flags |= DETACHED;
1006       /* Here the pthread thread id may have been recycled. */
1007       if (thread_gc_id -> flags & FINISHED) {
1008         GC_delete_gc_thread(thread_gc_id);
1009       }
1010       UNLOCK();
1011     }
1012     return result;
1013 }
1014
1015 GC_bool GC_in_thread_creation = FALSE;  /* Protected by allocation lock. */
1016
1017 STATIC GC_thread GC_register_my_thread_inner(struct GC_stack_base *sb,
1018                                              pthread_t my_pthread)
1019 {
1020     GC_thread me;
1021
1022     GC_in_thread_creation = TRUE; /* OK to collect from unknown thread. */
1023     me = GC_new_thread(my_pthread);
1024     GC_in_thread_creation = FALSE;
1025     if (me == 0)
1026       ABORT("Failed to allocate memory for thread registering.");
1027 #   ifdef GC_DARWIN_THREADS
1028       me -> stop_info.mach_thread = mach_thread_self();
1029 #   else
1030       me -> stop_info.stack_ptr = sb -> mem_base;
1031 #   endif
1032     me -> stack_end = sb -> mem_base;
1033     if (me -> stack_end == NULL)
1034       ABORT("Bad stack base in GC_register_my_thread");
1035 #   ifdef IA64
1036       me -> backing_store_end = sb -> reg_base;
1037 #   endif /* IA64 */
1038     return me;
1039 }
1040
1041 GC_API void GC_CALL GC_allow_register_threads(void)
1042 {
1043     /* Check GC is initialized and the current thread is registered. */
1044     GC_ASSERT(GC_lookup_thread(pthread_self()) != 0);
1045
1046     GC_need_to_lock = TRUE; /* We are multi-threaded now. */
1047 }
1048
1049 GC_API int GC_CALL GC_register_my_thread(struct GC_stack_base *sb)
1050 {
1051     pthread_t my_pthread = pthread_self();
1052     GC_thread me;
1053
1054     if (GC_need_to_lock == FALSE)
1055         ABORT("Threads explicit registering is not previously enabled");
1056
1057     LOCK();
1058     me = GC_lookup_thread(my_pthread);
1059     if (0 == me) {
1060         me = GC_register_my_thread_inner(sb, my_pthread);
1061         me -> flags |= DETACHED;
1062           /* Treat as detached, since we do not need to worry about     */
1063           /* pointer results.                                           */
1064 #       if defined(THREAD_LOCAL_ALLOC)
1065           GC_init_thread_local(&(me->tlfs));
1066 #       endif
1067         UNLOCK();
1068         return GC_SUCCESS;
1069     } else {
1070         UNLOCK();
1071         return GC_DUPLICATE;
1072     }
1073 }
1074
1075 STATIC void * GC_CALLBACK GC_inner_start_routine(struct GC_stack_base *sb,
1076                                                 void * arg)
1077 {
1078     struct start_info * si = arg;
1079     void * result;
1080     GC_thread me;
1081     pthread_t my_pthread;
1082     void *(*start)(void *);
1083     void *start_arg;
1084
1085     my_pthread = pthread_self();
1086 #   ifdef DEBUG_THREADS
1087         GC_printf("Starting thread 0x%x\n", (unsigned)my_pthread);
1088         GC_printf("pid = %ld\n", (long) getpid());
1089         GC_printf("sp = %p\n", &arg);
1090 #   endif
1091     LOCK();
1092     me = GC_register_my_thread_inner(sb, my_pthread);
1093     me -> flags = si -> flags;
1094 #   if defined(THREAD_LOCAL_ALLOC)
1095         GC_init_thread_local(&(me->tlfs));
1096 #   endif
1097     UNLOCK();
1098     start = si -> start_routine;
1099 #   ifdef DEBUG_THREADS
1100         GC_printf("start_routine = %p\n", (void *)(signed_word)start);
1101 #   endif
1102     start_arg = si -> arg;
1103     sem_post(&(si -> registered));      /* Last action on si.   */
1104                                         /* OK to deallocate.    */
1105     pthread_cleanup_push(GC_thread_exit_proc, 0);
1106     result = (*start)(start_arg);
1107 #   if DEBUG_THREADS
1108         GC_printf("Finishing thread 0x%x\n", (unsigned)pthread_self());
1109 #   endif
1110     me -> status = result;
1111     pthread_cleanup_pop(1);
1112     /* Cleanup acquires lock, ensuring that we can't exit               */
1113     /* while a collection that thinks we're alive is trying to stop     */
1114     /* us.                                                              */
1115     return(result);
1116 }
1117
1118 STATIC void * GC_start_routine(void * arg)
1119 {
1120 #   ifdef INCLUDE_LINUX_THREAD_DESCR
1121       struct GC_stack_base sb;
1122
1123 #     ifdef REDIRECT_MALLOC
1124         /* GC_get_stack_base may call pthread_getattr_np, which can     */
1125         /* unfortunately call realloc, which may allocate from an       */
1126         /* unregistered thread.  This is unpleasant, since it might     */ 
1127         /* force heap growth.                                           */
1128         GC_disable();
1129 #     endif
1130       if (GC_get_stack_base(&sb) != GC_SUCCESS)
1131         ABORT("Failed to get thread stack base.");
1132 #     ifdef REDIRECT_MALLOC
1133         GC_enable();
1134 #     endif
1135       return GC_inner_start_routine(&sb, arg);
1136 #   else
1137       return GC_call_with_stack_base(GC_inner_start_routine, arg);
1138 #   endif
1139 }
1140
1141 int
1142 WRAP_FUNC(pthread_create)(pthread_t *new_thread,
1143                   const pthread_attr_t *attr,
1144                   void *(*start_routine)(void *), void *arg)
1145 {
1146     int result;
1147     int detachstate;
1148     word my_flags = 0;
1149     struct start_info * si; 
1150         /* This is otherwise saved only in an area mmapped by the thread */
1151         /* library, which isn't visible to the collector.                */
1152  
1153     /* We resist the temptation to muck with the stack size here,       */
1154     /* even if the default is unreasonably small.  That's the client's  */
1155     /* responsibility.                                                  */
1156
1157     INIT_REAL_SYMS();
1158     LOCK();
1159     si = (struct start_info *)GC_INTERNAL_MALLOC(sizeof(struct start_info),
1160                                                  NORMAL);
1161     UNLOCK();
1162     if (!parallel_initialized) GC_init_parallel();
1163     if (0 == si &&
1164         (si = (struct start_info *)GC_oom_fn(sizeof(struct start_info))) == 0)
1165       return(ENOMEM);
1166     sem_init(&(si -> registered), 0, 0);
1167     si -> start_routine = start_routine;
1168     si -> arg = arg;
1169     LOCK();
1170     if (!GC_thr_initialized) GC_thr_init();
1171 #   ifdef GC_ASSERTIONS
1172       {
1173         size_t stack_size = 0;
1174         if (NULL != attr) {
1175            pthread_attr_getstacksize(attr, &stack_size);
1176         }
1177         if (0 == stack_size) {
1178            pthread_attr_t my_attr;
1179            pthread_attr_init(&my_attr);
1180            pthread_attr_getstacksize(&my_attr, &stack_size);
1181         }
1182         /* On Solaris 10, with default attr initialization,     */
1183         /* stack_size remains 0.  Fudge it.                     */
1184         if (0 == stack_size) {
1185 #           ifndef SOLARIS
1186               WARN("Failed to get stack size for assertion checking\n", 0);
1187 #           endif
1188             stack_size = 1000000;
1189         }
1190 #       ifdef PARALLEL_MARK
1191           GC_ASSERT(stack_size >= (8*HBLKSIZE*sizeof(word)));
1192 #       else
1193           /* FreeBSD-5.3/Alpha: default pthread stack is 64K,   */
1194           /* HBLKSIZE=8192, sizeof(word)=8                      */
1195           GC_ASSERT(stack_size >= 65536);
1196 #       endif
1197         /* Our threads may need to do some work for the GC.     */
1198         /* Ridiculously small threads won't work, and they      */
1199         /* probably wouldn't work anyway.                       */
1200       }
1201 #   endif
1202     if (NULL == attr) {
1203         detachstate = PTHREAD_CREATE_JOINABLE;
1204     } else { 
1205         pthread_attr_getdetachstate(attr, &detachstate);
1206     }
1207     if (PTHREAD_CREATE_DETACHED == detachstate) my_flags |= DETACHED;
1208     si -> flags = my_flags;
1209     UNLOCK();
1210 #   ifdef DEBUG_THREADS
1211         GC_printf("About to start new thread from thread 0x%x\n",
1212                   (unsigned)pthread_self());
1213 #   endif
1214     GC_need_to_lock = TRUE;
1215
1216     result = REAL_FUNC(pthread_create)(new_thread, attr, GC_start_routine, si);
1217
1218 #   ifdef DEBUG_THREADS
1219         GC_printf("Started thread 0x%x\n", (unsigned)(*new_thread));
1220 #   endif
1221     /* Wait until child has been added to the thread table.             */
1222     /* This also ensures that we hold onto si until the child is done   */
1223     /* with it.  Thus it doesn't matter whether it is otherwise         */
1224     /* visible to the collector.                                        */
1225     if (0 == result) {
1226         while (0 != sem_wait(&(si -> registered))) {
1227             if (EINTR != errno) ABORT("sem_wait failed");
1228         }
1229     }
1230     sem_destroy(&(si -> registered));
1231     LOCK();
1232     GC_INTERNAL_FREE(si);
1233     UNLOCK();
1234
1235     return(result);
1236 }
1237
1238 #if defined(USE_SPIN_LOCK) || !defined(NO_PTHREAD_TRYLOCK)
1239 /* Spend a few cycles in a way that can't introduce contention with     */
1240 /* other threads.                                                       */
1241 STATIC void GC_pause(void)
1242 {
1243     int i;
1244 #   if !defined(__GNUC__) || defined(__INTEL_COMPILER)
1245       volatile word dummy = 0;
1246 #   endif
1247
1248     for (i = 0; i < 10; ++i) { 
1249 #     if defined(__GNUC__) && !defined(__INTEL_COMPILER)
1250         __asm__ __volatile__ (" " : : : "memory");
1251 #     else
1252         /* Something that's unlikely to be optimized away. */
1253         GC_noop(++dummy);
1254 #     endif
1255     }
1256 }
1257 #endif
1258     
1259 #define SPIN_MAX 128    /* Maximum number of calls to GC_pause before   */
1260                         /* give up.                                     */
1261
1262 volatile GC_bool GC_collecting = 0;
1263                         /* A hint that we're in the collector and       */
1264                         /* holding the allocation lock for an           */
1265                         /* extended period.                             */
1266
1267 #if (!defined(USE_SPIN_LOCK) && !defined(NO_PTHREAD_TRYLOCK)) \
1268         || defined(PARALLEL_MARK)
1269 /* If we don't want to use the below spinlock implementation, either    */
1270 /* because we don't have a GC_test_and_set implementation, or because   */
1271 /* we don't want to risk sleeping, we can still try spinning on         */
1272 /* pthread_mutex_trylock for a while.  This appears to be very          */
1273 /* beneficial in many cases.                                            */
1274 /* I suspect that under high contention this is nearly always better    */
1275 /* than the spin lock.  But it's a bit slower on a uniprocessor.        */
1276 /* Hence we still default to the spin lock.                             */
1277 /* This is also used to acquire the mark lock for the parallel          */
1278 /* marker.                                                              */
1279
1280 /* Here we use a strict exponential backoff scheme.  I don't know       */
1281 /* whether that's better or worse than the above.  We eventually        */
1282 /* yield by calling pthread_mutex_lock(); it never makes sense to       */
1283 /* explicitly sleep.                                                    */
1284
1285 /* #define LOCK_STATS */
1286 #ifdef LOCK_STATS
1287   AO_t GC_spin_count = 0;
1288   AO_t GC_block_count = 0;
1289   AO_t GC_unlocked_count = 0;
1290 #endif
1291
1292 STATIC void GC_generic_lock(pthread_mutex_t * lock)
1293 {
1294 #ifndef NO_PTHREAD_TRYLOCK
1295     unsigned pause_length = 1;
1296     unsigned i;
1297     
1298     if (0 == pthread_mutex_trylock(lock)) {
1299 #       ifdef LOCK_STATS
1300             (void)AO_fetch_and_add1(&GC_unlocked_count);
1301 #       endif
1302         return;
1303     }
1304     for (; pause_length <= SPIN_MAX; pause_length <<= 1) {
1305         for (i = 0; i < pause_length; ++i) {
1306             GC_pause();
1307         }
1308         switch(pthread_mutex_trylock(lock)) {
1309             case 0:
1310 #               ifdef LOCK_STATS
1311                     (void)AO_fetch_and_add1(&GC_spin_count);
1312 #               endif
1313                 return;
1314             case EBUSY:
1315                 break;
1316             default:
1317                 ABORT("Unexpected error from pthread_mutex_trylock");
1318         }
1319     }
1320 #endif /* !NO_PTHREAD_TRYLOCK */
1321 #   ifdef LOCK_STATS
1322         (void)AO_fetch_and_add1(&GC_block_count);
1323 #   endif
1324     pthread_mutex_lock(lock);
1325 }
1326
1327 #endif /* !USE_SPIN_LOCK || ... */
1328
1329 #if defined(USE_SPIN_LOCK)
1330
1331 /* Reasonably fast spin locks.  Basically the same implementation */
1332 /* as STL alloc.h.  This isn't really the right way to do this.   */
1333 /* but until the POSIX scheduling mess gets straightened out ...  */
1334
1335 volatile AO_TS_t GC_allocate_lock = 0;
1336
1337
1338 void GC_lock(void)
1339 {
1340 #   define low_spin_max 30  /* spin cycles if we suspect uniprocessor */
1341 #   define high_spin_max SPIN_MAX /* spin cycles for multiprocessor */
1342     static unsigned spin_max = low_spin_max;
1343     unsigned my_spin_max;
1344     static unsigned last_spins = 0;
1345     unsigned my_last_spins;
1346     int i;
1347
1348     if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
1349         return;
1350     }
1351     my_spin_max = spin_max;
1352     my_last_spins = last_spins;
1353     for (i = 0; i < my_spin_max; i++) {
1354         if (GC_collecting || GC_nprocs == 1) goto yield;
1355         if (i < my_last_spins/2) {
1356             GC_pause();
1357             continue;
1358         }
1359         if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
1360             /*
1361              * got it!
1362              * Spinning worked.  Thus we're probably not being scheduled
1363              * against the other process with which we were contending.
1364              * Thus it makes sense to spin longer the next time.
1365              */
1366             last_spins = i;
1367             spin_max = high_spin_max;
1368             return;
1369         }
1370     }
1371     /* We are probably being scheduled against the other process.  Sleep. */
1372     spin_max = low_spin_max;
1373 yield:
1374     for (i = 0;; ++i) {
1375         if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) {
1376             return;
1377         }
1378 #       define SLEEP_THRESHOLD 12
1379                 /* Under Linux very short sleeps tend to wait until     */
1380                 /* the current time quantum expires.  On old Linux      */
1381                 /* kernels nanosleep(<= 2ms) just spins under Linux.    */
1382                 /* (Under 2.4, this happens only for real-time          */
1383                 /* processes.)  We want to minimize both behaviors      */
1384                 /* here.                                                */
1385         if (i < SLEEP_THRESHOLD) {
1386             sched_yield();
1387         } else {
1388             struct timespec ts;
1389         
1390             if (i > 24) i = 24;
1391                         /* Don't wait for more than about 15msecs, even */
1392                         /* under extreme contention.                    */
1393             ts.tv_sec = 0;
1394             ts.tv_nsec = 1 << i;
1395             nanosleep(&ts, 0);
1396         }
1397     }
1398 }
1399
1400 #else  /* !USE_SPINLOCK */
1401 void GC_lock(void)
1402 {
1403 #ifndef NO_PTHREAD_TRYLOCK
1404     if (1 == GC_nprocs || GC_collecting) {
1405         pthread_mutex_lock(&GC_allocate_ml);
1406     } else {
1407         GC_generic_lock(&GC_allocate_ml);
1408     }
1409 #else  /* !NO_PTHREAD_TRYLOCK */
1410     pthread_mutex_lock(&GC_allocate_ml);
1411 #endif /* !NO_PTHREAD_TRYLOCK */
1412 }
1413
1414 #endif /* !USE_SPINLOCK */
1415
1416 #ifdef PARALLEL_MARK
1417
1418 #ifdef GC_ASSERTIONS
1419   unsigned long GC_mark_lock_holder = NO_THREAD;
1420 #endif
1421
1422 #if 0
1423   /* Ugly workaround for a linux threads bug in the final versions      */
1424   /* of glibc2.1.  Pthread_mutex_trylock sets the mutex owner           */
1425   /* field even when it fails to acquire the mutex.  This causes        */
1426   /* pthread_cond_wait to die.  Remove for glibc2.2.                    */
1427   /* According to the man page, we should use                           */
1428   /* PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP, but that isn't actually   */
1429   /* defined.                                                           */
1430   static pthread_mutex_t mark_mutex =
1431         {0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, {0, 0}};
1432 #else
1433   static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
1434 #endif
1435
1436 static pthread_cond_t builder_cv = PTHREAD_COND_INITIALIZER;
1437
1438 void GC_acquire_mark_lock(void)
1439 {
1440 /*
1441     if (pthread_mutex_lock(&mark_mutex) != 0) {
1442         ABORT("pthread_mutex_lock failed");
1443     }
1444 */
1445     GC_generic_lock(&mark_mutex);
1446 #   ifdef GC_ASSERTIONS
1447         GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
1448 #   endif
1449 }
1450
1451 void GC_release_mark_lock(void)
1452 {
1453     GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
1454 #   ifdef GC_ASSERTIONS
1455         GC_mark_lock_holder = NO_THREAD;
1456 #   endif
1457     if (pthread_mutex_unlock(&mark_mutex) != 0) {
1458         ABORT("pthread_mutex_unlock failed");
1459     }
1460 }
1461
1462 /* Collector must wait for a freelist builders for 2 reasons:           */
1463 /* 1) Mark bits may still be getting examined without lock.             */
1464 /* 2) Partial free lists referenced only by locals may not be scanned   */
1465 /*    correctly, e.g. if they contain "pointer-free" objects, since the */
1466 /*    free-list link may be ignored.                                    */
1467 void GC_wait_builder(void)
1468 {
1469     GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
1470 #   ifdef GC_ASSERTIONS
1471         GC_mark_lock_holder = NO_THREAD;
1472 #   endif
1473     if (pthread_cond_wait(&builder_cv, &mark_mutex) != 0) {
1474         ABORT("pthread_cond_wait failed");
1475     }
1476     GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
1477 #   ifdef GC_ASSERTIONS
1478         GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
1479 #   endif
1480 }
1481
1482 void GC_wait_for_reclaim(void)
1483 {
1484     GC_acquire_mark_lock();
1485     while (GC_fl_builder_count > 0) {
1486         GC_wait_builder();
1487     }
1488     GC_release_mark_lock();
1489 }
1490
1491 void GC_notify_all_builder(void)
1492 {
1493     GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
1494     if (pthread_cond_broadcast(&builder_cv) != 0) {
1495         ABORT("pthread_cond_broadcast failed");
1496     }
1497 }
1498
1499 static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
1500
1501 void GC_wait_marker(void)
1502 {
1503     GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self()));
1504 #   ifdef GC_ASSERTIONS
1505         GC_mark_lock_holder = NO_THREAD;
1506 #   endif
1507     if (pthread_cond_wait(&mark_cv, &mark_mutex) != 0) {
1508         ABORT("pthread_cond_wait failed");
1509     }
1510     GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
1511 #   ifdef GC_ASSERTIONS
1512         GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self());
1513 #   endif
1514 }
1515
1516 void GC_notify_all_marker(void)
1517 {
1518     if (pthread_cond_broadcast(&mark_cv) != 0) {
1519         ABORT("pthread_cond_broadcast failed");
1520     }
1521 }
1522
1523 #endif /* PARALLEL_MARK */
1524
1525 # endif /* GC_LINUX_THREADS and friends */
1526