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