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