0.9.4.8:
[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             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
184         }
185 #define STATIC_TLS_INIT(sym,field) \
186   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
187   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
188
189         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
190         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
191         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
192         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
193         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
194 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
195         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
196         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
197 #endif
198 #undef STATIC_TLS_INIT
199 #endif
200     }
201
202     th=&per_thread->thread;
203     th->control_stack_start = spaces;
204     th->binding_stack_start=
205         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
206     th->control_stack_end = th->binding_stack_start;
207     th->alien_stack_start=
208         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
209     th->binding_stack_pointer=th->binding_stack_start;
210     th->this=th;
211     th->os_thread=0;
212     th->interrupt_fun=NIL;
213     th->interrupt_fun_lock=0;
214     th->state=STATE_STARTING;
215 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
216     th->alien_stack_pointer=((void *)th->alien_stack_start
217                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
218 #else
219     th->alien_stack_pointer=((void *)th->alien_stack_start);
220 #endif
221 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
222     th->pseudo_atomic_interrupted=0;
223     th->pseudo_atomic_atomic=0;
224 #endif
225 #ifdef LISP_FEATURE_GENCGC
226     gc_set_region_empty(&th->alloc_region);
227 #endif
228
229 #ifndef LISP_FEATURE_SB_THREAD
230     /* the tls-points-into-struct-thread trick is only good for threaded
231      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
232      * appropriate values from struct thread here, and make sure that
233      * we use the appropriate SymbolValue macros to access any of the
234      * variable quantities from the C runtime.  It's not quite OAOOM,
235      * it just feels like it */
236     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
237     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
238     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
239 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
240     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
241     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
242     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
243     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
244 #else
245     current_binding_stack_pointer=th->binding_stack_pointer;
246     current_control_stack_pointer=th->control_stack_start;
247 #endif
248 #endif
249     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
250     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
251     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
252     bind_variable(INTERRUPT_PENDING, NIL,th);
253     bind_variable(INTERRUPTS_ENABLED,T,th);
254     bind_variable(GC_PENDING,NIL,th);
255 #ifdef LISP_FEATURE_SB_THREAD
256     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
257 #endif
258
259     th->interrupt_data = (struct interrupt_data *)
260         os_validate(0,(sizeof (struct interrupt_data)));
261     if (!th->interrupt_data) {
262         free_thread_struct(th);
263         return 0;
264     }
265     if(all_threads)
266         memcpy(th->interrupt_data,
267                arch_os_get_current_thread()->interrupt_data,
268                sizeof (struct interrupt_data));
269     else
270         memcpy(th->interrupt_data,global_interrupt_data,
271                sizeof (struct interrupt_data));
272
273     th->no_tls_value_marker=initial_function;
274     return th;
275 }
276
277 static void
278 link_thread(struct thread *th,os_thread_t kid_tid)
279 {
280     if (all_threads) all_threads->prev=th;
281     th->next=all_threads;
282     th->prev=0;
283     all_threads=th;
284     /* note that th->os_thread is 0 at this time.  We rely on
285      * all_threads_lock to ensure that we don't have >1 thread with
286      * os_thread=0 on the list at once
287      */
288     protect_control_stack_guard_page(th,1);
289     /* child will not start until this is set */
290     th->os_thread=kid_tid;
291     FSHOW((stderr,"/created thread %lu\n",kid_tid));
292 }
293
294 void create_initial_thread(lispobj initial_function) {
295     struct thread *th=create_thread_struct(initial_function);
296     os_thread_t kid_tid=thread_self();
297     if(th && kid_tid>0) {
298         link_thread(th,kid_tid);
299         initial_thread_trampoline(all_threads); /* no return */
300     } else lose("can't create initial thread");
301 }
302
303 #ifdef LISP_FEATURE_SB_THREAD
304
305 #ifndef __USE_XOPEN2K
306 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
307                                   size_t __stacksize);
308 #endif
309
310 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
311 {
312     /* The new thread inherits the restrictive signal mask set here,
313      * and enables signals again when it is set up properly. */
314     pthread_attr_t attr;
315     sigset_t newset,oldset;
316     boolean r=1;
317     sigemptyset(&newset);
318     /* Blocking deferrable signals is enough, since gc_stop_the_world
319      * waits until the child leaves STATE_STARTING. And why not let gc
320      * proceed as soon as possible? */
321     sigaddset_deferrable(&newset);
322     thread_sigmask(SIG_BLOCK, &newset, &oldset);
323
324     if((pthread_attr_init(&attr)) ||
325        (pthread_attr_setstack(&attr,th->control_stack_start,
326                               THREAD_CONTROL_STACK_SIZE-16)) ||
327        (pthread_create
328         (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
329         r=0;
330     thread_sigmask(SIG_SETMASK,&oldset,0);
331     return r;
332 }
333
334 struct thread *create_thread(lispobj initial_function) {
335     struct thread *th;
336     os_thread_t kid_tid=0;
337     boolean success;
338
339     if(linux_no_threads_p) return 0;
340
341     th=create_thread_struct(initial_function);
342     if(th==0) return 0;
343
344     /* we must not be interrupted here after a successful
345      * create_os_thread, because the kid will be waiting for its
346      * thread struct to be linked */
347     GET_ALL_THREADS_LOCK("create_thread")
348
349     success=create_os_thread(th,&kid_tid);
350     if (success)
351         link_thread(th,kid_tid);
352     else
353         free_thread_struct(th);
354
355     RELEASE_ALL_THREADS_LOCK("create_thread")
356
357     if (success)
358         return th;
359     else
360         return 0;
361 }
362
363 /* called from lisp from the thread object finalizer */
364 void reap_dead_thread(struct thread *th)
365 {
366     if(th->state!=STATE_DEAD)
367         lose("thread %p is not joinable, state=%d\n",th,th->state);
368 #ifdef LISP_FEATURE_GENCGC
369     {
370         sigset_t newset,oldset;
371         sigemptyset(&newset);
372         sigaddset_blockable(&newset);
373         thread_sigmask(SIG_BLOCK, &newset, &oldset);
374         gc_alloc_update_page_tables(0, &th->alloc_region);
375         thread_sigmask(SIG_SETMASK,&oldset,0);
376     }
377 #endif
378     GET_ALL_THREADS_LOCK("reap_dead_thread")
379     FSHOW((stderr,"/reap_dead_thread: reaping %lu\n",th->os_thread));
380     if(th->prev)
381         th->prev->next=th->next;
382     else all_threads=th->next;
383     if(th->next)
384         th->next->prev=th->prev;
385     RELEASE_ALL_THREADS_LOCK("reap_dead_thread")
386     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
387     gc_assert(pthread_join(th->os_thread,NULL)==0);
388     free_thread_struct(th);
389 }
390
391 /* Send the signo to os_thread, retry if the rt signal queue is
392  * full. */
393 static int kill_thread_safely(os_thread_t os_thread, int signo)
394 {
395     int r;
396     /* The man page does not mention EAGAIN as a valid return value
397      * for either pthread_kill or kill. But that's theory, this is
398      * practice. By waiting here we assume that the delivery of this
399      * signal is not necessary for the delivery of the signals in the
400      * queue. In other words, we _assume_ there are no deadlocks. */
401     while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
402         /* wait a bit then try again in the hope of the rt signal
403          * queue not being full */
404         FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
405         /* FIXME: some kind of backoff (random, exponential) would be
406          * nice. */
407         sleep(1);
408     }
409     return r;
410 }
411
412 int interrupt_thread(struct thread *th, lispobj function)
413 {
414     /* In clone_threads, if A and B both interrupt C at approximately
415      * the same time, it does not matter: the second signal will be
416      * masked until the handler has returned from the first one.  In
417      * pthreads though, we can't put the knowledge of what function to
418      * call into the siginfo, so we have to store it in the
419      * destination thread, and do it in such a way that A won't
420      * clobber B's interrupt.  Hence, this stupid linked list.
421      *
422      * This does depend on SIG_INTERRUPT_THREAD being queued (as POSIX
423      * RT signals are): we need to keep interrupt_fun data for exactly
424      * as many signals as are going to be received by the destination
425      * thread.
426      */
427     lispobj c=alloc_cons(function,NIL);
428     sigset_t newset,oldset;
429     sigemptyset(&newset);
430     /* interrupt_thread_handler locks this spinlock with blockables
431      * blocked (it does so for the sake of
432      * arrange_return_to_lisp_function), so we must also block them or
433      * else SIG_STOP_FOR_GC and all_threads_lock will find a way to
434      * deadlock. */
435     sigaddset_blockable(&newset);
436     thread_sigmask(SIG_BLOCK, &newset, &oldset);
437     if (th == arch_os_get_current_thread())
438         lose("cannot interrupt current thread");
439     get_spinlock(&th->interrupt_fun_lock,
440                  (long)arch_os_get_current_thread());
441     ((struct cons *)native_pointer(c))->cdr=th->interrupt_fun;
442     th->interrupt_fun=c;
443     release_spinlock(&th->interrupt_fun_lock);
444     thread_sigmask(SIG_SETMASK,&oldset,0);
445     /* Called from lisp with the thread object as a parameter. Thus,
446      * the object cannot be garbage collected and consequently reaped
447      * and joined. Because it's not joined, kill should work (even if
448      * the thread has died/exited). */
449     {
450         int status=kill_thread_safely(th->os_thread,SIG_INTERRUPT_THREAD);
451         if (status==0) {
452             return 0;
453         } else if (status==ESRCH) {
454             /* This thread has exited. */
455             th->interrupt_fun=NIL;
456             errno=ESRCH;
457             return -1;
458         } else {
459             lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
460                  th->os_thread,status,strerror(status));
461         }
462     }
463 }
464
465 /* stopping the world is a two-stage process.  From this thread we signal
466  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
467  * the usual pseudo-atomic checks (we don't want to stop a thread while
468  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
469  */
470
471 /* To avoid deadlocks when gc stops the world all clients of each
472  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
473  * holding the lock, but they must agree on which. */
474 void gc_stop_the_world()
475 {
476     struct thread *p,*th=arch_os_get_current_thread();
477     int status;
478     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
479                   th->os_thread));
480     /* keep threads from starting while the world is stopped. */
481     pthread_mutex_lock(&all_threads_lock); \
482     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
483                   th->os_thread));
484     /* stop all other threads by sending them SIG_STOP_FOR_GC */
485     for(p=all_threads; p; p=p->next) {
486         while(p->state==STATE_STARTING) sched_yield();
487         if((p!=th) && (p->state==STATE_RUNNING)) {
488             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
489                           p->os_thread));
490             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
491             if (status==ESRCH) {
492                 /* This thread has exited. */
493                 gc_assert(p->state==STATE_DEAD);
494             } else if (status) {
495                 lose("cannot send suspend thread=%lu: %d, %s",
496                      p->os_thread,status,strerror(status));
497             }
498         }
499     }
500     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
501     /* wait for the running threads to stop or finish */
502     for(p=all_threads;p;) {
503         gc_assert(p->os_thread!=0);
504         gc_assert(p->state!=STATE_STARTING);
505         if((p==th) || (p->state==STATE_SUSPENDED) ||
506            (p->state==STATE_DEAD)) {
507             p=p->next;
508         } else {
509             sched_yield();
510         }
511     }
512     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
513 }
514
515 void gc_start_the_world()
516 {
517     struct thread *p,*th=arch_os_get_current_thread();
518     int status;
519     /* if a resumed thread creates a new thread before we're done with
520      * this loop, the new thread will get consed on the front of
521      * all_threads, but it won't have been stopped so won't need
522      * restarting */
523     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
524     for(p=all_threads;p;p=p->next) {
525         gc_assert(p->os_thread!=0);
526         if((p!=th) && (p->state!=STATE_DEAD)) {
527             if(p->state!=STATE_SUSPENDED) {
528                 lose("gc_start_the_world: wrong thread state is %d\n",
529                      fixnum_value(p->state));
530             }
531             FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
532                           p->os_thread));
533             p->state=STATE_RUNNING;
534             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
535             if (status) {
536                 lose("cannot resume thread=%lu: %d, %s",
537                      p->os_thread,status,strerror(status));
538             }
539         }
540     }
541     /* If we waited here until all threads leave STATE_SUSPENDED, then
542      * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
543      * performance implications, but does away with the 'rt signal
544      * queue full' problem. */
545     pthread_mutex_unlock(&all_threads_lock); \
546     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
547 }
548 #endif