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