0.8.21.41
[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 "thread.h"
15 #include "arch.h"
16 #include "target-arch-os.h"
17 #include "os.h"
18 #include "globals.h"
19 #include "dynbind.h"
20 #include "genesis/cons.h"
21 #include "genesis/fdefn.h"
22 #include "interr.h"             /* for lose() */
23 #include "gc-internal.h"
24
25 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
26
27 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
28 struct thread *all_threads;
29 volatile lispobj all_threads_lock;
30 extern struct interrupt_data * global_interrupt_data;
31 extern int linux_no_threads_p;
32
33 int
34 initial_thread_trampoline(struct thread *th)
35 {
36     lispobj function;
37     lispobj *args = NULL;
38     function = th->unbound_marker;
39     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
40     if(arch_os_thread_init(th)==0) return 1;
41
42     if(th->pid < 1) lose("th->pid not set up right");
43     th->state=STATE_RUNNING;
44 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
45     return call_into_lisp_first_time(function,args,0);
46 #else
47     return funcall0(function);
48 #endif
49 }
50
51 /* this is the first thing that clone() runs in the child (which is
52  * why the silly calling convention).  Basically it calls the user's
53  * requested lisp function after doing arch_os_thread_init and
54  * whatever other bookkeeping needs to be done
55  */
56
57 #ifdef LISP_FEATURE_SB_THREAD
58 int
59 new_thread_trampoline(struct thread *th)
60 {
61     lispobj function;
62     function = th->unbound_marker;
63     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
64     if(arch_os_thread_init(th)==0) return 1;    
65
66     /* wait here until our thread is linked into all_threads: see below */
67     while(th->pid<1) sched_yield();
68
69     th->state=STATE_RUNNING;
70     return funcall0(function);
71 }
72 #endif /* LISP_FEATURE_SB_THREAD */
73
74 /* this is called from any other thread to create the new one, and
75  * initialize all parts of it that can be initialized from another 
76  * thread 
77  */
78
79 struct thread * create_thread_struct(lispobj initial_function) {
80     union per_thread_data *per_thread;
81     struct thread *th=0;        /*  subdue gcc */
82     void *spaces=0;
83
84     /* may as well allocate all the spaces at once: it saves us from
85      * having to decide what to do if only some of the allocations
86      * succeed */
87     spaces=os_validate(0,
88                        THREAD_CONTROL_STACK_SIZE+
89                        BINDING_STACK_SIZE+
90                        ALIEN_STACK_SIZE+
91                        dynamic_values_bytes+
92                        32*SIGSTKSZ
93                        );
94     if(!spaces) goto cleanup;
95     per_thread=(union per_thread_data *)
96         (spaces+
97          THREAD_CONTROL_STACK_SIZE+
98          BINDING_STACK_SIZE+
99          ALIEN_STACK_SIZE);
100
101     th=&per_thread->thread;
102     if(all_threads) {
103         memcpy(per_thread,arch_os_get_current_thread(),
104                dynamic_values_bytes);
105     } else {
106 #ifdef LISP_FEATURE_SB_THREAD
107         int i;
108         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
109             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
110         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
111             SetSymbolValue
112                 (FREE_TLS_INDEX,
113                  make_fixnum(MAX_INTERRUPTS+
114                              sizeof(struct thread)/sizeof(lispobj)),
115                  0);
116 #define STATIC_TLS_INIT(sym,field) \
117   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
118   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
119                                   
120         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
121         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
122         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
123         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
124         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
125 #ifdef LISP_FEATURE_X86
126         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
127         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
128 #endif
129 #undef STATIC_TLS_INIT
130 #endif
131     }
132
133     th->control_stack_start = spaces;
134     th->binding_stack_start=
135         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
136     th->control_stack_end = th->binding_stack_start;
137     th->alien_stack_start=
138         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
139     th->binding_stack_pointer=th->binding_stack_start;
140     th->this=th;
141     th->pid=0;
142     th->state=STATE_STOPPED;
143 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
144     th->alien_stack_pointer=((void *)th->alien_stack_start
145                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
146 #else
147     th->alien_stack_pointer=((void *)th->alien_stack_start);
148 #endif
149 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
150     th->pseudo_atomic_interrupted=0;
151     th->pseudo_atomic_atomic=0;
152 #endif
153 #ifdef LISP_FEATURE_GENCGC
154     gc_set_region_empty(&th->alloc_region);
155 #endif
156
157 #ifndef LISP_FEATURE_SB_THREAD
158     /* the tls-points-into-struct-thread trick is only good for threaded
159      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
160      * appropriate values from struct thread here, and make sure that 
161      * we use the appropriate SymbolValue macros to access any of the
162      * variable quantities from the C runtime.  It's not quite OAOOM,
163      * it just feels like it */
164     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
165     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
166     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
167 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
168     SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
169     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
170     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
171     SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
172 #else
173     current_binding_stack_pointer=th->binding_stack_pointer;
174     current_control_stack_pointer=th->control_stack_start;
175 #endif
176 #endif    
177     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
178     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th); 
179     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
180     bind_variable(INTERRUPT_PENDING, NIL,th);
181     bind_variable(INTERRUPTS_ENABLED,T,th);
182
183     th->interrupt_data =
184         os_validate(0,(sizeof (struct interrupt_data)));
185     if(all_threads) 
186         memcpy(th->interrupt_data,
187                arch_os_get_current_thread()->interrupt_data,
188                sizeof (struct interrupt_data));
189     else 
190         memcpy(th->interrupt_data,global_interrupt_data,
191                sizeof (struct interrupt_data));
192
193     th->unbound_marker=initial_function;
194     return th;
195  cleanup:
196     /* if(th && th->tls_cookie>=0) os_free_tls_pointer(th); */
197     if(spaces) os_invalidate(spaces,
198                              THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
199                              ALIEN_STACK_SIZE+dynamic_values_bytes);
200     return 0;
201 }
202
203 void link_thread(struct thread *th,pid_t kid_pid)
204 {
205     sigset_t newset,oldset;
206     sigemptyset(&newset);
207     sigaddset_blockable(&newset);
208     sigprocmask(SIG_BLOCK, &newset, &oldset); 
209
210     get_spinlock(&all_threads_lock,kid_pid);
211     th->next=all_threads;
212     all_threads=th;
213     /* note that th->pid is 0 at this time.  We rely on all_threads_lock
214      * to ensure that we don't have >1 thread with pid=0 on the list at once
215      */
216     protect_control_stack_guard_page(th->pid,1);
217     release_spinlock(&all_threads_lock);
218
219     sigprocmask(SIG_SETMASK,&oldset,0);
220     th->pid=kid_pid;            /* child will not start until this is set */
221 }
222
223 void create_initial_thread(lispobj initial_function) {
224     struct thread *th=create_thread_struct(initial_function);
225     pid_t kid_pid=getpid();
226     if(th && kid_pid>0) {
227         link_thread(th,kid_pid);
228         initial_thread_trampoline(all_threads); /* no return */
229     } else lose("can't create initial thread");
230 }
231
232 #ifdef LISP_FEATURE_SB_THREAD
233 pid_t create_thread(lispobj initial_function) {
234     struct thread *th;
235     pid_t kid_pid=0;
236
237     if(linux_no_threads_p) return 0;
238     th=create_thread_struct(initial_function);
239     if(th==0) return 0;
240     kid_pid=clone(new_thread_trampoline,
241                   (((void*)th->control_stack_start)+
242                    THREAD_CONTROL_STACK_SIZE-16),
243                   CLONE_FILES|SIG_THREAD_EXIT|CLONE_VM,th);
244     
245     if(kid_pid>0) {
246         link_thread(th,kid_pid);
247         return th->pid;
248     } else {
249         os_invalidate((os_vm_address_t) th->control_stack_start,
250                       ((sizeof (lispobj))
251                        * (th->control_stack_end-th->control_stack_start)) +
252                       BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
253                       32*SIGSTKSZ);
254         return 0;
255     }
256 }
257 #endif
258
259 struct thread *find_thread_by_pid(pid_t pid) 
260 {
261     struct thread *th;
262     for_each_thread(th)
263         if(th->pid==pid) return th;
264     return 0;
265 }
266
267 #if defined LISP_FEATURE_SB_THREAD
268 /* This is not needed unless #+SB-THREAD, as there's a trivial null
269  * unithread definition. */
270
271 void mark_dead_threads() 
272 {
273     pid_t kid;
274     int status;
275     while(1) {
276         kid=waitpid(-1,&status,__WALL|WNOHANG);
277         if(kid<=0) break;
278         if(WIFEXITED(status) || WIFSIGNALED(status)) {
279             struct thread *th=find_thread_by_pid(kid);
280             if(th) th->state=STATE_DEAD;
281         }
282     }
283 }
284
285 void reap_dead_threads() 
286 {
287     struct thread *th,*next,*prev=0;
288     th=all_threads;
289     while(th) {
290         next=th->next;
291         if(th->state==STATE_DEAD) {
292             funcall1(SymbolFunction(HANDLE_THREAD_EXIT),make_fixnum(th->pid));
293 #ifdef LISP_FEATURE_GENCGC
294             gc_alloc_update_page_tables(0, &th->alloc_region);
295 #endif
296             get_spinlock(&all_threads_lock,th->pid);
297             if(prev) prev->next=next;
298             else all_threads=next;
299             release_spinlock(&all_threads_lock);
300             if(th->tls_cookie>=0) arch_os_thread_cleanup(th); 
301             os_invalidate((os_vm_address_t) th->control_stack_start,
302                           ((sizeof (lispobj))
303                            * (th->control_stack_end-th->control_stack_start)) +
304                           BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
305                           32*SIGSTKSZ);
306         } else 
307             prev=th;
308         th=next;
309     }
310 }
311
312 /* These are not needed unless #+SB-THREAD, and since sigwaitinfo()
313  * doesn't seem to be easily available everywhere (OpenBSD...) it's
314  * more trouble than it's worth to compile it when not needed. */
315 void block_sigcont(void)
316 {
317     /* don't allow ourselves to receive SIGCONT while we're in the
318      * "ambiguous" state of being on the queue but not actually stopped.
319      */
320     sigset_t newset;
321     sigemptyset(&newset);
322     sigaddset(&newset,SIG_DEQUEUE);
323     sigprocmask(SIG_BLOCK, &newset, 0); 
324 }
325
326 void unblock_sigcont_and_sleep(void)
327 {
328     sigset_t set;
329     sigemptyset(&set);
330     sigaddset(&set,SIG_DEQUEUE);
331     do {
332         errno=0;
333         sigwaitinfo(&set,0);
334     }while(errno==EINTR);
335     sigprocmask(SIG_UNBLOCK,&set,0);
336 }
337
338 int interrupt_thread(pid_t pid, lispobj function)
339 {
340     union sigval sigval;
341     struct thread *th;
342     sigval.sival_int=function;
343     for_each_thread(th) 
344         if((th->pid==pid) && (th->state != STATE_DEAD))
345             return sigqueue(pid, SIG_INTERRUPT_THREAD, sigval);
346     errno=EPERM; return -1;
347 }
348
349 int signal_thread_to_dequeue (pid_t pid)
350 {
351     return kill (pid, SIG_DEQUEUE);
352 }
353
354
355 /* stopping the world is a two-stage process.  From this thread we signal 
356  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
357  * the usual pseudo-atomic checks (we don't want to stop a thread while 
358  * it's in the middle of allocation) then kills _itself_ with SIGSTOP.
359  */
360
361 void gc_stop_the_world()
362 {
363     /* stop all other threads by sending them SIG_STOP_FOR_GC */
364     struct thread *p,*th=arch_os_get_current_thread();
365     pid_t old_pid;
366     int finished;
367     do {
368         finished=1;
369         for(p=all_threads,old_pid=p->pid; p; p=p->next) {
370             if(p==th) continue;
371             if(p->state==STATE_RUNNING) {
372                 p->state=STATE_STOPPING;
373                 if(kill(p->pid,SIG_STOP_FOR_GC)==-1) {
374                     /* we can't kill the process; assume because it
375                      * died already (and its parent is dead so never
376                      * saw the SIGCHLD) */
377                     p->state=STATE_DEAD;
378                 }
379             }
380             if((p->state!=STATE_STOPPED) &&
381                (p->state!=STATE_DEAD)) {
382                 finished=0;
383             }
384         }
385         if(old_pid!=all_threads->pid) {
386             finished=0;
387         }
388     } while(!finished);
389 }
390
391 void gc_start_the_world()
392 {
393     struct thread *p,*th=arch_os_get_current_thread();
394     /* if a resumed thread creates a new thread before we're done with
395      * this loop, the new thread will get consed on the front of *
396      * all_threads_lock, but it won't have been stopped so won't need
397      * restarting */
398     for(p=all_threads;p;p=p->next) {
399         if((p==th) || (p->state==STATE_DEAD)) continue;
400         p->state=STATE_RUNNING;
401         kill(p->pid,SIG_STOP_FOR_GC);
402     }
403 }
404 #endif