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.
7 * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
8 * OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
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.
17 * Support code for LinuxThreads, the clone()-based kernel
18 * thread package for Linux which is included in libc6.
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
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.
29 /* DG/UX ix86 support <takis@xfree86.org> */
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
35 * Eric also suggested an alternate basis for a lock implementation in
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) \
44 * + # define GC_LOCK_TAKEN GC_allocate_lock
47 /*#define DEBUG_THREADS 1*/
48 /*#define GC_ASSERTIONS*/
50 # include "private/pthread_support.h"
52 # if defined(GC_PTHREADS) && !defined(GC_SOLARIS_THREADS) \
53 && !defined(GC_WIN32_THREADS)
55 # if defined(GC_HPUX_THREADS) && !defined(USE_PTHREAD_SPECIFIC) \
56 && !defined(USE_COMPILER_TLS)
58 # define USE_PTHREAD_SPECIFIC
59 /* Empirically, as of gcc 3.3, USE_COMPILER_TLS doesn't work. */
61 # define USE_COMPILER_TLS
65 # if defined USE_HPUX_TLS
66 --> Macro replaced by USE_COMPILER_TLS
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
75 # if defined(GC_DGUX386_THREADS) && !defined(_POSIX4A_DRAFT10_SOURCE)
76 # define _POSIX4A_DRAFT10_SOURCE 1
79 # if defined(GC_DGUX386_THREADS) && !defined(_USING_POSIX4A_DRAFT10)
80 # define _USING_POSIX4A_DRAFT10 1
83 # ifdef THREAD_LOCAL_ALLOC
84 # if !defined(USE_PTHREAD_SPECIFIC) && !defined(USE_COMPILER_TLS)
85 # include "private/specific.h"
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...
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;
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;
107 # include <pthread.h>
112 # include <sys/mman.h>
113 # include <sys/time.h>
114 # include <sys/types.h>
115 # include <sys/stat.h>
119 #if defined(GC_DARWIN_THREADS)
120 # include "private/darwin_semaphore.h"
122 # include <semaphore.h>
123 #endif /* !GC_DARWIN_THREADS */
125 #if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS)
126 # include <sys/sysctl.h>
127 #endif /* GC_DARWIN_THREADS */
129 #if defined(GC_NETBSD_THREADS)
130 # include <sys/param.h>
131 # include <sys/sysctl.h>
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 */
147 #ifdef GC_USE_LD_WRAP
148 # define WRAP_FUNC(f) __wrap_##f
149 # define REAL_FUNC(f) __real_##f
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
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
174 static GC_bool parallel_initialized = FALSE;
176 void GC_init_parallel();
178 # if defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
180 /* We don't really support thread-local allocation with DBG_HDRS_ALL */
182 /* work around a dlopen issue (bug #75390), undefs to avoid warnings with redefinitions */
183 #undef PACKAGE_BUGREPORT
185 #undef PACKAGE_STRING
186 #undef PACKAGE_TARNAME
187 #undef PACKAGE_VERSION
188 #include "mono/utils/mono-compiler.h"
191 GC_key_t GC_thread_key;
193 #ifdef USE_COMPILER_TLS
194 static __thread MONO_TLS_FAST void* GC_thread_tls;
197 static GC_bool keys_initialized;
199 #ifdef MONO_DEBUGGER_SUPPORTED
200 #include "include/libgc-mono-debugger.h"
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)
213 for (i = 1; i < NFREELISTS; ++i) {
214 nwords = i * (GRANULARITY/sizeof(word));
217 if ((word)q >= HBLKSIZE) {
218 if (gfl[nwords] == 0) {
222 for (; (word)q >= HBLKSIZE; qptr = &(obj_link(q)), q = *qptr);
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;
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);
240 void GC_delete_gc_thread(pthread_t id, GC_thread gct);
241 void GC_destroy_thread_local(GC_thread p);
243 void GC_thread_deregister_foreign (void *data)
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) {
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);
253 GC_delete_gc_thread(me->id, me);
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)
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");
269 keys_initialized = TRUE;
271 if (0 != GC_setspecific(GC_thread_key, p)) {
272 ABORT("Failed to set thread specific allocation pointers");
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;
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);
289 #ifdef GC_GCJ_SUPPORT
290 extern ptr_t * GC_gcjobjfreelist;
293 /* We hold the allocator lock. */
294 void GC_destroy_thread_local(GC_thread p)
296 /* We currently only do this from the thread itself or from */
297 /* the fork handler for a child process. */
299 GC_ASSERT(GC_getspecific(GC_thread_key) == (void *)p);
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);
308 extern GC_PTR GC_generic_malloc_many();
310 GC_PTR GC_local_malloc(size_t bytes)
312 if (EXPECT(!SMALL_ENOUGH(bytes),0)) {
313 return(GC_malloc(bytes));
315 int index = INDEX_FROM_BYTES(bytes);
318 # if defined(REDIRECT_MALLOC) && !defined(USE_PTHREAD_SPECIFIC)
319 GC_key_t k = GC_thread_key;
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. */
332 tsd = GC_getspecific(GC_thread_key);
333 # ifdef GC_ASSERTIONS
335 GC_ASSERT(tsd == (void *)GC_lookup_thread(pthread_self()));
338 my_fl = ((GC_thread)tsd) -> normal_freelists + index;
340 if (EXPECT((word)my_entry >= HBLKSIZE, 1)) {
341 ptr_t next = obj_link(my_entry);
342 GC_PTR result = (GC_PTR)my_entry;
344 obj_link(my_entry) = 0;
345 PREFETCH_FOR_WRITE(next);
347 } else if ((word)my_entry - 1 < DIRECT_GRANULES) {
348 *my_fl = my_entry + index + 1;
349 return GC_malloc(bytes);
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);
358 GC_PTR GC_local_malloc_atomic(size_t bytes)
360 if (EXPECT(!SMALL_ENOUGH(bytes), 0)) {
361 return(GC_malloc_atomic(bytes));
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;
368 if (EXPECT((word)my_entry >= HBLKSIZE, 1)) {
369 GC_PTR result = (GC_PTR)my_entry;
370 *my_fl = obj_link(my_entry);
372 } else if ((word)my_entry - 1 < DIRECT_GRANULES) {
373 *my_fl = my_entry + index + 1;
374 return GC_malloc_atomic(bytes);
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 */
380 if (*my_fl == 0) return GC_oom_fn(bytes);
381 return GC_local_malloc_atomic(bytes);
386 #ifdef GC_GCJ_SUPPORT
388 #include "include/gc_gcj.h"
391 extern GC_bool GC_gcj_malloc_initialized;
394 extern int GC_gcj_kind;
396 GC_PTR GC_local_gcj_malloc(size_t bytes,
397 void * ptr_to_struct_containing_descr)
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);
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 */
419 /* A memory barrier is probably never needed, since the */
420 /* action of stopping this thread will cause prior writes */
422 GC_ASSERT(((void * volatile *)result)[1] == 0);
423 *(void * volatile *)result = ptr_to_struct_containing_descr;
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);
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);
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)
443 ptr_t * my_fl = ((GC_thread)GC_getspecific(GC_thread_key))
444 -> gcj_freelists + lw;
445 ptr_t my_entry = *my_fl;
447 GC_ASSERT(GC_gcj_malloc_initialized);
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 */
461 /* A memory barrier is probably never needed, since the */
462 /* action of stopping this thread will cause prior writes */
464 GC_ASSERT(((void * volatile *)result)[1] == 0);
465 *(void * volatile *)result = ptr_to_struct_containing_descr;
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);
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);
479 #endif /* GC_GCJ_SUPPORT */
481 # else /* !THREAD_LOCAL_ALLOC && !DBG_HDRS_ALL */
483 # define GC_destroy_thread_local(t)
485 # endif /* !THREAD_LOCAL_ALLOC */
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
495 We no longer do this, since this code is now portable enough that it might
496 actually work for something else.
498 void (*dummy_var_to_force_linux_threads)() = pthread_kill_other_threads_np;
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 ... */
508 # define MAX_MARKERS 16
511 static ptr_t marker_sp[MAX_MARKERS] = {0};
513 void * GC_mark_thread(void * id)
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 */
528 my_mark_no = GC_mark_no;
530 # ifdef DEBUG_THREADS
531 GC_printf1("Starting mark helper for mark number %ld\n", my_mark_no);
533 GC_help_marker(my_mark_no);
537 extern long GC_markers; /* Number of mark threads we would */
538 /* like to have. Includes the */
539 /* initiating thread. */
541 pthread_t GC_mark_threads[MAX_MARKERS];
543 #define PTHREAD_CREATE REAL_FUNC(pthread_create)
545 static void start_mark_threads()
550 if (GC_markers > MAX_MARKERS) {
551 WARN("Limiting number of mark threads\n", 0);
552 GC_markers = MAX_MARKERS;
554 if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed");
556 if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED))
557 ABORT("pthread_attr_setdetachstate failed");
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 */
563 # define MIN_STACK_SIZE (8*HBLKSIZE*sizeof(word))
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");
575 # endif /* HPUX || GC_DGUX386_THREADS */
577 if (GC_print_stats) {
578 GC_printf1("Starting %ld marker threads\n", GC_markers - 1);
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);
589 #else /* !PARALLEL_MARK */
591 static __inline__ void start_mark_threads()
595 #endif /* !PARALLEL_MARK */
597 GC_bool GC_thr_initialized = FALSE;
599 volatile GC_thread GC_threads[THREAD_TABLE_SZ];
602 * gcc-3.3.6 miscompiles the &GC_thread_key+sizeof(&GC_thread_key) expression so
603 * put it into a separate function.
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))
608 return (unsigned char*)&GC_thread_key;
611 void GC_push_thread_structures GC_PROTO((void))
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));
622 void GC_push_thread_structures GC_PROTO((void))
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));
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)
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 */
659 #endif /* THREAD_LOCAL_ALLOC */
661 static struct GC_Thread_Rep first_thread;
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)
667 int hv = ((word)id) % THREAD_TABLE_SZ;
669 static GC_bool first_thread_used = FALSE;
671 if (!first_thread_used) {
672 result = &first_thread;
673 first_thread_used = TRUE;
675 result = (struct GC_Thread_Rep *)
676 GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
678 if (result == 0) return(0);
680 result -> next = GC_threads[hv];
681 GC_threads[hv] = result;
682 GC_ASSERT(result -> flags == 0 && result -> thread_blocked == 0);
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)
691 int hv = ((word)id) % THREAD_TABLE_SZ;
692 register GC_thread p = GC_threads[hv];
693 register GC_thread prev = 0;
695 while (!pthread_equal(p -> id, id)) {
700 GC_threads[hv] = p -> next;
702 prev -> next = p -> next;
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);
709 #ifdef GC_DARWIN_THREADS
710 mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
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)
722 int hv = ((word)id) % THREAD_TABLE_SZ;
723 register GC_thread p = GC_threads[hv];
724 register GC_thread prev = 0;
731 GC_threads[hv] = p -> next;
733 prev -> next = p -> next;
736 #ifdef GC_DARWIN_THREADS
737 mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread);
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 */
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)
751 int hv = ((word)id) % THREAD_TABLE_SZ;
752 register GC_thread p = GC_threads[hv];
754 while (p != 0 && !pthread_equal(p -> id, id)) p = p -> next;
758 int GC_thread_is_registered (void)
763 ptr = (void *)GC_lookup_thread(pthread_self());
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)
776 pthread_t self = pthread_self();
778 GC_thread p, next, me;
780 for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) {
782 for (p = GC_threads[hv]; 0 != p; p = next) {
784 if (p -> id == self) {
788 # ifdef THREAD_LOCAL_ALLOC
789 if (!(p -> flags & FINISHED)) {
790 GC_destroy_thread_local(p);
792 # endif /* THREAD_LOCAL_ALLOC */
793 if (p != &first_thread) GC_INTERNAL_FREE(p);
800 #endif /* HANDLE_FORK */
802 #ifdef USE_PROC_FOR_LIBRARIES
803 int GC_segment_is_thread_stack(ptr_t lo, ptr_t hi)
808 # ifdef PARALLEL_MARK
809 for (i = 0; i < GC_markers; ++i) {
810 if (marker_sp[i] > lo & marker_sp[i] < hi) return 1;
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;
826 #endif /* USE_PROC_FOR_LIBRARIES */
828 #ifdef GC_LINUX_THREADS
829 /* Return the number of processors, or i<= 0 if it can't be determined. */
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 */
839 char stat_buf[STAT_BUF_SIZE];
842 /* Some old kernels only have a single "cpu nnnn ..." */
843 /* entry in /proc/stat. We identify those as */
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);
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;
862 #endif /* GC_LINUX_THREADS */
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 */
869 extern GC_bool GC_collection_in_progress();
870 void GC_wait_for_gc_completion(GC_bool wait_for_all)
872 if (GC_incremental && GC_collection_in_progress()) {
873 int old_gc_no = GC_gc_no;
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)) {
880 GC_in_thread_creation = TRUE;
881 GC_collect_a_little_inner(1);
882 GC_in_thread_creation = FALSE;
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. */
900 /* Called before a fork() */
901 void GC_fork_prepare_proc(void)
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. */
911 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
912 GC_wait_for_reclaim();
914 GC_wait_for_gc_completion(TRUE);
915 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
916 GC_acquire_mark_lock();
920 /* Called in parent after a fork() */
921 void GC_fork_parent_proc(void)
923 # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
924 GC_release_mark_lock();
929 /* Called in child after a fork() */
930 void GC_fork_child_proc(void)
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();
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. */
942 # endif /* PARALLEL_MARK */
945 #endif /* HANDLE_FORK */
947 #if defined(GC_DGUX386_THREADS)
948 /* Return the number of processors, or i<= 0 if it can't be determined. */
951 /* <takis@XFree86.Org> */
953 struct dg_sys_info_pm_info pm_sysinfo;
956 status = dg_sys_info((long int *) &pm_sysinfo,
957 DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION);
959 /* set -1 for error */
963 numCpus = pm_sysinfo.idle_vp_count;
965 # ifdef DEBUG_THREADS
966 GC_printf1("Number of active CPUs in this system: %d\n", numCpus);
970 #endif /* GC_DGUX386_THREADS */
972 /* We hold the allocation lock. */
975 # ifndef GC_DARWIN_THREADS
980 if (GC_thr_initialized) return;
981 GC_thr_initialized = TRUE;
984 /* Prepare for a possible fork. */
985 pthread_atfork(GC_fork_prepare_proc, GC_fork_parent_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();
993 t -> stop_info.stack_ptr = (ptr_t)(&dummy);
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);
1003 /* Set GC_nprocs. */
1005 char * nprocs_string = GETENV("GC_NPROCS");
1007 if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string);
1009 if (GC_nprocs <= 0) {
1010 # if defined(GC_HPUX_THREADS)
1011 GC_nprocs = pthread_num_processors_np();
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;
1017 # if defined(GC_IRIX_THREADS)
1018 GC_nprocs = sysconf(_SC_NPROC_ONLN);
1019 if (GC_nprocs <= 0) GC_nprocs = 1;
1021 # if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS) || defined(GC_NETBSD_THREADS)
1023 size_t len = sizeof(ncpus);
1024 sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0);
1027 # if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS)
1028 GC_nprocs = GC_get_nprocs();
1031 if (GC_nprocs <= 0) {
1032 WARN("GC_get_nprocs() returned %ld\n", GC_nprocs);
1034 # ifdef PARALLEL_MARK
1038 # ifdef PARALLEL_MARK
1040 char * markers_string = GETENV("GC_MARKERS");
1041 if (markers_string != NULL) {
1042 GC_markers = atoi(markers_string);
1044 GC_markers = GC_nprocs;
1049 # ifdef PARALLEL_MARK
1051 if (GC_print_stats) {
1052 GC_printf2("Number of processors = %ld, "
1053 "number of marker threads = %ld\n", GC_nprocs, GC_markers);
1056 if (GC_markers == 1) {
1057 GC_parallel = FALSE;
1059 if (GC_print_stats) {
1060 GC_printf0("Single marker thread, turning off parallel marking\n");
1065 /* Disable true incremental collection, but generational is OK. */
1066 GC_time_limit = GC_TIME_UNLIMITED;
1068 /* If we are using a parallel marker, actually start helper threads. */
1069 if (GC_parallel) start_mark_threads();
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()
1081 if (parallel_initialized) return;
1082 parallel_initialized = TRUE;
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)
1089 GC_init_thread_local(GC_lookup_thread(pthread_self()));
1095 #if !defined(GC_DARWIN_THREADS)
1096 int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, sigset_t *oset)
1098 sigset_t fudged_set;
1100 if (set != NULL && (how == SIG_BLOCK || how == SIG_SETMASK)) {
1102 sigdelset(&fudged_set, SIG_SUSPEND);
1105 return(REAL_FUNC(pthread_sigmask)(how, set, oset));
1107 #endif /* !GC_DARWIN_THREADS */
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. */
1114 void GC_start_blocking(void) {
1115 # define SP_SLOP 128
1118 me = GC_lookup_thread(pthread_self());
1119 GC_ASSERT(!(me -> thread_blocked));
1121 me -> stop_info.stack_ptr = (ptr_t)GC_save_regs_in_stack();
1123 # ifndef GC_DARWIN_THREADS
1124 me -> stop_info.stack_ptr = (ptr_t)GC_approx_sp();
1128 me -> backing_store_ptr = (ptr_t)GC_save_regs_in_stack() + SP_SLOP;
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;
1136 me -> stop_info.stack_ptr -= SP_SLOP;
1139 me -> thread_blocked = TRUE;
1143 void GC_end_blocking(void) {
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;
1152 #if defined(GC_DGUX386_THREADS)
1153 #define __d10_sleep sleep
1154 #endif /* GC_DGUX386_THREADS */
1156 /* A wrapper for the standard C sleep function */
1157 int WRAP_FUNC(sleep) (unsigned int seconds)
1161 GC_start_blocking();
1162 result = REAL_FUNC(sleep)(seconds);
1168 void *(*start_routine)(void *);
1171 sem_t registered; /* 1 ==> in our thread table, but */
1172 /* parent hasn't yet noticed. */
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)
1185 me = GC_lookup_thread(pthread_self());
1186 GC_destroy_thread_local(me);
1187 if (me -> flags & DETACHED) {
1188 GC_delete_thread(pthread_self());
1190 me -> flags |= FINISHED;
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);
1196 /* The following may run the GC from "nonexistent" thread. */
1197 GC_wait_for_gc_completion(FALSE);
1201 int WRAP_FUNC(pthread_join)(pthread_t thread, void **retval)
1204 GC_thread thread_gc_id;
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. */
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;
1225 /* Here the pthread thread id may have been recycled. */
1226 GC_delete_gc_thread(thread, thread_gc_id);
1233 WRAP_FUNC(pthread_detach)(pthread_t thread)
1236 GC_thread thread_gc_id;
1239 thread_gc_id = GC_lookup_thread(thread);
1241 result = REAL_FUNC(pthread_detach)(thread);
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);
1254 GC_bool GC_in_thread_creation = FALSE;
1256 typedef void *(*ThreadStartFn)(void *);
1257 void * GC_start_routine_head(void * arg, void *base_addr,
1258 ThreadStartFn *start, void **start_arg )
1260 struct start_info * si = arg;
1263 pthread_t my_pthread;
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);
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();
1278 me -> stop_info.stack_ptr = 0;
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;
1291 /* Needs to be plausible, since an asynchronous stack mark */
1292 /* should not crash. */
1294 me -> stack_end = (ptr_t)((word)(base_addr) & ~(GC_page_size - 1));
1295 me -> stop_info.stack_ptr = me -> stack_end + 0x10;
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. */
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. */
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);
1311 if (start) *start = si -> start_routine;
1312 if (start_arg) *start_arg = si -> arg;
1314 sem_post(&(si -> registered)); /* Last action on si. */
1315 /* OK to deallocate. */
1316 # if defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL)
1318 GC_init_thread_local(me);
1325 int GC_thread_register_foreign (void *base_addr)
1327 struct start_info si = { 0, }; /* stacked for legibility & locking */
1330 # ifdef DEBUG_THREADS
1331 GC_printf1( "GC_thread_register_foreign %p\n", &si );
1334 si.flags = FOREIGN_THREAD;
1336 if (!parallel_initialized) GC_init_parallel();
1338 if (!GC_thr_initialized) GC_thr_init();
1342 me = GC_start_routine_head(&si, base_addr, NULL, NULL);
1347 void * GC_start_routine(void * arg)
1350 struct start_info * si = arg;
1353 ThreadStartFn start;
1356 me = GC_start_routine_head (arg, &dummy, &start, &start_arg);
1358 pthread_cleanup_push(GC_thread_exit_proc, 0);
1359 # ifdef DEBUG_THREADS
1360 GC_printf1("start_routine = 0x%lx\n", start);
1362 result = (*start)(start_arg);
1364 GC_printf1("Finishing thread 0x%x\n", pthread_self());
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 */
1375 WRAP_FUNC(pthread_create)(pthread_t *new_thread,
1376 const pthread_attr_t *attr,
1377 void *(*start_routine)(void *), void *arg)
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. */
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. */
1391 si = (struct start_info *)GC_INTERNAL_MALLOC(sizeof(struct start_info),
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;
1400 if (!GC_thr_initialized) GC_thr_init();
1401 # ifdef GC_ASSERTIONS
1405 pthread_attr_t my_attr;
1406 pthread_attr_init(&my_attr);
1407 pthread_attr_getstacksize(&my_attr, &stack_size);
1409 pthread_attr_getstacksize(attr, &stack_size);
1411 # ifdef PARALLEL_MARK
1412 GC_ASSERT(stack_size >= (8*HBLKSIZE*sizeof(word)));
1414 /* FreeBSD-5.3/Alpha: default pthread stack is 64K, */
1415 /* HBLKSIZE=8192, sizeof(word)=8 */
1416 GC_ASSERT(stack_size >= 65536);
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. */
1424 detachstate = PTHREAD_CREATE_JOINABLE;
1426 pthread_attr_getdetachstate(attr, &detachstate);
1428 if (PTHREAD_CREATE_DETACHED == detachstate) my_flags |= DETACHED;
1429 si -> flags = my_flags;
1431 # ifdef DEBUG_THREADS
1432 GC_printf1("About to start new thread from thread 0x%X\n",
1436 result = REAL_FUNC(pthread_create)(new_thread, attr, GC_start_routine, si);
1438 # ifdef DEBUG_THREADS
1439 GC_printf1("Started thread 0x%X\n", *new_thread);
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. */
1446 while (0 != sem_wait(&(si -> registered))) {
1447 if (EINTR != errno) ABORT("sem_wait failed");
1450 sem_destroy(&(si -> registered));
1452 GC_INTERNAL_FREE(si);
1458 #ifdef GENERIC_COMPARE_AND_SWAP
1459 pthread_mutex_t GC_compare_and_swap_lock = PTHREAD_MUTEX_INITIALIZER;
1461 GC_bool GC_compare_and_exchange(volatile GC_word *addr,
1462 GC_word old, GC_word new_val)
1465 pthread_mutex_lock(&GC_compare_and_swap_lock);
1472 pthread_mutex_unlock(&GC_compare_and_swap_lock);
1476 GC_word GC_atomic_add(volatile GC_word *addr, GC_word how_much)
1479 pthread_mutex_lock(&GC_compare_and_swap_lock);
1481 *addr = old + how_much;
1482 pthread_mutex_unlock(&GC_compare_and_swap_lock);
1486 #endif /* GENERIC_COMPARE_AND_SWAP */
1487 /* Spend a few cycles in a way that can't introduce contention with */
1488 /* othre threads. */
1492 # if !defined(__GNUC__) || defined(__INTEL_COMPILER)
1493 volatile word dummy = 0;
1496 for (i = 0; i < 10; ++i) {
1497 # if defined(__GNUC__) && !defined(__INTEL_COMPILER)
1498 __asm__ __volatile__ (" " : : : "memory");
1500 /* Something that's unlikely to be optimized away. */
1506 #define SPIN_MAX 128 /* Maximum number of calls to GC_pause before */
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. */
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 */
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. */
1533 unsigned long GC_spin_count = 0;
1534 unsigned long GC_block_count = 0;
1535 unsigned long GC_unlocked_count = 0;
1538 void GC_generic_lock(pthread_mutex_t * lock)
1540 #ifndef NO_PTHREAD_TRYLOCK
1541 unsigned pause_length = 1;
1544 if (0 == pthread_mutex_trylock(lock)) {
1546 ++GC_unlocked_count;
1550 for (; pause_length <= SPIN_MAX; pause_length <<= 1) {
1551 for (i = 0; i < pause_length; ++i) {
1554 switch(pthread_mutex_trylock(lock)) {
1563 ABORT("Unexpected error from pthread_mutex_trylock");
1566 #endif /* !NO_PTHREAD_TRYLOCK */
1570 pthread_mutex_lock(lock);
1573 #endif /* !USE_SPIN_LOCK || PARALLEL_MARK */
1575 #if defined(USE_SPIN_LOCK)
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 ... */
1581 volatile unsigned int GC_allocate_lock = 0;
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;
1594 if (!GC_test_and_set(&GC_allocate_lock)) {
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) {
1605 if (!GC_test_and_set(&GC_allocate_lock)) {
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.
1613 spin_max = high_spin_max;
1617 /* We are probably being scheduled against the other process. Sleep. */
1618 spin_max = low_spin_max;
1621 if (!GC_test_and_set(&GC_allocate_lock)) {
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 */
1631 if (i < SLEEP_THRESHOLD) {
1637 /* Don't wait for more than about 15msecs, even */
1638 /* under extreme contention. */
1640 ts.tv_nsec = 1 << i;
1646 #else /* !USE_SPINLOCK */
1649 #ifndef NO_PTHREAD_TRYLOCK
1650 if (1 == GC_nprocs || GC_collecting) {
1651 pthread_mutex_lock(&GC_allocate_ml);
1653 GC_generic_lock(&GC_allocate_ml);
1655 #else /* !NO_PTHREAD_TRYLOCK */
1656 pthread_mutex_lock(&GC_allocate_ml);
1657 #endif /* !NO_PTHREAD_TRYLOCK */
1660 #endif /* !USE_SPINLOCK */
1662 #if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC)
1664 #ifdef GC_ASSERTIONS
1665 pthread_t GC_mark_lock_holder = NO_THREAD;
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 */
1676 static pthread_mutex_t mark_mutex =
1677 {0, 0, 0, PTHREAD_MUTEX_ERRORCHECK_NP, {0, 0}};
1679 static pthread_mutex_t mark_mutex = PTHREAD_MUTEX_INITIALIZER;
1682 static pthread_cond_t builder_cv = PTHREAD_COND_INITIALIZER;
1684 void GC_acquire_mark_lock()
1687 if (pthread_mutex_lock(&mark_mutex) != 0) {
1688 ABORT("pthread_mutex_lock failed");
1691 GC_generic_lock(&mark_mutex);
1692 # ifdef GC_ASSERTIONS
1693 GC_mark_lock_holder = pthread_self();
1697 void GC_release_mark_lock()
1699 GC_ASSERT(GC_mark_lock_holder == pthread_self());
1700 # ifdef GC_ASSERTIONS
1701 GC_mark_lock_holder = NO_THREAD;
1703 if (pthread_mutex_unlock(&mark_mutex) != 0) {
1704 ABORT("pthread_mutex_unlock failed");
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()
1715 GC_ASSERT(GC_mark_lock_holder == pthread_self());
1716 # ifdef GC_ASSERTIONS
1717 GC_mark_lock_holder = NO_THREAD;
1719 if (pthread_cond_wait(&builder_cv, &mark_mutex) != 0) {
1720 ABORT("pthread_cond_wait failed");
1722 GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
1723 # ifdef GC_ASSERTIONS
1724 GC_mark_lock_holder = pthread_self();
1728 void GC_wait_for_reclaim()
1730 GC_acquire_mark_lock();
1731 while (GC_fl_builder_count > 0) {
1734 GC_release_mark_lock();
1737 void GC_notify_all_builder()
1739 GC_ASSERT(GC_mark_lock_holder == pthread_self());
1740 if (pthread_cond_broadcast(&builder_cv) != 0) {
1741 ABORT("pthread_cond_broadcast failed");
1745 #endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */
1747 #ifdef PARALLEL_MARK
1749 static pthread_cond_t mark_cv = PTHREAD_COND_INITIALIZER;
1751 void GC_wait_marker()
1753 GC_ASSERT(GC_mark_lock_holder == pthread_self());
1754 # ifdef GC_ASSERTIONS
1755 GC_mark_lock_holder = NO_THREAD;
1757 if (pthread_cond_wait(&mark_cv, &mark_mutex) != 0) {
1758 ABORT("pthread_cond_wait failed");
1760 GC_ASSERT(GC_mark_lock_holder == NO_THREAD);
1761 # ifdef GC_ASSERTIONS
1762 GC_mark_lock_holder = pthread_self();
1766 void GC_notify_all_marker()
1768 if (pthread_cond_broadcast(&mark_cv) != 0) {
1769 ABORT("pthread_cond_broadcast failed");
1773 #endif /* PARALLEL_MARK */
1775 # endif /* GC_LINUX_THREADS and friends */