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