0.9.0.8:
[sbcl.git] / src / runtime / thread.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <string.h>
4 #include <sched.h>
5 #include <signal.h>
6 #include <stddef.h>
7 #include <errno.h>
8 #include <sys/types.h>
9 #include <sys/wait.h>
10
11 #include "sbcl.h"
12 #include "runtime.h"
13 #include "validate.h"           /* for CONTROL_STACK_SIZE etc */
14 #include "thread.h"
15 #include "arch.h"
16 #include "target-arch-os.h"
17 #include "os.h"
18 #include "globals.h"
19 #include "dynbind.h"
20 #include "genesis/cons.h"
21 #include "genesis/fdefn.h"
22 #include "interr.h"             /* for lose() */
23 #include "gc-internal.h"
24
25 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
26
27 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
28 struct thread *all_threads;
29 volatile lispobj all_threads_lock;
30 extern struct interrupt_data * global_interrupt_data;
31 extern int linux_no_threads_p;
32
33 int
34 initial_thread_trampoline(struct thread *th)
35 {
36     lispobj function;
37 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
38     lispobj *args = NULL;
39 #endif
40
41     function = th->unbound_marker;
42     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
43     if(arch_os_thread_init(th)==0) return 1;
44
45     if(th->pid < 1) lose("th->pid not set up right");
46     th->state=STATE_RUNNING;
47 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
48     return call_into_lisp_first_time(function,args,0);
49 #else
50     return funcall0(function);
51 #endif
52 }
53
54 /* this is the first thing that clone() runs in the child (which is
55  * why the silly calling convention).  Basically it calls the user's
56  * requested lisp function after doing arch_os_thread_init and
57  * whatever other bookkeeping needs to be done
58  */
59
60 #ifdef LISP_FEATURE_SB_THREAD
61 int
62 new_thread_trampoline(struct thread *th)
63 {
64     lispobj function;
65     function = th->unbound_marker;
66     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
67     if(arch_os_thread_init(th)==0) return 1;    
68
69     /* wait here until our thread is linked into all_threads: see below */
70     while(th->pid<1) sched_yield();
71
72     th->state=STATE_RUNNING;
73     return funcall0(function);
74 }
75 #endif /* LISP_FEATURE_SB_THREAD */
76
77 /* this is called from any other thread to create the new one, and
78  * initialize all parts of it that can be initialized from another 
79  * thread 
80  */
81
82 struct thread * create_thread_struct(lispobj initial_function) {
83     union per_thread_data *per_thread;
84     struct thread *th=0;        /*  subdue gcc */
85     void *spaces=0;
86
87     /* may as well allocate all the spaces at once: it saves us from
88      * having to decide what to do if only some of the allocations
89      * succeed */
90     spaces=os_validate(0,
91                        THREAD_CONTROL_STACK_SIZE+
92                        BINDING_STACK_SIZE+
93                        ALIEN_STACK_SIZE+
94                        dynamic_values_bytes+
95                        32*SIGSTKSZ);
96     if(!spaces)
97          return NULL;
98     per_thread=(union per_thread_data *)
99         (spaces+
100          THREAD_CONTROL_STACK_SIZE+
101          BINDING_STACK_SIZE+
102          ALIEN_STACK_SIZE);
103
104     if(all_threads) {
105         memcpy(per_thread,arch_os_get_current_thread(),
106                dynamic_values_bytes);
107     } else {
108 #ifdef LISP_FEATURE_SB_THREAD
109         int i;
110         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
111             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
112         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
113             SetSymbolValue
114                 (FREE_TLS_INDEX,
115                  make_fixnum(MAX_INTERRUPTS+
116                              sizeof(struct thread)/sizeof(lispobj)),
117                  0);
118 #define STATIC_TLS_INIT(sym,field) \
119   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
120   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
121                                   
122         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
123         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
124         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
125         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
126         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
127 #ifdef LISP_FEATURE_X86
128         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
129         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
130 #endif
131 #undef STATIC_TLS_INIT
132 #endif
133     }
134
135     th=&per_thread->thread;
136     th->control_stack_start = spaces;
137     th->binding_stack_start=
138         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
139     th->control_stack_end = th->binding_stack_start;
140     th->alien_stack_start=
141         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
142     th->binding_stack_pointer=th->binding_stack_start;
143     th->this=th;
144     th->pid=0;
145     th->state=STATE_STOPPED;
146 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
147     th->alien_stack_pointer=((void *)th->alien_stack_start
148                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
149 #else
150     th->alien_stack_pointer=((void *)th->alien_stack_start);
151 #endif
152 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
153     th->pseudo_atomic_interrupted=0;
154     th->pseudo_atomic_atomic=0;
155 #endif
156 #ifdef LISP_FEATURE_GENCGC
157     gc_set_region_empty(&th->alloc_region);
158 #endif
159
160 #ifndef LISP_FEATURE_SB_THREAD
161     /* the tls-points-into-struct-thread trick is only good for threaded
162      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
163      * appropriate values from struct thread here, and make sure that 
164      * we use the appropriate SymbolValue macros to access any of the
165      * variable quantities from the C runtime.  It's not quite OAOOM,
166      * it just feels like it */
167     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
168     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
169     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
170 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
171     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
172     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
173     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
174     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
175 #else
176     current_binding_stack_pointer=th->binding_stack_pointer;
177     current_control_stack_pointer=th->control_stack_start;
178 #endif
179 #endif    
180     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
181     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th); 
182     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
183     bind_variable(INTERRUPT_PENDING, NIL,th);
184     bind_variable(INTERRUPTS_ENABLED,T,th);
185
186     th->interrupt_data =
187         os_validate(0,(sizeof (struct interrupt_data)));
188     if(all_threads) 
189         memcpy(th->interrupt_data,
190                arch_os_get_current_thread()->interrupt_data,
191                sizeof (struct interrupt_data));
192     else 
193         memcpy(th->interrupt_data,global_interrupt_data,
194                sizeof (struct interrupt_data));
195
196     th->unbound_marker=initial_function;
197     return th;
198 }
199
200 void link_thread(struct thread *th,pid_t kid_pid)
201 {
202     sigset_t newset,oldset;
203     sigemptyset(&newset);
204     sigaddset_blockable(&newset);
205     sigprocmask(SIG_BLOCK, &newset, &oldset); 
206
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
216     sigprocmask(SIG_SETMASK,&oldset,0);
217     th->pid=kid_pid;            /* child will not start until this is set */
218 }
219
220 void create_initial_thread(lispobj initial_function) {
221     struct thread *th=create_thread_struct(initial_function);
222     pid_t kid_pid=getpid();
223     if(th && kid_pid>0) {
224         link_thread(th,kid_pid);
225         initial_thread_trampoline(all_threads); /* no return */
226     } else lose("can't create initial thread");
227 }
228
229 #ifdef LISP_FEATURE_SB_THREAD
230 pid_t create_thread(lispobj initial_function) {
231     struct thread *th;
232     pid_t kid_pid=0;
233
234     if(linux_no_threads_p) return 0;
235     th=create_thread_struct(initial_function);
236     if(th==0) return 0;
237     kid_pid=clone(new_thread_trampoline,
238                   (((void*)th->control_stack_start)+
239                    THREAD_CONTROL_STACK_SIZE-16),
240                   CLONE_FILES|SIG_THREAD_EXIT|CLONE_VM,th);
241     
242     if(kid_pid>0) {
243         link_thread(th,kid_pid);
244         return th->pid;
245     } else {
246         os_invalidate((os_vm_address_t) th->control_stack_start,
247                       ((sizeof (lispobj))
248                        * (th->control_stack_end-th->control_stack_start)) +
249                       BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
250                       32*SIGSTKSZ);
251         return 0;
252     }
253 }
254 #endif
255
256 struct thread *find_thread_by_pid(pid_t pid) 
257 {
258     struct thread *th;
259     for_each_thread(th)
260         if(th->pid==pid) return th;
261     return 0;
262 }
263
264 #if defined LISP_FEATURE_SB_THREAD
265 /* This is not needed unless #+SB-THREAD, as there's a trivial null
266  * unithread definition. */
267
268 void mark_dead_threads() 
269 {
270     pid_t kid;
271     int status;
272     while(1) {
273         kid=waitpid(-1,&status,__WALL|WNOHANG);
274         if(kid<=0) break;
275         if(WIFEXITED(status) || WIFSIGNALED(status)) {
276             struct thread *th=find_thread_by_pid(kid);
277             if(th) th->state=STATE_DEAD;
278         }
279     }
280 }
281
282 void reap_dead_threads() 
283 {
284     struct thread *th,*next,*prev=0;
285     th=all_threads;
286     while(th) {
287         next=th->next;
288         if(th->state==STATE_DEAD) {
289             funcall1(SymbolFunction(HANDLE_THREAD_EXIT),make_fixnum(th->pid));
290 #ifdef LISP_FEATURE_GENCGC
291             gc_alloc_update_page_tables(0, &th->alloc_region);
292 #endif
293             get_spinlock(&all_threads_lock,th->pid);
294             if(prev) prev->next=next;
295             else all_threads=next;
296             release_spinlock(&all_threads_lock);
297             if(th->tls_cookie>=0) arch_os_thread_cleanup(th); 
298             os_invalidate((os_vm_address_t) th->control_stack_start,
299                           ((sizeof (lispobj))
300                            * (th->control_stack_end-th->control_stack_start)) +
301                           BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
302                           32*SIGSTKSZ);
303         } else 
304             prev=th;
305         th=next;
306     }
307 }
308
309 /* These are not needed unless #+SB-THREAD, and since sigwaitinfo()
310  * doesn't seem to be easily available everywhere (OpenBSD...) it's
311  * more trouble than it's worth to compile it when not needed. */
312 void block_sigcont(void)
313 {
314     /* don't allow ourselves to receive SIGCONT while we're in the
315      * "ambiguous" state of being on the queue but not actually stopped.
316      */
317     sigset_t newset;
318     sigemptyset(&newset);
319     sigaddset(&newset,SIG_DEQUEUE);
320     sigprocmask(SIG_BLOCK, &newset, 0); 
321 }
322
323 void unblock_sigcont_and_sleep(void)
324 {
325     sigset_t set;
326     sigemptyset(&set);
327     sigaddset(&set,SIG_DEQUEUE);
328     do {
329         errno=0;
330         sigwaitinfo(&set,0);
331     }while(errno==EINTR);
332     sigprocmask(SIG_UNBLOCK,&set,0);
333 }
334
335 int interrupt_thread(pid_t pid, lispobj function)
336 {
337     union sigval sigval;
338     struct thread *th;
339     sigval.sival_int=function;
340     for_each_thread(th) 
341         if((th->pid==pid) && (th->state != STATE_DEAD))
342             return sigqueue(pid, SIG_INTERRUPT_THREAD, sigval);
343     errno=EPERM; return -1;
344 }
345
346 int signal_thread_to_dequeue (pid_t pid)
347 {
348     return kill (pid, SIG_DEQUEUE);
349 }
350
351
352 /* stopping the world is a two-stage process.  From this thread we signal 
353  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
354  * the usual pseudo-atomic checks (we don't want to stop a thread while 
355  * it's in the middle of allocation) then kills _itself_ with SIGSTOP.
356  */
357
358 void gc_stop_the_world()
359 {
360     /* stop all other threads by sending them SIG_STOP_FOR_GC */
361     struct thread *p,*th=arch_os_get_current_thread();
362     pid_t old_pid;
363     int finished;
364     do {
365         finished=1;
366         for(p=all_threads,old_pid=p->pid; p; p=p->next) {
367             if(p==th) continue;
368             if(p->state==STATE_RUNNING) {
369                 p->state=STATE_STOPPING;
370                 if(kill(p->pid,SIG_STOP_FOR_GC)==-1) {
371                     /* we can't kill the process; assume because it
372                      * died already (and its parent is dead so never
373                      * saw the SIGCHLD) */
374                     p->state=STATE_DEAD;
375                 }
376             }
377             if((p->state!=STATE_STOPPED) &&
378                (p->state!=STATE_DEAD)) {
379                 finished=0;
380             }
381         }
382         if(old_pid!=all_threads->pid) {
383             finished=0;
384         }
385     } while(!finished);
386 }
387
388 void gc_start_the_world()
389 {
390     struct thread *p,*th=arch_os_get_current_thread();
391     /* if a resumed thread creates a new thread before we're done with
392      * this loop, the new thread will get consed on the front of *
393      * all_threads_lock, but it won't have been stopped so won't need
394      * restarting */
395     for(p=all_threads;p;p=p->next) {
396         if((p==th) || (p->state==STATE_DEAD)) continue;
397         p->state=STATE_RUNNING;
398         kill(p->pid,SIG_STOP_FOR_GC);
399     }
400 }
401 #endif