a6b462fad6a6b61c31c978423b7441c3140b1d07
[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 "alloc.h"
15 #include "thread.h"
16 #include "arch.h"
17 #include "target-arch-os.h"
18 #include "os.h"
19 #include "globals.h"
20 #include "dynbind.h"
21 #include "genesis/cons.h"
22 #include "genesis/fdefn.h"
23 #include "interr.h"             /* for lose() */
24 #include "gc-internal.h"
25
26 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
27
28 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
29 struct thread *all_threads;
30 volatile lispobj all_threads_lock;
31 volatile lispobj thread_start_lock;
32 extern struct interrupt_data * global_interrupt_data;
33 extern int linux_no_threads_p;
34
35 int
36 initial_thread_trampoline(struct thread *th)
37 {
38     lispobj function;
39 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
40     lispobj *args = NULL;
41 #endif
42
43     function = th->unbound_marker;
44     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
45     if(arch_os_thread_init(th)==0) return 1;
46
47     if(th->os_thread < 1) lose("th->os_thread not set up right");
48     th->state=STATE_RUNNING;
49 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
50     return call_into_lisp_first_time(function,args,0);
51 #else
52     return funcall0(function);
53 #endif
54 }
55
56 #ifdef LISP_FEATURE_SB_THREAD
57 void mark_thread_dead(struct thread *th) {
58     funcall1(SymbolFunction(HANDLE_THREAD_EXIT),alloc_number(th->os_thread));
59     /* I hope it's safe for a thread to detach itself inside a 
60      * cancellation cleanup */
61     pthread_detach(th->os_thread);
62     th->state=STATE_DEAD;
63     /* FIXME: if gc hits here it will rip the stack from under us */
64 }
65
66 /* this is the first thing that runs in the child (which is why the
67  * silly calling convention).  Basically it calls the user's requested
68  * lisp function after doing arch_os_thread_init and whatever other
69  * bookkeeping needs to be done
70  */
71 int
72 new_thread_trampoline(struct thread *th)
73 {
74     lispobj function,ret;
75     function = th->unbound_marker;
76     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
77     pthread_cleanup_push((void (*) (void *))mark_thread_dead,th);
78     if(arch_os_thread_init(th)==0) return 1;    
79
80     /* wait here until our thread is linked into all_threads: see below */
81     while(th->os_thread<1) sched_yield();
82
83     th->state=STATE_RUNNING;
84     ret = funcall0(function);
85     /* execute cleanup */
86     pthread_cleanup_pop(1);
87     return ret;
88 }
89 #endif /* LISP_FEATURE_SB_THREAD */
90
91 /* this is called from any other thread to create the new one, and
92  * initialize all parts of it that can be initialized from another 
93  * thread 
94  */
95
96 struct thread * create_thread_struct(lispobj initial_function) {
97     union per_thread_data *per_thread;
98     struct thread *th=0;        /*  subdue gcc */
99     void *spaces=0;
100
101     /* may as well allocate all the spaces at once: it saves us from
102      * having to decide what to do if only some of the allocations
103      * succeed */
104     spaces=os_validate(0,
105                        THREAD_CONTROL_STACK_SIZE+
106                        BINDING_STACK_SIZE+
107                        ALIEN_STACK_SIZE+
108                        dynamic_values_bytes+
109                        32*SIGSTKSZ);
110     if(!spaces)
111          return NULL;
112     per_thread=(union per_thread_data *)
113         (spaces+
114          THREAD_CONTROL_STACK_SIZE+
115          BINDING_STACK_SIZE+
116          ALIEN_STACK_SIZE);
117
118     if(all_threads) {
119         memcpy(per_thread,arch_os_get_current_thread(),
120                dynamic_values_bytes);
121     } else {
122 #ifdef LISP_FEATURE_SB_THREAD
123         int i;
124         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
125             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
126         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
127             SetSymbolValue
128                 (FREE_TLS_INDEX,
129                  make_fixnum(MAX_INTERRUPTS+
130                              sizeof(struct thread)/sizeof(lispobj)),
131                  0);
132 #define STATIC_TLS_INIT(sym,field) \
133   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
134   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
135                                   
136         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
137         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
138         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
139         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
140         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
141 #ifdef LISP_FEATURE_X86
142         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
143         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
144 #endif
145 #undef STATIC_TLS_INIT
146 #endif
147     }
148
149     th=&per_thread->thread;
150     th->control_stack_start = spaces;
151     th->binding_stack_start=
152         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
153     th->control_stack_end = th->binding_stack_start;
154     th->alien_stack_start=
155         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
156     th->binding_stack_pointer=th->binding_stack_start;
157     th->this=th;
158     th->os_thread=0;
159     th->interrupt_fun=NIL;
160     th->interrupt_fun_lock=0;
161     th->state=STATE_STARTING;
162 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
163     th->alien_stack_pointer=((void *)th->alien_stack_start
164                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
165 #else
166     th->alien_stack_pointer=((void *)th->alien_stack_start);
167 #endif
168 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
169     th->pseudo_atomic_interrupted=0;
170     th->pseudo_atomic_atomic=0;
171 #endif
172 #ifdef LISP_FEATURE_GENCGC
173     gc_set_region_empty(&th->alloc_region);
174 #endif
175
176 #ifndef LISP_FEATURE_SB_THREAD
177     /* the tls-points-into-struct-thread trick is only good for threaded
178      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
179      * appropriate values from struct thread here, and make sure that 
180      * we use the appropriate SymbolValue macros to access any of the
181      * variable quantities from the C runtime.  It's not quite OAOOM,
182      * it just feels like it */
183     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
184     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
185     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
186 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
187     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
188     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
189     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
190     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
191 #else
192     current_binding_stack_pointer=th->binding_stack_pointer;
193     current_control_stack_pointer=th->control_stack_start;
194 #endif
195 #endif    
196     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
197     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th); 
198     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
199     bind_variable(INTERRUPT_PENDING, NIL,th);
200     bind_variable(INTERRUPTS_ENABLED,T,th);
201
202     th->interrupt_data = (struct interrupt_data *)
203         os_validate(0,(sizeof (struct interrupt_data)));
204     if(all_threads) 
205         memcpy(th->interrupt_data,
206                arch_os_get_current_thread()->interrupt_data,
207                sizeof (struct interrupt_data));
208     else 
209         memcpy(th->interrupt_data,global_interrupt_data,
210                sizeof (struct interrupt_data));
211
212     th->unbound_marker=initial_function;
213     return th;
214 }
215
216 void link_thread(struct thread *th,os_thread_t kid_tid)
217 {
218     sigset_t newset,oldset;
219     sigemptyset(&newset);
220     sigaddset_blockable(&newset);
221     thread_sigmask(SIG_BLOCK, &newset, &oldset); 
222
223     get_spinlock(&all_threads_lock,kid_tid);
224     if (all_threads) all_threads->prev=th;
225     th->next=all_threads;
226     th->prev=0;
227     all_threads=th;
228     /* note that th->os_thread is 0 at this time.  We rely on
229      * all_threads_lock to ensure that we don't have >1 thread with
230      * os_thread=0 on the list at once
231      */
232     protect_control_stack_guard_page(th->os_thread,1);
233     /* child will not start until this is set */
234     th->os_thread=kid_tid;
235     release_spinlock(&all_threads_lock);
236
237     thread_sigmask(SIG_SETMASK,&oldset,0);
238 }
239
240 void create_initial_thread(lispobj initial_function) {
241     struct thread *th=create_thread_struct(initial_function);
242     os_thread_t kid_tid=thread_self();
243     if(th && kid_tid>0) {
244         link_thread(th,kid_tid);
245         initial_thread_trampoline(all_threads); /* no return */
246     } else lose("can't create initial thread");
247 }
248
249 #ifdef LISP_FEATURE_SB_THREAD
250 os_thread_t create_thread(lispobj initial_function) {
251     struct thread *th;
252     os_thread_t kid_tid=0;
253     pthread_attr_t attr;
254
255     if(linux_no_threads_p) return 0;
256     th=create_thread_struct(initial_function);
257     if(th==0) return 0;
258 #ifdef QSHOW_SIGNALS
259     SHOW("create_thread:waiting on lock");
260 #endif
261     get_spinlock(&thread_start_lock,arch_os_get_current_thread()->os_thread);
262 #ifdef QSHOW_SIGNALS
263     SHOW("create_thread:got lock");
264 #endif
265     /* The new thread inherits the restrictive signal mask set here,
266      * and enables signals again when it is set up properly. */
267     {
268         sigset_t newset,oldset;
269         sigemptyset(&newset);
270         sigaddset_blockable(&newset);
271         thread_sigmask(SIG_BLOCK, &newset, &oldset);
272         if((pthread_attr_init(&attr)) ||
273            (pthread_attr_setstack(&attr,th->control_stack_start,
274                                   THREAD_CONTROL_STACK_SIZE-16)) ||
275            (pthread_create
276             (&kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
277             kid_tid=0;
278         thread_sigmask(SIG_SETMASK,&oldset,0);
279     }
280     if(kid_tid>0) {
281         link_thread(th,kid_tid);
282         /* it's started and initialized, it's safe to gc */
283         release_spinlock(&thread_start_lock);
284 #ifdef QSHOW_SIGNALS
285         SHOW("create_thread:released lock");
286 #endif
287         /* by now the kid might have already exited */
288         return kid_tid;
289     } else {
290         release_spinlock(&thread_start_lock);
291 #ifdef QSHOW_SIGNALS
292         SHOW("create_thread:released lock(failure)");
293 #endif
294         os_invalidate((os_vm_address_t) th->control_stack_start,
295                       ((sizeof (lispobj))
296                        * (th->control_stack_end-th->control_stack_start)) +
297                       BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
298                       32*SIGSTKSZ);
299         return 0;
300     }
301 }
302 #endif
303
304 struct thread *find_thread_by_os_thread(os_thread_t tid) 
305 {
306     struct thread *th;
307     for_each_thread(th)
308         if(th->os_thread==tid) return th;
309     return 0;
310 }
311
312 #if defined LISP_FEATURE_SB_THREAD
313 /* This is not needed unless #+SB-THREAD, as there's a trivial null
314  * unithread definition. */
315
316 void reap_dead_threads() 
317 {
318     struct thread *th,*next,*prev=0;
319     th=all_threads;
320     while(th) {
321         next=th->next;
322         if(th->state==STATE_DEAD) {
323 #ifdef LISP_FEATURE_GENCGC
324             gc_alloc_update_page_tables(0, &th->alloc_region);
325 #endif
326             get_spinlock(&all_threads_lock,th->os_thread);
327             if(prev) prev->next=next;
328             else all_threads=next;
329             release_spinlock(&all_threads_lock);
330             if(th->tls_cookie>=0) arch_os_thread_cleanup(th); 
331             os_invalidate((os_vm_address_t) th->control_stack_start,
332                           ((sizeof (lispobj))
333                            * (th->control_stack_end-th->control_stack_start)) +
334                           BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
335                           32*SIGSTKSZ);
336         } else 
337             prev=th;
338         th=next;
339     }
340 }
341
342 int interrupt_thread(os_thread_t tid, lispobj function)
343 {
344     struct thread *th;
345     for_each_thread(th) 
346         if((th->os_thread==tid) && (th->state != STATE_DEAD)) {
347             /* In clone_threads, if A and B both interrupt C at approximately 
348              * the same time, it does not matter: the second signal will be
349              * masked until the handler has returned from the first one.
350              * In pthreads though, we can't put the knowledge of what function
351              * to call into the siginfo, so we have to store it in the 
352              * destination thread, and do it in such a way that A won't 
353              * clobber B's interrupt.  Hence this stupid linked list.
354              *
355              * This does depend on SIG_INTERRUPT_THREAD being queued
356              * (as POSIX RT signals are): we need to keep
357              * interrupt_fun data for exactly as many signals as are
358              * going to be received by the destination thread.
359              */
360             struct cons *c;
361             int kill_status;
362             /* mask the signals in case this thread is being interrupted */
363             sigset_t newset,oldset;
364             sigemptyset(&newset);
365             sigaddset_blockable(&newset);
366             thread_sigmask(SIG_BLOCK, &newset, &oldset); 
367
368             get_spinlock(&th->interrupt_fun_lock,
369                          (int)arch_os_get_current_thread());
370             kill_status=thread_kill(th->os_thread,SIG_INTERRUPT_THREAD);
371             if(kill_status==0) {
372                 c=alloc_cons(function,th->interrupt_fun);
373                 th->interrupt_fun=c;
374             }
375             release_spinlock(&th->interrupt_fun_lock);
376             thread_sigmask(SIG_SETMASK,&oldset,0);
377             return (kill_status ? -1 : 0);
378         } 
379     errno=EPERM; return -1;
380 }
381
382 /* stopping the world is a two-stage process.  From this thread we signal 
383  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
384  * the usual pseudo-atomic checks (we don't want to stop a thread while 
385  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
386  */
387
388 void gc_stop_the_world()
389 {
390     struct thread *p,*th=arch_os_get_current_thread();
391 #ifdef QSHOW_SIGNALS
392     SHOW("gc_stop_the_world:begin");
393 #endif
394     /* keep threads from starting while the world is stopped. */
395     get_spinlock(&thread_start_lock,th->os_thread);
396 #ifdef QSHOW_SIGNALS
397     SHOW("gc_stop_the_world:locked");
398 #endif
399     /* stop all other threads by sending them SIG_STOP_FOR_GC */
400     for(p=all_threads; p; p=p->next) {
401         while(p->state==STATE_STARTING) sched_yield();
402         if((p!=th) && (p->os_thread!=0) && (p->state==STATE_RUNNING)) {
403             p->state=STATE_STOPPING;
404             if(thread_kill(p->os_thread,SIG_STOP_FOR_GC)==-1) {
405                 /* FIXME: we can't kill the thread; assume because it died
406                  * already */
407                 p->state=STATE_DEAD;
408             }
409         }
410     }
411 #ifdef QSHOW_SIGNALS
412     SHOW("gc_stop_the_world:signals sent");
413 #endif
414     /* wait for the running threads to stop */
415     for(p=all_threads;p;) {
416         if((p==th) || (p->os_thread==0) || (p->state==STATE_STARTING) ||
417            (p->state==STATE_DEAD) || (p->state==STATE_STOPPED)) {
418             p=p->next;
419         }
420     }
421 #ifdef QSHOW_SIGNALS
422     SHOW("gc_stop_the_world:end");
423 #endif
424 }
425
426 void gc_start_the_world()
427 {
428     struct thread *p,*th=arch_os_get_current_thread();
429     /* if a resumed thread creates a new thread before we're done with
430      * this loop, the new thread will get consed on the front of
431      * all_threads, but it won't have been stopped so won't need
432      * restarting; there can be threads just starting from before
433      * gc_stop_the_world, though */
434 #ifdef QSHOW_SIGNALS
435     SHOW("gc_start_the_world:begin");
436 #endif
437     for(p=all_threads;p;p=p->next) {
438         if((p!=th) && (p->os_thread!=0) && (p->state!=STATE_STARTING) &&
439            (p->state!=STATE_DEAD)) {
440             if(p->state!=STATE_STOPPED) {
441                 lose("gc_start_the_world: wrong thread state is %ld\n",
442                      fixnum_value(p->state));
443             }
444             thread_kill(p->os_thread,SIG_STOP_FOR_GC);
445         }
446     }
447     /* we must wait for all threads to leave stopped state else we
448      * risk signal accumulation and lose any meaning of
449      * thread->state */
450     for(p=all_threads;p;) {
451         gc_assert(p->state!=STATE_STOPPING);
452         if((p==th) || (p->os_thread==0) || (p->state!=STATE_STOPPED)) {
453             p=p->next;
454         }
455     }
456     release_spinlock(&thread_start_lock);
457 #ifdef QSHOW_SIGNALS
458     SHOW("gc_start_the_world:end");
459 #endif
460 }
461 #endif