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