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