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