Moved abi stuff into md-abi.h
[cacao.git] / src / boehm-gc / solaris_threads.c
1 /* 
2  * Copyright (c) 1994 by Xerox Corporation.  All rights reserved.
3  *
4  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
5  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
6  *
7  * Permission is hereby granted to use or copy this program
8  * for any purpose,  provided the above notices are retained on all copies.
9  * Permission to modify the code and to distribute modified code is granted,
10  * provided the above notices are retained, and a notice that the code was
11  * modified is included with the above copyright notice.
12  */
13 /*
14  * Support code for Solaris threads.  Provides functionality we wish Sun
15  * had provided.  Relies on some information we probably shouldn't rely on.
16  */
17 /* Boehm, September 14, 1994 4:44 pm PDT */
18
19 #include "config.h"
20
21 # if defined(GC_SOLARIS_THREADS) || defined(GC_SOLARIS_PTHREADS) \
22      || defined(GC_THREADS)
23 #   include "private/gc_priv.h"
24 # endif
25
26 # if defined(GC_SOLARIS_THREADS) || defined(GC_SOLARIS_PTHREADS)
27 # include "private/solaris_threads.h"
28 # include <thread.h>
29 # include <synch.h>
30 # include <signal.h>
31 # include <fcntl.h>
32 # include <sys/types.h>
33 # include <sys/mman.h>
34 # include <sys/time.h>
35 # include <sys/resource.h>
36 # include <sys/stat.h>
37 # include <sys/syscall.h>
38 # include <sys/procfs.h>
39 # include <sys/lwp.h>
40 # include <sys/reg.h>
41 # define _CLASSIC_XOPEN_TYPES
42 # include <unistd.h>
43 # include <errno.h>
44
45 #ifdef HANDLE_FORK
46   --> Not yet supported.  Try porting the code from linux_threads.c.
47 #endif
48
49 /*
50  * This is the default size of the LWP arrays. If there are more LWPs
51  * than this when a stop-the-world GC happens, set_max_lwps will be
52  * called to cope.
53  * This must be higher than the number of LWPs at startup time.
54  * The threads library creates a thread early on, so the min. is 3
55  */
56 # define DEFAULT_MAX_LWPS       4
57
58 #undef thr_join
59 #undef thr_create
60 #undef thr_suspend
61 #undef thr_continue
62
63 cond_t GC_prom_join_cv;         /* Broadcast when any thread terminates */
64 cond_t GC_create_cv;            /* Signalled when a new undetached      */
65                                 /* thread starts.                       */
66                                 
67
68 #ifdef MMAP_STACKS
69 static int GC_zfd;
70 #endif /* MMAP_STACKS */
71
72 /* We use the allocation lock to protect thread-related data structures. */
73
74 /* We stop the world using /proc primitives.  This makes some   */
75 /* minimal assumptions about the threads implementation.        */
76 /* We don't play by the rules, since the rules make this        */
77 /* impossible (as of Solaris 2.3).  Also note that as of        */
78 /* Solaris 2.3 the various thread and lwp suspension            */
79 /* primitives failed to stop threads by the time the request    */
80 /* is completed.                                                */
81
82
83 static sigset_t old_mask;
84
85 /* Sleep for n milliseconds, n < 1000   */
86 void GC_msec_sleep(int n)
87 {
88     struct timespec ts;
89                             
90     ts.tv_sec = 0;
91     ts.tv_nsec = 1000000*n;
92     if (syscall(SYS_nanosleep, &ts, 0) < 0) {
93         ABORT("nanosleep failed");
94     }
95 }
96 /* Turn off preemption;  gross but effective.           */
97 /* Caller has allocation lock.                          */
98 /* Actually this is not needed under Solaris 2.3 and    */
99 /* 2.4, but hopefully that'll change.                   */
100 void preempt_off()
101 {
102     sigset_t set;
103
104     (void)sigfillset(&set);
105     sigdelset(&set, SIGABRT);
106     syscall(SYS_sigprocmask, SIG_SETMASK, &set, &old_mask);
107 }
108
109 void preempt_on()
110 {
111     syscall(SYS_sigprocmask, SIG_SETMASK, &old_mask, NULL);
112 }
113
114 int GC_main_proc_fd = -1;
115
116
117 struct lwp_cache_entry {
118     lwpid_t lc_id;
119     int lc_descr;       /* /proc file descriptor.       */
120 }  GC_lwp_cache_default[DEFAULT_MAX_LWPS];
121
122 static int max_lwps = DEFAULT_MAX_LWPS;
123 static struct lwp_cache_entry *GC_lwp_cache = GC_lwp_cache_default;
124
125 static prgregset_t GC_lwp_registers_default[DEFAULT_MAX_LWPS];
126 static prgregset_t *GC_lwp_registers = GC_lwp_registers_default;
127
128 /* Return a file descriptor for the /proc entry corresponding   */
129 /* to the given lwp.  The file descriptor may be stale if the   */
130 /* lwp exited and a new one was forked.                         */
131 static int open_lwp(lwpid_t id)
132 {
133     int result;
134     static int next_victim = 0;
135     register int i;
136     
137     for (i = 0; i < max_lwps; i++) {
138         if (GC_lwp_cache[i].lc_id == id) return(GC_lwp_cache[i].lc_descr);
139     }
140     result = syscall(SYS_ioctl, GC_main_proc_fd, PIOCOPENLWP, &id);
141     /*
142      * If PIOCOPENLWP fails, try closing fds in the cache until it succeeds.
143      */
144     if (result < 0 && errno == EMFILE) {
145             for (i = 0; i < max_lwps; i++) {
146                 if (GC_lwp_cache[i].lc_id != 0) {
147                         (void)syscall(SYS_close, GC_lwp_cache[i].lc_descr);
148                         result = syscall(SYS_ioctl, GC_main_proc_fd, PIOCOPENLWP, &id);
149                         if (result >= 0 || (result < 0 && errno != EMFILE))
150                                 break;
151                 }
152             }
153     }
154     if (result < 0) {
155         if (errno == EMFILE) {
156                 ABORT("Too many open files");
157         }
158         return(-1) /* exited? */;
159     }
160     if (GC_lwp_cache[next_victim].lc_id != 0)
161         (void)syscall(SYS_close, GC_lwp_cache[next_victim].lc_descr);
162     GC_lwp_cache[next_victim].lc_id = id;
163     GC_lwp_cache[next_victim].lc_descr = result;
164     if (++next_victim >= max_lwps)
165         next_victim = 0;
166     return(result);
167 }
168
169 static void uncache_lwp(lwpid_t id)
170 {
171     register int i;
172     
173     for (i = 0; i < max_lwps; i++) {
174         if (GC_lwp_cache[i].lc_id == id) {
175             (void)syscall(SYS_close, GC_lwp_cache[id].lc_descr);
176             GC_lwp_cache[i].lc_id = 0;
177             break;
178         }
179     }
180 }
181         /* Sequence of current lwp ids  */
182 static lwpid_t GC_current_ids_default[DEFAULT_MAX_LWPS + 1];
183 static lwpid_t *GC_current_ids = GC_current_ids_default;
184
185         /* Temporary used below (can be big if large number of LWPs) */
186 static lwpid_t last_ids_default[DEFAULT_MAX_LWPS + 1];
187 static lwpid_t *last_ids = last_ids_default;
188
189
190 #define ROUNDUP(n)    WORDS_TO_BYTES(ROUNDED_UP_WORDS(n))
191
192 static void set_max_lwps(GC_word n)
193 {
194     char *mem;
195     char *oldmem;
196     int required_bytes = ROUNDUP(n * sizeof(struct lwp_cache_entry))
197         + ROUNDUP(n * sizeof(prgregset_t))
198         + ROUNDUP((n + 1) * sizeof(lwpid_t))
199         + ROUNDUP((n + 1) * sizeof(lwpid_t));
200
201     GC_expand_hp_inner(divHBLKSZ((word)required_bytes));
202     oldmem = mem = GC_scratch_alloc(required_bytes);
203     if (0 == mem) ABORT("No space for lwp data structures");
204
205     /*
206      * We can either flush the old lwp cache or copy it over. Do the latter.
207      */
208     memcpy(mem, GC_lwp_cache, max_lwps * sizeof(struct lwp_cache_entry));
209     GC_lwp_cache = (struct lwp_cache_entry*)mem;
210     mem += ROUNDUP(n * sizeof(struct lwp_cache_entry));
211
212     BZERO(GC_lwp_registers, max_lwps * sizeof(GC_lwp_registers[0]));
213     GC_lwp_registers = (prgregset_t *)mem;
214     mem += ROUNDUP(n * sizeof(prgregset_t));
215
216
217     GC_current_ids = (lwpid_t *)mem;
218     mem += ROUNDUP((n + 1) * sizeof(lwpid_t));
219
220     last_ids = (lwpid_t *)mem;
221     mem += ROUNDUP((n + 1)* sizeof(lwpid_t));
222
223     if (mem > oldmem + required_bytes)
224         ABORT("set_max_lwps buffer overflow");
225
226     max_lwps = n;
227 }
228
229
230 /* Stop all lwps in process.  Assumes preemption is off.        */
231 /* Caller has allocation lock (and any other locks he may       */
232 /* need).                                                       */
233 static void stop_all_lwps()
234 {
235     int lwp_fd;
236     char buf[30];
237     prstatus_t status;
238     register int i;
239     GC_bool changed;
240     lwpid_t me = _lwp_self();
241
242     if (GC_main_proc_fd == -1) {
243         sprintf(buf, "/proc/%d", getpid());
244         GC_main_proc_fd = syscall(SYS_open, buf, O_RDONLY);
245         if (GC_main_proc_fd < 0) {
246                 if (errno == EMFILE)
247                         ABORT("/proc open failed: too many open files");
248                 GC_printf1("/proc open failed: errno %d", errno);
249                 abort();
250         }
251     }
252     BZERO(GC_lwp_registers, sizeof (prgregset_t) * max_lwps);
253     for (i = 0; i < max_lwps; i++)
254         last_ids[i] = 0;
255     for (;;) {
256     if (syscall(SYS_ioctl, GC_main_proc_fd, PIOCSTATUS, &status) < 0)
257         ABORT("Main PIOCSTATUS failed");
258         if (status.pr_nlwp < 1)
259                 ABORT("Invalid number of lwps returned by PIOCSTATUS");
260         if (status.pr_nlwp >= max_lwps) {
261                 set_max_lwps(status.pr_nlwp*2 + 10);
262                 /*
263                  * The data in the old GC_current_ids and
264                  * GC_lwp_registers has been trashed. Cleaning out last_ids
265                  * will make sure every LWP gets re-examined.
266                  */
267                 for (i = 0; i < max_lwps; i++)
268                         last_ids[i] = 0;
269                 continue;
270     }
271         if (syscall(SYS_ioctl, GC_main_proc_fd, PIOCLWPIDS, GC_current_ids) < 0)
272             ABORT("PIOCLWPIDS failed");
273         changed = FALSE;
274         for (i = 0; GC_current_ids[i] != 0 && i < max_lwps; i++) {
275             if (GC_current_ids[i] != last_ids[i]) {
276                 changed = TRUE;
277                 if (GC_current_ids[i] != me) {
278                     /* PIOCSTOP doesn't work without a writable         */
279                     /* descriptor.  And that makes the process          */
280                     /* undebuggable.                                    */
281                     if (_lwp_suspend(GC_current_ids[i]) < 0) {
282                         /* Could happen if the lwp exited */
283                         uncache_lwp(GC_current_ids[i]);
284                         GC_current_ids[i] = me; /* ignore */
285                     }
286                 }
287             }
288         }
289         /*
290          * In the unlikely event something does a fork between the
291          * PIOCSTATUS and the PIOCLWPIDS. 
292          */
293         if (i >= max_lwps)
294                 continue;
295         /* All lwps in GC_current_ids != me have been suspended.  Note  */
296         /* that _lwp_suspend is idempotent.                             */
297         for (i = 0; GC_current_ids[i] != 0; i++) {
298             if (GC_current_ids[i] != last_ids[i]) {
299                 if (GC_current_ids[i] != me) {
300                     lwp_fd = open_lwp(GC_current_ids[i]);
301                     if (lwp_fd == -1)
302                     {
303                             GC_current_ids[i] = me;
304                             continue;
305                     }
306                     /* LWP should be stopped.  Empirically it sometimes */
307                     /* isn't, and more frequently the PR_STOPPED flag   */
308                     /* is not set.  Wait for PR_STOPPED.                */
309                     if (syscall(SYS_ioctl, lwp_fd,
310                                 PIOCSTATUS, &status) < 0) {
311                         /* Possible if the descriptor was stale, or */
312                         /* we encountered the 2.3 _lwp_suspend bug. */
313                         uncache_lwp(GC_current_ids[i]);
314                         GC_current_ids[i] = me; /* handle next time. */
315                     } else {
316                         while (!(status.pr_flags & PR_STOPPED)) {
317                             GC_msec_sleep(1);
318                             if (syscall(SYS_ioctl, lwp_fd,
319                                         PIOCSTATUS, &status) < 0) {
320                                 ABORT("Repeated PIOCSTATUS failed");
321                             }
322                             if (status.pr_flags & PR_STOPPED) break;
323                             
324                             GC_msec_sleep(20);
325                             if (syscall(SYS_ioctl, lwp_fd,
326                                         PIOCSTATUS, &status) < 0) {
327                                 ABORT("Repeated PIOCSTATUS failed");
328                             }
329                         }
330                         if (status.pr_who !=  GC_current_ids[i]) {
331                                 /* can happen if thread was on death row */
332                                 uncache_lwp(GC_current_ids[i]);
333                                 GC_current_ids[i] = me; /* handle next time. */
334                                 continue;       
335                         }
336                         /* Save registers where collector can */
337                         /* find them.                     */
338                             BCOPY(status.pr_reg, GC_lwp_registers[i],
339                                   sizeof (prgregset_t));
340                     }
341                 }
342             }
343         }
344         if (!changed) break;
345         for (i = 0; i < max_lwps; i++) last_ids[i] = GC_current_ids[i];
346     }
347 }
348
349 /* Restart all lwps in process.  Assumes preemption is off.     */
350 static void restart_all_lwps()
351 {
352     int lwp_fd;
353     register int i;
354     GC_bool changed;
355     lwpid_t me = _lwp_self();
356 #   define PARANOID
357
358     for (i = 0; GC_current_ids[i] != 0; i++) {
359 #       ifdef PARANOID
360           if (GC_current_ids[i] != me) {
361             int lwp_fd = open_lwp(GC_current_ids[i]);
362             prstatus_t status;
363             
364             if (lwp_fd < 0) ABORT("open_lwp failed");
365             if (syscall(SYS_ioctl, lwp_fd,
366                         PIOCSTATUS, &status) < 0) {
367                 ABORT("PIOCSTATUS failed in restart_all_lwps");
368             }
369             if (memcmp(status.pr_reg, GC_lwp_registers[i],
370                        sizeof (prgregset_t)) != 0) {
371                     int j;
372
373                     for(j = 0; j < NPRGREG; j++)
374                     {
375                             GC_printf3("%i: %x -> %x\n", j,
376                                        GC_lwp_registers[i][j],
377                                        status.pr_reg[j]);
378                     }
379                 ABORT("Register contents changed");
380             }
381             if (!status.pr_flags & PR_STOPPED) {
382                 ABORT("lwp no longer stopped");
383             }
384 #ifdef SPARC
385             {
386                     gwindows_t windows;
387               if (syscall(SYS_ioctl, lwp_fd,
388                         PIOCGWIN, &windows) < 0) {
389                 ABORT("PIOCSTATUS failed in restart_all_lwps");
390               }
391               if (windows.wbcnt > 0) ABORT("unsaved register windows");
392             }
393 #endif
394           }
395 #       endif /* PARANOID */
396         if (GC_current_ids[i] == me) continue;
397         if (_lwp_continue(GC_current_ids[i]) < 0) {
398             ABORT("Failed to restart lwp");
399         }
400     }
401     if (i >= max_lwps) ABORT("Too many lwps");
402 }
403
404 GC_bool GC_multithreaded = 0;
405
406 void GC_stop_world()
407 {
408     preempt_off();
409     if (GC_multithreaded)
410         stop_all_lwps();
411 }
412
413 void GC_start_world()
414 {
415     if (GC_multithreaded)
416         restart_all_lwps();
417     preempt_on();
418 }
419
420 void GC_thr_init(void);
421
422 GC_bool GC_thr_initialized = FALSE;
423
424 size_t GC_min_stack_sz;
425
426
427 /*
428  * stack_head is stored at the top of free stacks
429  */
430 struct stack_head {
431         struct stack_head       *next;
432         ptr_t                   base;
433         thread_t                owner;
434 };
435
436 # define N_FREE_LISTS 25
437 struct stack_head *GC_stack_free_lists[N_FREE_LISTS] = { 0 };
438                 /* GC_stack_free_lists[i] is free list for stacks of    */
439                 /* size GC_min_stack_sz*2**i.                           */
440                 /* Free lists are linked through stack_head stored      */                      /* at top of stack.                                     */
441
442 /* Return a stack of size at least *stack_size.  *stack_size is */
443 /* replaced by the actual stack size.                           */
444 /* Caller holds allocation lock.                                */
445 ptr_t GC_stack_alloc(size_t * stack_size)
446 {
447     register size_t requested_sz = *stack_size;
448     register size_t search_sz = GC_min_stack_sz;
449     register int index = 0;     /* = log2(search_sz/GC_min_stack_sz) */
450     register ptr_t base;
451     register struct stack_head *result;
452     
453     while (search_sz < requested_sz) {
454         search_sz *= 2;
455         index++;
456     }
457     if ((result = GC_stack_free_lists[index]) == 0
458         && (result = GC_stack_free_lists[index+1]) != 0) {
459         /* Try next size up. */
460         search_sz *= 2; index++;
461     }
462     if (result != 0) {
463         base =  GC_stack_free_lists[index]->base;
464         GC_stack_free_lists[index] = GC_stack_free_lists[index]->next;
465     } else {
466 #ifdef MMAP_STACKS
467         base = (ptr_t)mmap(0, search_sz + GC_page_size,
468                              PROT_READ|PROT_WRITE, MAP_PRIVATE |MAP_NORESERVE,
469                              GC_zfd, 0);
470         if (base == (ptr_t)-1)
471         {
472                 *stack_size = 0;
473                 return NULL;
474         }
475
476         mprotect(base, GC_page_size, PROT_NONE);
477         /* Should this use divHBLKSZ(search_sz + GC_page_size) ? -- cf */
478         GC_is_fresh((struct hblk *)base, divHBLKSZ(search_sz));
479         base += GC_page_size;
480
481 #else
482         base = (ptr_t) GC_scratch_alloc(search_sz + 2*GC_page_size);
483         if (base == NULL)
484         {
485                 *stack_size = 0;
486                 return NULL;
487         }
488
489         base = (ptr_t)(((word)base + GC_page_size) & ~(GC_page_size - 1));
490         /* Protect hottest page to detect overflow. */
491 #       ifdef SOLARIS23_MPROTECT_BUG_FIXED
492             mprotect(base, GC_page_size, PROT_NONE);
493 #       endif
494         GC_is_fresh((struct hblk *)base, divHBLKSZ(search_sz));
495
496         base += GC_page_size;
497 #endif
498     }
499     *stack_size = search_sz;
500     return(base);
501 }
502
503 /* Caller holds  allocationlock.                                        */
504 void GC_stack_free(ptr_t stack, size_t size)
505 {
506     register int index = 0;
507     register size_t search_sz = GC_min_stack_sz;
508     register struct stack_head *head;
509     
510 #ifdef MMAP_STACKS
511     /* Zero pointers */
512     mmap(stack, size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_NORESERVE|MAP_FIXED,
513          GC_zfd, 0);
514 #endif
515     while (search_sz < size) {
516         search_sz *= 2;
517         index++;
518     }
519     if (search_sz != size) ABORT("Bad stack size");
520
521     head = (struct stack_head *)(stack + search_sz - sizeof(struct stack_head));
522     head->next = GC_stack_free_lists[index];
523     head->base = stack;
524     GC_stack_free_lists[index] = head;
525 }
526
527 void GC_my_stack_limits();
528
529 /* Notify virtual dirty bit implementation that known empty parts of    */
530 /* stacks do not contain useful data.                                   */ 
531 /* Caller holds allocation lock.                                        */
532 void GC_old_stacks_are_fresh()
533 {
534 /* No point in doing this for MMAP stacks - and pointers are zero'd out */
535 /* by the mmap in GC_stack_free */
536 #ifndef MMAP_STACKS
537     register int i;
538     register struct stack_head *s;
539     register ptr_t p;
540     register size_t sz;
541     register struct hblk * h;
542     int dummy;
543     
544     for (i = 0, sz= GC_min_stack_sz; i < N_FREE_LISTS;
545          i++, sz *= 2) {
546          for (s = GC_stack_free_lists[i]; s != 0; s = s->next) {
547              p = s->base;
548              h = (struct hblk *)(((word)p + HBLKSIZE-1) & ~(HBLKSIZE-1));
549              if ((ptr_t)h == p) {
550                  GC_is_fresh((struct hblk *)p, divHBLKSZ(sz));
551              } else {
552                  GC_is_fresh((struct hblk *)p, divHBLKSZ(sz) - 1);
553                  BZERO(p, (ptr_t)h - p);
554              }
555          }
556     }
557 #endif /* MMAP_STACKS */
558     GC_my_stack_limits();
559 }
560
561 /* The set of all known threads.  We intercept thread creation and      */
562 /* joins.  We never actually create detached threads.  We allocate all  */
563 /* new thread stacks ourselves.  These allow us to maintain this        */
564 /* data structure.                                                      */
565
566 # define THREAD_TABLE_SZ 128    /* Must be power of 2   */
567 volatile GC_thread GC_threads[THREAD_TABLE_SZ];
568
569 void GC_push_thread_structures GC_PROTO((void))
570 {
571     GC_push_all((ptr_t)(GC_threads), (ptr_t)(GC_threads)+sizeof(GC_threads));
572 }
573
574 /* Add a thread to GC_threads.  We assume it wasn't already there.      */
575 /* Caller holds allocation lock.                                        */
576 GC_thread GC_new_thread(thread_t id)
577 {
578     int hv = ((word)id) % THREAD_TABLE_SZ;
579     GC_thread result;
580     static struct GC_Thread_Rep first_thread;
581     static GC_bool first_thread_used = FALSE;
582     
583     if (!first_thread_used) {
584         result = &first_thread;
585         first_thread_used = TRUE;
586         /* Dont acquire allocation lock, since we may already hold it. */
587     } else {
588         result = (struct GC_Thread_Rep *)
589                  GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL);
590     }
591     if (result == 0) return(0);
592     result -> id = id;
593     result -> next = GC_threads[hv];
594     GC_threads[hv] = result;
595     /* result -> finished = 0; */
596     (void) cond_init(&(result->join_cv), USYNC_THREAD, 0);
597     return(result);
598 }
599
600 /* Delete a thread from GC_threads.  We assume it is there.     */
601 /* (The code intentionally traps if it wasn't.)                 */
602 /* Caller holds allocation lock.                                */
603 void GC_delete_thread(thread_t id)
604 {
605     int hv = ((word)id) % THREAD_TABLE_SZ;
606     register GC_thread p = GC_threads[hv];
607     register GC_thread prev = 0;
608     
609     while (p -> id != id) {
610         prev = p;
611         p = p -> next;
612     }
613     if (prev == 0) {
614         GC_threads[hv] = p -> next;
615     } else {
616         prev -> next = p -> next;
617     }
618 }
619
620 /* Return the GC_thread correpsonding to a given thread_t.      */
621 /* Returns 0 if it's not there.                                 */
622 /* Caller holds  allocation lock.                               */
623 GC_thread GC_lookup_thread(thread_t id)
624 {
625     int hv = ((word)id) % THREAD_TABLE_SZ;
626     register GC_thread p = GC_threads[hv];
627     
628     while (p != 0 && p -> id != id) p = p -> next;
629     return(p);
630 }
631
632 /* Solaris 2/Intel uses an initial stack size limit slightly bigger than the
633    SPARC default of 8 MB.  Account for this to warn only if the user has
634    raised the limit beyond the default.
635
636    This is identical to DFLSSIZ defined in <sys/vm_machparam.h>.  This file
637    is installed in /usr/platform/`uname -m`/include, which is not in the
638    default include directory list, so copy the definition here.  */
639 #ifdef I386
640 # define MAX_ORIG_STACK_SIZE (8 * 1024 * 1024 + ((USRSTACK) & 0x3FFFFF))
641 #else
642 # define MAX_ORIG_STACK_SIZE (8 * 1024 * 1024)
643 #endif
644
645 word GC_get_orig_stack_size() {
646     struct rlimit rl;
647     static int warned = 0;
648     int result;
649
650     if (getrlimit(RLIMIT_STACK, &rl) != 0) ABORT("getrlimit failed");
651     result = (word)rl.rlim_cur & ~(HBLKSIZE-1);
652     if (result > MAX_ORIG_STACK_SIZE) {
653         if (!warned) {
654             WARN("Large stack limit(%ld): only scanning 8 MB\n", result);
655             warned = 1;
656         }
657         result = MAX_ORIG_STACK_SIZE;
658     }
659     return result;
660 }
661
662 /* Notify dirty bit implementation of unused parts of my stack. */
663 /* Caller holds allocation lock.                                */
664 void GC_my_stack_limits()
665 {
666     int dummy;
667     register ptr_t hottest = (ptr_t)((word)(&dummy) & ~(HBLKSIZE-1));
668     register GC_thread me = GC_lookup_thread(thr_self());
669     register size_t stack_size = me -> stack_size;
670     register ptr_t stack;
671     
672     if (stack_size == 0) {
673       /* original thread */
674         /* Empirically, what should be the stack page with lowest       */
675         /* address is actually inaccessible.                            */
676         stack_size = GC_get_orig_stack_size() - GC_page_size;
677         stack = GC_stackbottom - stack_size + GC_page_size;
678     } else {
679         stack = me -> stack;
680     }
681     if (stack > hottest || stack + stack_size < hottest) {
682         ABORT("sp out of bounds");
683     }
684     GC_is_fresh((struct hblk *)stack, divHBLKSZ(hottest - stack));
685 }
686
687
688 /* We hold allocation lock.  Should do exactly the right thing if the   */
689 /* world is stopped.  Should not fail if it isn't.                      */
690 void GC_push_all_stacks()
691 {
692     register int i;
693     register GC_thread p;
694     register ptr_t sp = GC_approx_sp();
695     register ptr_t bottom, top;
696     struct rlimit rl;
697     
698 #   define PUSH(bottom,top) \
699       if (GC_dirty_maintained) { \
700         GC_push_selected((bottom), (top), GC_page_was_ever_dirty, \
701                       GC_push_all_stack); \
702       } else { \
703         GC_push_all_stack((bottom), (top)); \
704       }
705     GC_push_all_stack((ptr_t)GC_lwp_registers,
706                       (ptr_t)GC_lwp_registers
707                       + max_lwps * sizeof(GC_lwp_registers[0]));
708     for (i = 0; i < THREAD_TABLE_SZ; i++) {
709       for (p = GC_threads[i]; p != 0; p = p -> next) {
710         if (p -> stack_size != 0) {
711             bottom = p -> stack;
712             top = p -> stack + p -> stack_size;
713         } else {
714             /* The original stack. */
715             bottom = GC_stackbottom - GC_get_orig_stack_size() + GC_page_size;
716             top = GC_stackbottom;
717         }
718         if ((word)sp > (word)bottom && (word)sp < (word)top) bottom = sp;
719         PUSH(bottom, top);
720       }
721     }
722 }
723
724
725 int GC_is_thread_stack(ptr_t addr)
726 {
727     register int i;
728     register GC_thread p;
729     register ptr_t bottom, top;
730     
731     for (i = 0; i < THREAD_TABLE_SZ; i++) {
732       for (p = GC_threads[i]; p != 0; p = p -> next) {
733         if (p -> stack_size != 0) {
734             if (p -> stack <= addr &&
735                 addr < p -> stack + p -> stack_size)
736                     return 1;
737         }
738       }
739     }
740     return 0;
741 }
742
743 /* The only thread that ever really performs a thr_join.        */
744 void * GC_thr_daemon(void * dummy)
745 {
746     void *status;
747     thread_t departed;
748     register GC_thread t;
749     register int i;
750     register int result;
751     
752     for(;;) {
753       start:
754         result = thr_join((thread_t)0, &departed, &status);
755         LOCK();
756         if (result != 0) {
757             /* No more threads; wait for create. */
758             for (i = 0; i < THREAD_TABLE_SZ; i++) {
759                 for (t = GC_threads[i]; t != 0; t = t -> next) {
760                     if (!(t -> flags & (DETACHED | FINISHED))) {
761                       UNLOCK();
762                       goto start; /* Thread started just before we */
763                                   /* acquired the lock.            */
764                     }
765                 }
766             }
767             cond_wait(&GC_create_cv, &GC_allocate_ml);
768             UNLOCK();
769         } else {
770             t = GC_lookup_thread(departed);
771             GC_multithreaded--;
772             if (!(t -> flags & CLIENT_OWNS_STACK)) {
773                 GC_stack_free(t -> stack, t -> stack_size);
774             }
775             if (t -> flags & DETACHED) {
776                 GC_delete_thread(departed);
777             } else {
778                 t -> status = status;
779                 t -> flags |= FINISHED;
780                 cond_signal(&(t -> join_cv));
781                 cond_broadcast(&GC_prom_join_cv);
782             }
783             UNLOCK();
784         }
785     }
786 }
787
788 /* We hold the allocation lock, or caller ensures that 2 instances      */
789 /* cannot be invoked concurrently.                                      */
790 void GC_thr_init(void)
791 {
792     GC_thread t;
793     thread_t tid;
794     int ret;
795
796     if (GC_thr_initialized)
797             return;
798     GC_thr_initialized = TRUE;
799     GC_min_stack_sz = ((thr_min_stack() + 32*1024 + HBLKSIZE-1)
800                        & ~(HBLKSIZE - 1));
801 #ifdef MMAP_STACKS
802     GC_zfd = open("/dev/zero", O_RDONLY);
803     if (GC_zfd == -1)
804             ABORT("Can't open /dev/zero");
805 #endif /* MMAP_STACKS */
806     cond_init(&GC_prom_join_cv, USYNC_THREAD, 0);
807     cond_init(&GC_create_cv, USYNC_THREAD, 0);
808     /* Add the initial thread, so we can stop it.       */
809       t = GC_new_thread(thr_self());
810       t -> stack_size = 0;
811       t -> flags = DETACHED | CLIENT_OWNS_STACK;
812     ret = thr_create(0 /* stack */, 0 /* stack_size */, GC_thr_daemon,
813                      0 /* arg */, THR_DETACHED | THR_DAEMON,
814                      &tid /* thread_id */);
815     if (ret != 0) {
816         GC_err_printf1("Thr_create returned %ld\n", ret);
817         ABORT("Cant fork daemon");
818     }
819     thr_setprio(tid, 126);
820 }
821
822 /* We acquire the allocation lock to prevent races with         */
823 /* stopping/starting world.                                     */
824 /* This is no more correct than the underlying Solaris 2.X      */
825 /* implementation.  Under 2.3 THIS IS BROKEN.                   */
826 int GC_thr_suspend(thread_t target_thread)
827 {
828     GC_thread t;
829     int result;
830     
831     LOCK();
832     result = thr_suspend(target_thread);
833     if (result == 0) {
834         t = GC_lookup_thread(target_thread);
835         if (t == 0) ABORT("thread unknown to GC");
836         t -> flags |= SUSPNDED;
837     }
838     UNLOCK();
839     return(result);
840 }
841
842 int GC_thr_continue(thread_t target_thread)
843 {
844     GC_thread t;
845     int result;
846     
847     LOCK();
848     result = thr_continue(target_thread);
849     if (result == 0) {
850         t = GC_lookup_thread(target_thread);
851         if (t == 0) ABORT("thread unknown to GC");
852         t -> flags &= ~SUSPNDED;
853     }
854     UNLOCK();
855     return(result);
856 }
857
858 int GC_thr_join(thread_t wait_for, thread_t *departed, void **status)
859 {
860     register GC_thread t;
861     int result = 0;
862     
863     LOCK();
864     if (wait_for == 0) {
865         register int i;
866         register GC_bool thread_exists;
867     
868         for (;;) {
869           thread_exists = FALSE;
870           for (i = 0; i < THREAD_TABLE_SZ; i++) {
871             for (t = GC_threads[i]; t != 0; t = t -> next) {
872               if (!(t -> flags & DETACHED)) {
873                 if (t -> flags & FINISHED) {
874                   goto found;
875                 }
876                 thread_exists = TRUE;
877               }
878             }
879           }
880           if (!thread_exists) {
881               result = ESRCH;
882               goto out;
883           }
884           cond_wait(&GC_prom_join_cv, &GC_allocate_ml);
885         }
886     } else {
887         t = GC_lookup_thread(wait_for);
888         if (t == 0 || t -> flags & DETACHED) {
889             result = ESRCH;
890             goto out;
891         }
892         if (wait_for == thr_self()) {
893             result = EDEADLK;
894             goto out;
895         }
896         while (!(t -> flags & FINISHED)) {
897             cond_wait(&(t -> join_cv), &GC_allocate_ml);
898         }
899         
900     }
901   found:
902     if (status) *status = t -> status;
903     if (departed) *departed = t -> id;
904     cond_destroy(&(t -> join_cv));
905     GC_delete_thread(t -> id);
906   out:
907     UNLOCK();
908     return(result);
909 }
910
911
912 int
913 GC_thr_create(void *stack_base, size_t stack_size,
914               void *(*start_routine)(void *), void *arg, long flags,
915               thread_t *new_thread)
916 {
917     int result;
918     GC_thread t;
919     thread_t my_new_thread;
920     word my_flags = 0;
921     void * stack = stack_base;
922    
923     LOCK();
924     if (!GC_is_initialized) GC_init_inner();
925     GC_multithreaded++;
926     if (stack == 0) {
927         if (stack_size == 0) stack_size = 1024*1024;
928         stack = (void *)GC_stack_alloc(&stack_size);
929         if (stack == 0) {
930             GC_multithreaded--;
931             UNLOCK();
932             return(ENOMEM);
933         }
934     } else {
935         my_flags |= CLIENT_OWNS_STACK;
936     }
937     if (flags & THR_DETACHED) my_flags |= DETACHED;
938     if (flags & THR_SUSPENDED) my_flags |= SUSPNDED;
939     result = thr_create(stack, stack_size, start_routine,
940                         arg, flags & ~THR_DETACHED, &my_new_thread);
941     if (result == 0) {
942         t = GC_new_thread(my_new_thread);
943         t -> flags = my_flags;
944         if (!(my_flags & DETACHED)) cond_init(&(t -> join_cv), USYNC_THREAD, 0);
945         t -> stack = stack;
946         t -> stack_size = stack_size;
947         if (new_thread != 0) *new_thread = my_new_thread;
948         cond_signal(&GC_create_cv);
949     } else {
950         GC_multithreaded--;
951         if (!(my_flags & CLIENT_OWNS_STACK)) {
952             GC_stack_free(stack, stack_size);
953         }
954     }        
955     UNLOCK();  
956     return(result);
957 }
958
959 # else /* !GC_SOLARIS_THREADS */
960
961 #ifndef LINT
962   int GC_no_sunOS_threads;
963 #endif
964 #endif