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