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