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