source: trunk/gc6.8/pthread_support.c

Last change on this file was 132, checked in by cinc, 19 years ago

Boehm-Demers-Weiser garbage collector. Single-threaded for OS/2.

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