0.9.3.34: cosmetics
[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     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 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
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 #ifndef __USE_XOPEN2K
274 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
275                                   size_t __stacksize);
276 #endif
277
278 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
279 {
280     /* The new thread inherits the restrictive signal mask set here,
281      * and enables signals again when it is set up properly. */
282     pthread_attr_t attr;
283     sigset_t newset,oldset;
284     boolean r=1;
285     sigemptyset(&newset);
286     sigaddset_blockable(&newset);
287     thread_sigmask(SIG_BLOCK, &newset, &oldset);
288
289     if((pthread_attr_init(&attr)) ||
290        (pthread_attr_setstack(&attr,th->control_stack_start,
291                               THREAD_CONTROL_STACK_SIZE-16)) ||
292        (pthread_create
293         (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
294         r=0;
295     thread_sigmask(SIG_SETMASK,&oldset,0);
296     return r;
297 }
298
299 struct thread *create_thread(lispobj initial_function) {
300     struct thread *th;
301     os_thread_t kid_tid=0;
302     boolean success;
303
304     if(linux_no_threads_p) return 0;
305
306     th=create_thread_struct(initial_function);
307     if(th==0) return 0;
308
309     /* we must not be interrupted here after a successful
310      * create_os_thread, because the kid will be waiting for its
311      * thread struct to be linked */
312     GET_ALL_THREADS_LOCK("create_thread")
313
314     success=create_os_thread(th,&kid_tid);
315     if (success)
316         link_thread(th,kid_tid);
317     else
318         os_invalidate((os_vm_address_t) th->control_stack_start,
319                       ((sizeof (lispobj))
320                        * (th->control_stack_end-th->control_stack_start)) +
321                       BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
322                       32*SIGSTKSZ);
323
324     RELEASE_ALL_THREADS_LOCK("create_thread")
325
326     if (success)
327         return th;
328     else
329         return 0;
330 }
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 %p 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 %lu\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         lispobj c=alloc_cons(function,NIL);
384         int kill_status;
385         /* interrupt_thread_handler locks this spinlock with
386          * interrupts blocked (it does so for the sake of
387          * arrange_return_to_lisp_function), so we must also block
388          * them or else SIG_STOP_FOR_GC and all_threads_lock will find
389          * a way to deadlock. */
390         sigset_t newset,oldset;
391         sigemptyset(&newset);
392         sigaddset_blockable(&newset);
393         thread_sigmask(SIG_BLOCK, &newset, &oldset);
394         get_spinlock(&th->interrupt_fun_lock,
395                      (long)arch_os_get_current_thread());
396         kill_status=thread_kill(th->os_thread,SIG_INTERRUPT_THREAD);
397         if(kill_status==0) {
398             ((struct cons *)native_pointer(c))->cdr=th->interrupt_fun;
399             th->interrupt_fun=c;
400         }
401         release_spinlock(&th->interrupt_fun_lock);
402         thread_sigmask(SIG_SETMASK,&oldset,0);
403         return (kill_status ? -1 : 0);
404     }
405     errno=EPERM; return -1;
406 }
407
408 /* stopping the world is a two-stage process.  From this thread we signal
409  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
410  * the usual pseudo-atomic checks (we don't want to stop a thread while
411  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
412  */
413
414 /* To avoid deadlocks when gc stops the world all clients of each
415  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
416  * holding the lock, but they must agree on which. */
417 void gc_stop_the_world()
418 {
419     struct thread *p,*th=arch_os_get_current_thread();
420     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
421                   th->os_thread));
422     /* keep threads from starting while the world is stopped. */
423     get_spinlock(&all_threads_lock,(long)th);
424     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
425                   th->os_thread));
426     /* stop all other threads by sending them SIG_STOP_FOR_GC */
427     for(p=all_threads; p; p=p->next) {
428         while(p->state==STATE_STARTING) sched_yield();
429         if((p!=th) && (p->state==STATE_RUNNING)) {
430             FSHOW_SIGNAL((stderr, "/gc_stop_the_world: suspending %lu\n",
431                           p->os_thread));
432             if(thread_kill(p->os_thread,SIG_STOP_FOR_GC)==-1) {
433                 /* we can't kill the thread; assume because it died
434                  * since we last checked */
435                 p->state=STATE_DEAD;
436                 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:assuming %lu dead\n",
437                    p->os_thread));
438             }
439         }
440     }
441     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
442     /* wait for the running threads to stop or finish */
443     for(p=all_threads;p;) {
444         gc_assert(p->os_thread!=0);
445         gc_assert(p->state!=STATE_STARTING);
446         if((p==th) || (p->state==STATE_SUSPENDED) ||
447            (p->state==STATE_DEAD)) {
448             p=p->next;
449         }
450     }
451     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
452 }
453
454 void gc_start_the_world()
455 {
456     struct thread *p,*th=arch_os_get_current_thread();
457     /* if a resumed thread creates a new thread before we're done with
458      * this loop, the new thread will get consed on the front of
459      * all_threads, but it won't have been stopped so won't need
460      * restarting */
461     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
462     for(p=all_threads;p;p=p->next) {
463         gc_assert(p->os_thread!=0);
464         if((p!=th) && (p->state!=STATE_DEAD)) {
465             if(p->state!=STATE_SUSPENDED) {
466                 lose("gc_start_the_world: wrong thread state is %d\n",
467                      fixnum_value(p->state));
468             }
469             FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
470                           p->os_thread));
471             thread_kill(p->os_thread,SIG_STOP_FOR_GC);
472         }
473     }
474     /* we must wait for all threads to leave suspended state else we
475      * risk signal accumulation and lose any meaning of
476      * thread->state */
477     for(p=all_threads;p;) {
478         if((p==th) || (p->state!=STATE_SUSPENDED)) {
479             p=p->next;
480         }
481     }
482     release_spinlock(&all_threads_lock);
483     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
484 }
485 #endif