0.9.8.7:
[sbcl.git] / src / runtime / thread.c
1 /*
2  * This software is part of the SBCL system. See the README file for
3  * more information.
4  *
5  * This software is derived from the CMU CL system, which was
6  * written at Carnegie Mellon University and released into the
7  * public domain. The software is in the public domain and is
8  * provided with absolutely no warranty. See the COPYING and CREDITS
9  * files for more information.
10  */
11
12 #include "sbcl.h"
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #ifndef LISP_FEATURE_WIN32
18 #include <sched.h>
19 #endif
20 #include <signal.h>
21 #include <stddef.h>
22 #include <errno.h>
23 #include <sys/types.h>
24 #ifndef LISP_FEATURE_WIN32
25 #include <sys/wait.h>
26 #endif
27
28 #include "runtime.h"
29 #include "validate.h"           /* for CONTROL_STACK_SIZE etc */
30 #include "alloc.h"
31 #include "thread.h"
32 #include "arch.h"
33 #include "target-arch-os.h"
34 #include "os.h"
35 #include "globals.h"
36 #include "dynbind.h"
37 #include "genesis/cons.h"
38 #include "genesis/fdefn.h"
39 #include "interr.h"             /* for lose() */
40 #include "gc-internal.h"
41
42 #ifdef LISP_FEATURE_WIN32
43 /*
44  * Win32 doesn't have SIGSTKSZ, and we're not switching stacks anyway,
45  * so define it arbitrarily
46  */
47 #define SIGSTKSZ 1024
48 #endif
49
50 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
51
52 struct freeable_stack {
53     os_thread_t os_thread;
54     os_vm_address_t stack;
55 };
56
57 static struct freeable_stack * volatile freeable_stack = 0;
58
59 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
60 struct thread * volatile all_threads;
61 extern struct interrupt_data * global_interrupt_data;
62 extern int linux_no_threads_p;
63
64 #ifdef LISP_FEATURE_SB_THREAD
65 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
66 #endif
67
68 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
69 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs);
70 #endif
71
72 static void
73 link_thread(struct thread *th)
74 {
75     if (all_threads) all_threads->prev=th;
76     th->next=all_threads;
77     th->prev=0;
78     all_threads=th;
79 }
80
81 #ifdef LISP_FEATURE_SB_THREAD
82 static void
83 unlink_thread(struct thread *th)
84 {
85     if (th->prev)
86         th->prev->next = th->next;
87     else
88         all_threads = th->next;
89     if (th->next)
90         th->next->prev = th->prev;
91 }
92 #endif
93
94 static int
95 initial_thread_trampoline(struct thread *th)
96 {
97     lispobj function;
98 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
99     lispobj *args = NULL;
100 #endif
101     function = th->no_tls_value_marker;
102     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
103     if(arch_os_thread_init(th)==0) return 1;
104     link_thread(th);
105     th->os_thread=thread_self();
106     protect_control_stack_guard_page(1);
107
108 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
109     return call_into_lisp_first_time(function,args,0);
110 #else
111     return funcall0(function);
112 #endif
113 }
114
115 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
116                             ALIEN_STACK_SIZE + dynamic_values_bytes + \
117                             32 * SIGSTKSZ)
118
119 #ifdef LISP_FEATURE_SB_THREAD
120
121 static void
122 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
123 {
124     struct freeable_stack *new_freeable_stack = 0;
125     if (thread_to_be_cleaned_up) {
126         new_freeable_stack = (struct freeable_stack *)
127             os_validate(0, sizeof(struct freeable_stack));
128         new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
129         new_freeable_stack->stack = (os_vm_address_t)
130             thread_to_be_cleaned_up->control_stack_start;
131     }
132     new_freeable_stack = (struct freeable_stack *)
133         swap_lispobjs((lispobj *)(void *)&freeable_stack,
134                       (lispobj)new_freeable_stack);
135     if (new_freeable_stack) {
136         FSHOW((stderr,"/reaping %lu\n", new_freeable_stack->os_thread));
137         /* Under NPTL pthread_join really waits until the thread
138          * exists and the stack can be safely freed. This is sadly not
139          * mandated by the pthread spec. */
140         gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
141         os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
142         os_invalidate((os_vm_address_t) new_freeable_stack,
143                       sizeof(struct freeable_stack));
144     }
145 }
146
147 /* this is the first thing that runs in the child (which is why the
148  * silly calling convention).  Basically it calls the user's requested
149  * lisp function after doing arch_os_thread_init and whatever other
150  * bookkeeping needs to be done
151  */
152 int
153 new_thread_trampoline(struct thread *th)
154 {
155     lispobj function;
156     int result;
157     FSHOW((stderr,"/creating thread %lu\n", thread_self()));
158     function = th->no_tls_value_marker;
159     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
160     if(arch_os_thread_init(th)==0) {
161         /* FIXME: handle error */
162         lose("arch_os_thread_init failed\n");
163     }
164
165     th->os_thread=thread_self();
166     protect_control_stack_guard_page(1);
167     /* Since GC can only know about this thread from the all_threads
168      * list and we're just adding this thread to it there is no danger
169      * of deadlocking even with SIG_STOP_FOR_GC blocked (which it is
170      * not). */
171     pthread_mutex_lock(&all_threads_lock);
172     link_thread(th);
173     pthread_mutex_unlock(&all_threads_lock);
174
175     result = funcall0(function);
176     th->state=STATE_DEAD;
177
178     /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
179      * thread, but since we are already dead it won't wait long. */
180     pthread_mutex_lock(&all_threads_lock);
181     gc_alloc_update_page_tables(0, &th->alloc_region);
182     unlink_thread(th);
183     pthread_mutex_unlock(&all_threads_lock);
184
185     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
186     os_invalidate((os_vm_address_t)th->interrupt_data,
187                   (sizeof (struct interrupt_data)));
188     free_thread_stack_later(th);
189     FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
190     return result;
191 }
192
193 #endif /* LISP_FEATURE_SB_THREAD */
194
195 static void
196 free_thread_struct(struct thread *th)
197 {
198     if (th->interrupt_data)
199         os_invalidate((os_vm_address_t) th->interrupt_data,
200                       (sizeof (struct interrupt_data)));
201     os_invalidate((os_vm_address_t) th->control_stack_start,
202                   THREAD_STRUCT_SIZE);
203 }
204
205 /* this is called from any other thread to create the new one, and
206  * initialize all parts of it that can be initialized from another
207  * thread
208  */
209
210 static struct thread *
211 create_thread_struct(lispobj initial_function) {
212     union per_thread_data *per_thread;
213     struct thread *th=0;        /*  subdue gcc */
214     void *spaces=0;
215 #ifdef LISP_FEATURE_SB_THREAD
216     int i;
217 #endif
218
219     /* may as well allocate all the spaces at once: it saves us from
220      * having to decide what to do if only some of the allocations
221      * succeed */
222     spaces=os_validate(0, THREAD_STRUCT_SIZE);
223     if(!spaces)
224          return NULL;
225     per_thread=(union per_thread_data *)
226         (spaces+
227          THREAD_CONTROL_STACK_SIZE+
228          BINDING_STACK_SIZE+
229          ALIEN_STACK_SIZE);
230
231 #ifdef LISP_FEATURE_SB_THREAD
232     for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
233         per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
234     if (all_threads == 0) {
235         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
236             SetSymbolValue
237                 (FREE_TLS_INDEX,
238                  /* FIXME: should be MAX_INTERRUPTS -1 ? */
239                  make_fixnum(MAX_INTERRUPTS+
240                              sizeof(struct thread)/sizeof(lispobj)),
241                  0);
242             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
243         }
244 #define STATIC_TLS_INIT(sym,field) \
245   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
246   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
247
248         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
249         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
250         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
251         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
252         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
253 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
254         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
255         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
256 #endif
257 #undef STATIC_TLS_INIT
258     }
259 #endif
260
261     th=&per_thread->thread;
262     th->control_stack_start = spaces;
263     th->binding_stack_start=
264         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
265     th->control_stack_end = th->binding_stack_start;
266     th->alien_stack_start=
267         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
268     th->binding_stack_pointer=th->binding_stack_start;
269     th->this=th;
270     th->os_thread=0;
271     th->state=STATE_RUNNING;
272 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
273     th->alien_stack_pointer=((void *)th->alien_stack_start
274                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
275 #else
276     th->alien_stack_pointer=((void *)th->alien_stack_start);
277 #endif
278 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
279     th->pseudo_atomic_interrupted=0;
280     th->pseudo_atomic_atomic=0;
281 #endif
282 #ifdef LISP_FEATURE_GENCGC
283     gc_set_region_empty(&th->alloc_region);
284 #endif
285
286 #ifndef LISP_FEATURE_SB_THREAD
287     /* the tls-points-into-struct-thread trick is only good for threaded
288      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
289      * appropriate values from struct thread here, and make sure that
290      * we use the appropriate SymbolValue macros to access any of the
291      * variable quantities from the C runtime.  It's not quite OAOOM,
292      * it just feels like it */
293     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
294     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
295     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
296 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
297     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
298     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
299     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
300     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
301 #else
302     current_binding_stack_pointer=th->binding_stack_pointer;
303     current_control_stack_pointer=th->control_stack_start;
304 #endif
305 #endif
306     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
307     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
308     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
309     bind_variable(INTERRUPT_PENDING, NIL,th);
310     bind_variable(INTERRUPTS_ENABLED,T,th);
311     bind_variable(GC_PENDING,NIL,th);
312 #ifdef LISP_FEATURE_SB_THREAD
313     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
314 #endif
315
316     th->interrupt_data = (struct interrupt_data *)
317         os_validate(0,(sizeof (struct interrupt_data)));
318     if (!th->interrupt_data) {
319         free_thread_struct(th);
320         return 0;
321     }
322     th->interrupt_data->pending_handler = 0;
323     th->no_tls_value_marker=initial_function;
324     return th;
325 }
326
327 void create_initial_thread(lispobj initial_function) {
328     struct thread *th=create_thread_struct(initial_function);
329     if(th) {
330         initial_thread_trampoline(th); /* no return */
331     } else lose("can't create initial thread\n");
332 }
333
334 #ifdef LISP_FEATURE_SB_THREAD
335
336 #ifndef __USE_XOPEN2K
337 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
338                                   size_t __stacksize);
339 #endif
340
341 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
342 {
343     /* The new thread inherits the restrictive signal mask set here,
344      * and enables signals again when it is set up properly. */
345     pthread_attr_t attr;
346     sigset_t newset,oldset;
347     boolean r=1;
348     sigemptyset(&newset);
349     /* Blocking deferrable signals is enough, no need to block
350      * SIG_STOP_FOR_GC because the child process is not linked onto
351      * all_threads until it's ready. */
352     sigaddset_deferrable(&newset);
353     thread_sigmask(SIG_BLOCK, &newset, &oldset);
354
355     if((pthread_attr_init(&attr)) ||
356        (pthread_attr_setstack(&attr,th->control_stack_start,
357                               THREAD_CONTROL_STACK_SIZE-16)) ||
358        (pthread_create
359         (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
360         r=0;
361     thread_sigmask(SIG_SETMASK,&oldset,0);
362     return r;
363 }
364
365 os_thread_t create_thread(lispobj initial_function) {
366     struct thread *th;
367     os_thread_t kid_tid;
368
369     if(linux_no_threads_p) return 0;
370
371     /* Assuming that a fresh thread struct has no lisp objects in it,
372      * linking it to all_threads can be left to the thread itself
373      * without fear of gc lossage. initial_function violates this
374      * assumption and must stay pinned until the child starts up. */
375     th = create_thread_struct(initial_function);
376     if(th==0) return 0;
377
378     if (create_os_thread(th,&kid_tid)) {
379         return kid_tid;
380     } else {
381         free_thread_struct(th);
382         return 0;
383     }
384 }
385
386 /* Send the signo to os_thread, retry if the rt signal queue is
387  * full. */
388 static int kill_thread_safely(os_thread_t os_thread, int signo)
389 {
390     int r;
391     /* The man page does not mention EAGAIN as a valid return value
392      * for either pthread_kill or kill. But that's theory, this is
393      * practice. By waiting here we assume that the delivery of this
394      * signal is not necessary for the delivery of the signals in the
395      * queue. In other words, we _assume_ there are no deadlocks. */
396     while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
397         /* wait a bit then try again in the hope of the rt signal
398          * queue not being full */
399         FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
400         /* FIXME: some kind of backoff (random, exponential) would be
401          * nice. */
402         sleep(1);
403     }
404     return r;
405 }
406
407 int signal_interrupt_thread(os_thread_t os_thread)
408 {
409     int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
410     if (status == 0) {
411         return 0;
412     } else if (status == ESRCH) {
413         return -1;
414     } else {
415         lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s\n",
416              os_thread, status, strerror(status));
417     }
418 }
419
420 /* stopping the world is a two-stage process.  From this thread we signal
421  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
422  * the usual pseudo-atomic checks (we don't want to stop a thread while
423  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
424  */
425
426 /* To avoid deadlocks when gc stops the world all clients of each
427  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
428  * holding the lock, but they must agree on which. */
429 void gc_stop_the_world()
430 {
431     struct thread *p,*th=arch_os_get_current_thread();
432     int status;
433     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
434                   th->os_thread));
435     /* keep threads from starting while the world is stopped. */
436     pthread_mutex_lock(&all_threads_lock); \
437     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
438                   th->os_thread));
439     /* stop all other threads by sending them SIG_STOP_FOR_GC */
440     for(p=all_threads; p; p=p->next) {
441         gc_assert(p->os_thread != 0);
442         if((p!=th) && ((p->state==STATE_RUNNING))) {
443             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
444                           p->os_thread));
445             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
446             if (status==ESRCH) {
447                 /* This thread has exited. */
448                 gc_assert(p->state==STATE_DEAD);
449             } else if (status) {
450                 lose("cannot send suspend thread=%lu: %d, %s\n",
451                      p->os_thread,status,strerror(status));
452             }
453         }
454     }
455     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
456     /* wait for the running threads to stop or finish */
457     for(p=all_threads;p;) {
458         if((p!=th) && (p->state==STATE_RUNNING)) {
459             sched_yield();
460         } else {
461             p=p->next;
462         }
463     }
464     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
465 }
466
467 void gc_start_the_world()
468 {
469     struct thread *p,*th=arch_os_get_current_thread();
470     int status;
471     /* if a resumed thread creates a new thread before we're done with
472      * this loop, the new thread will get consed on the front of
473      * all_threads, but it won't have been stopped so won't need
474      * restarting */
475     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
476     for(p=all_threads;p;p=p->next) {
477         gc_assert(p->os_thread!=0);
478         if((p!=th) && (p->state!=STATE_DEAD)) {
479             if(p->state!=STATE_SUSPENDED) {
480                 lose("gc_start_the_world: wrong thread state is %d\n",
481                      fixnum_value(p->state));
482             }
483             FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
484                           p->os_thread));
485             p->state=STATE_RUNNING;
486             status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
487             if (status) {
488                 lose("cannot resume thread=%lu: %d, %s\n",
489                      p->os_thread,status,strerror(status));
490             }
491         }
492     }
493     /* If we waited here until all threads leave STATE_SUSPENDED, then
494      * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
495      * performance implications, but does away with the 'rt signal
496      * queue full' problem. */
497     pthread_mutex_unlock(&all_threads_lock); \
498     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
499 }
500 #endif