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