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