0.8.4.10
[sbcl.git] / src / runtime / thread.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sched.h>
4 #include <signal.h>
5 #include <stddef.h>
6 #include <errno.h>
7 #ifndef CLONE_PARENT            /* lameass glibc 2.2  doesn't define this */
8 #define CLONE_PARENT 0x00008000 /* even though the manpage documents it */
9 #endif
10 #include "runtime.h"
11 #include "sbcl.h"
12 #include "validate.h"           /* for CONTROL_STACK_SIZE etc */
13 #include "thread.h"
14 #include "arch.h"
15 #include "target-arch-os.h"
16 #include "os.h"
17 #include "globals.h"
18 #ifdef LISP_FEATURE_GENCGC
19 #include "gencgc.h"
20 #endif
21 #include "dynbind.h"
22 #include "genesis/cons.h"
23 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
24
25 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
26 struct thread *all_threads;
27 volatile lispobj all_threads_lock;
28 volatile int countdown_to_gc;
29 extern struct interrupt_data * global_interrupt_data;
30
31 void get_spinlock(lispobj *word,int value);
32
33 /* this is the first thing that clone() runs in the child (which is
34  * why the silly calling convention).  Basically it calls the user's
35  * requested lisp function after doing arch_os_thread_init and
36  * whatever other bookkeeping needs to be done
37  */
38
39 /* set go to 0 to stop the thread before it starts.  Convenient if you
40 * want to attach a debugger to it before it does anything */
41 volatile int go=1;              
42
43 int
44 new_thread_trampoline(struct thread *th)
45 {
46     lispobj function;
47     lispobj *args = NULL;
48     function = th->unbound_marker;
49     if(go==0) {
50         fprintf(stderr, "/pausing 0x%lx(%d,%d) before new_thread_trampoline(0x%lx)\n",
51                 (unsigned long)th,th->pid,getpid(),(unsigned long)function);
52         while(go==0) ;
53         fprintf(stderr, "/continue\n");
54     }
55     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
56 #ifdef LISP_FEATURE_SB_THREAD
57     /* wait here until our thread is linked into all_threads: see below */
58     while(th->pid<1) sched_yield();
59 #else
60     if(th->pid < 1)
61         lose("th->pid not set up right");
62 #endif
63
64     if(arch_os_thread_init(th)==0) 
65         return 1;               /* failure.  no, really */
66 #if !defined(LISP_FEATURE_SB_THREAD) && defined(LISP_FEATURE_X86)
67     return call_into_lisp_first_time(function,args,0);
68 #else
69     return funcall0(function);
70 #endif
71 }
72
73 /* this is called from any other thread to create the new one, and
74  * initialize all parts of it that can be initialized from another 
75  * thread 
76  */
77
78 pid_t create_thread(lispobj initial_function) {
79     union per_thread_data *per_thread;
80     struct thread *th=0;        /*  subdue gcc */
81     void *spaces=0;
82     pid_t kid_pid;
83
84     /* may as well allocate all the spaces at once: it saves us from
85      * having to decide what to do if only some of the allocations
86      * succeed */
87     spaces=os_validate(0,
88                        THREAD_CONTROL_STACK_SIZE+
89                        BINDING_STACK_SIZE+
90                        ALIEN_STACK_SIZE+
91                        dynamic_values_bytes+
92                        32*SIGSTKSZ
93                        );
94     if(!spaces) goto cleanup;
95     per_thread=(union per_thread_data *)
96         (spaces+
97          THREAD_CONTROL_STACK_SIZE+
98          BINDING_STACK_SIZE+
99          ALIEN_STACK_SIZE);
100
101     th=&per_thread->thread;
102     if(all_threads) {
103         memcpy(per_thread,arch_os_get_current_thread(),
104                dynamic_values_bytes);
105     } else {
106 #ifdef LISP_FEATURE_SB_THREAD
107         int i;
108         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
109             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
110         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
111             SetSymbolValue
112                 (FREE_TLS_INDEX,
113                  make_fixnum(MAX_INTERRUPTS+
114                              sizeof(struct thread)/sizeof(lispobj)),
115                  0);
116 #define STATIC_TLS_INIT(sym,field) \
117   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
118   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
119                                   
120         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
121         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
122         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
123         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
124         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
125 #ifdef LISP_FEATURE_X86
126         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
127         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
128 #endif
129 #undef STATIC_TLS_INIT
130 #endif
131     }
132
133     th->control_stack_start = spaces;
134     th->binding_stack_start=
135         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
136     th->control_stack_end = th->binding_stack_start;
137     th->alien_stack_start=
138         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
139     th->binding_stack_pointer=th->binding_stack_start;
140     th->this=th;
141     th->pid=0;
142     th->state=STATE_RUNNING;
143 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
144     th->alien_stack_pointer=((void *)th->alien_stack_start
145                              + ALIEN_STACK_SIZE-4); /* naked 4.  FIXME */
146 #else
147     th->alien_stack_pointer=((void *)th->alien_stack_start);
148 #endif
149 #ifdef LISP_FEATURE_X86
150     th->pseudo_atomic_interrupted=0;
151     /* runtime.c used to set PSEUDO_ATOMIC_ATOMIC =1 globally.  I'm not
152      * sure why, but it appears to help */
153     th->pseudo_atomic_atomic=make_fixnum(1);
154 #endif
155 #ifdef LISP_FEATURE_GENCGC
156     gc_set_region_empty(&th->alloc_region);
157 #endif
158
159 #ifndef LISP_FEATURE_SB_THREAD
160     /* the tls-points-into-struct-thread trick is only good for threaded
161      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
162      * appropriate values from struct thread here, and make sure that 
163      * we use the appropriate SymbolValue macros to access any of the
164      * variable quantities from the C runtime.  It's not quite OAOOM,
165      * it just feels like it */
166     SetSymbolValue(BINDING_STACK_START,th->binding_stack_start,th);
167     SetSymbolValue(CONTROL_STACK_START,th->control_stack_start,th);
168     SetSymbolValue(CONTROL_STACK_END,th->control_stack_end,th);
169 #ifdef LISP_FEATURE_X86
170     SetSymbolValue(BINDING_STACK_POINTER,th->binding_stack_pointer,th);
171     SetSymbolValue(ALIEN_STACK,th->alien_stack_pointer,th);
172     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,th->pseudo_atomic_atomic,th);
173     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
174 #else
175     current_binding_stack_pointer=th->binding_stack_pointer;
176     current_control_stack_pointer=th->control_stack_start;
177 #endif
178 #endif    
179     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
180     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th); 
181     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
182     bind_variable(INTERRUPT_PENDING, NIL,th);
183     bind_variable(INTERRUPTS_ENABLED,T,th);
184
185     th->interrupt_data=os_validate(0,(sizeof (struct interrupt_data)));
186     if(all_threads) 
187         memcpy(th->interrupt_data,
188                arch_os_get_current_thread()->interrupt_data,
189                sizeof (struct interrupt_data));
190     else 
191         memcpy(th->interrupt_data,global_interrupt_data,
192                sizeof (struct interrupt_data));
193
194     th->unbound_marker=initial_function;
195 #ifdef LISP_FEATURE_SB_THREAD
196 #if defined(LISP_FEATURE_X86) && defined (LISP_FEATURE_LINUX)
197     kid_pid=
198         clone(new_thread_trampoline,
199               (((void*)th->control_stack_start)+THREAD_CONTROL_STACK_SIZE-4),
200               (((getpid()!=parent_pid)?(CLONE_PARENT):0)
201                |CLONE_FILES|SIGALRM|CLONE_VM),th);
202     if(kid_pid<=0) 
203         goto cleanup;
204 #else
205 #error this stuff presently only works on x86 Linux
206 #endif
207 #else
208     kid_pid=getpid();
209 #endif
210     get_spinlock(&all_threads_lock,kid_pid);
211     th->next=all_threads;
212     all_threads=th;
213     /* note that th->pid is 0 at this time.  We rely on all_threads_lock
214      * to ensure that we don't have >1 thread with pid=0 on the list at once
215      */
216     protect_control_stack_guard_page(th->pid,1);
217     release_spinlock(&all_threads_lock);
218     th->pid=kid_pid;            /* child will not start until this is set */
219 #ifndef LISP_FEATURE_SB_THREAD
220     new_thread_trampoline(all_threads); /*  call_into_lisp */
221     lose("Clever child?  Idiot savant, verging on the.");
222 #endif
223
224     return th->pid;
225  cleanup:
226     /* if(th && th->tls_cookie>=0) os_free_tls_pointer(th); */
227     if(spaces) os_invalidate(spaces,
228                              THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
229                              ALIEN_STACK_SIZE+dynamic_values_bytes);
230     return 0;
231 }
232
233 void destroy_thread (struct thread *th)
234 {
235     /* precondition: the unix task has already been killed and exited.
236      * This is called by the parent */
237 #ifdef LISP_FEATURE_GENCGC
238     gc_alloc_update_page_tables(0, &th->alloc_region);
239 #endif
240     get_spinlock(&all_threads_lock,th->pid);
241     if(countdown_to_gc>0) countdown_to_gc--;
242     th->state=STATE_STOPPED;
243     if(th==all_threads) 
244         all_threads=th->next;
245     else {
246         struct thread *th1=all_threads;
247         while(th1->next!=th) th1=th1->next;
248         th1->next=th->next;     /* unlink */
249     }
250     release_spinlock(&all_threads_lock);
251     if(th && th->tls_cookie>=0) arch_os_thread_cleanup(th); 
252     os_invalidate((os_vm_address_t) th->control_stack_start,
253                   ((sizeof (lispobj))
254                    * (th->control_stack_end-th->control_stack_start)) +
255                   BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
256                   32*SIGSTKSZ);
257 }
258
259
260 struct thread *find_thread_by_pid(pid_t pid) 
261 {
262     struct thread *th;
263     for_each_thread(th)
264         if(th->pid==pid) return th;
265     return 0;
266 }
267
268 /* These are not needed unless #+SB-THREAD, and since sigwaitinfo()
269  * doesn't seem to be easily available everywhere (OpenBSD...) it's
270  * more trouble than it's worth to compile it when not needed. */
271 #if defined LISP_FEATURE_SB_THREAD
272 void block_sigcont(void)
273 {
274     /* don't allow ourselves to receive SIGCONT while we're in the
275      * "ambiguous" state of being on the queue but not actually stopped.
276      */
277     sigset_t newset;
278     sigemptyset(&newset);
279     sigaddset(&newset,SIG_DEQUEUE);
280     sigprocmask(SIG_BLOCK, &newset, 0); 
281 }
282
283 void unblock_sigcont_and_sleep(void)
284 {
285     sigset_t set;
286     sigemptyset(&set);
287     sigaddset(&set,SIG_DEQUEUE);
288     do {
289         errno=0;
290         sigwaitinfo(&set,0);
291     }while(errno==EINTR);
292     sigprocmask(SIG_UNBLOCK,&set,0);
293 }
294
295 int interrupt_thread(pid_t pid, lispobj function)
296 {
297     union sigval sigval;
298     sigval.sival_int=function;
299
300     return sigqueue(pid, SIG_INTERRUPT_THREAD, sigval);
301 }
302
303 /* stopping the world is a two-stage process.  From this thread we signal 
304  * all the others with SIG_STOP_FOR_GC.  The handler for this thread does
305  * the usual pseudo-atomic checks (we don't want to stop a thread while 
306  * it's in the middle of allocation) then kills _itself_ with SIGSTOP.
307  * At any given time, countdown_to_gc should reflect the number of threads
308  * signalled but which haven't yet come to rest
309  */
310
311 void gc_stop_the_world()
312 {
313     /* stop all other threads by sending them SIG_STOP_FOR_GC */
314     struct thread *p,*th=arch_os_get_current_thread();
315     struct thread *tail=0;
316     int finished=0;
317     do {
318         get_spinlock(&all_threads_lock,th->pid);
319         if(tail!=all_threads) {
320             /* new threads always get consed onto the front of all_threads,
321              * and may be created by any thread that we haven't signalled
322              * yet or hasn't received our signal and stopped yet.  So, check
323              * for them on each time around */
324             for(p=all_threads;p!=tail;p=p->next) {
325                 if(p==th) continue;
326                 /* if the head of all_threads is removed during
327                  * gc_stop_the_world, we may take a second trip through the 
328                  * list and end up counting twice as many threads to wait for
329                  * as actually exist */
330                 if(p->state!=STATE_RUNNING) continue;
331                 countdown_to_gc++;
332                 p->state=STATE_STOPPING;
333                 /* Note no return value check from kill().  If the
334                  * thread had been reaped already, we kill it and
335                  * increment countdown_to_gc anyway.  This is to avoid
336                  * complicating the logic in destroy_thread, which would 
337                  * otherwise have to know whether the thread died before or
338                  * after it was killed
339                  */
340                 kill(p->pid,SIG_STOP_FOR_GC);
341             }
342             tail=all_threads;
343         } else {
344             finished=(countdown_to_gc==0);
345         }
346         release_spinlock(&all_threads_lock);
347         sched_yield();
348     } while(!finished);
349 }
350
351 void gc_start_the_world()
352 {
353     struct thread *p,*th=arch_os_get_current_thread();
354     get_spinlock(&all_threads_lock,th->pid);
355     for(p=all_threads;p;p=p->next) {
356         if(p==th) continue;
357         p->state=STATE_RUNNING;
358         kill(p->pid,SIGCONT);
359     }
360     release_spinlock(&all_threads_lock);
361 }
362 #endif