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