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