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