0.8.21.1:
[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-4),
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 /* unused */
260 void destroy_thread (struct thread *th)
261 {
262     /* precondition: the unix task has already been killed and exited.
263      * This is called by the parent or some other thread */
264 #ifdef LISP_FEATURE_GENCGC
265     gc_alloc_update_page_tables(0, &th->alloc_region);
266 #endif
267     get_spinlock(&all_threads_lock,th->pid);
268     th->unbound_marker=0;       /* for debugging */
269     if(th==all_threads) 
270         all_threads=th->next;
271     else {
272         struct thread *th1=all_threads;
273         while(th1 && th1->next!=th) th1=th1->next;
274         if(th1) th1->next=th->next;     /* unlink */
275     }
276     release_spinlock(&all_threads_lock);
277     if(th && th->tls_cookie>=0) arch_os_thread_cleanup(th); 
278     os_invalidate((os_vm_address_t) th->control_stack_start,
279                   ((sizeof (lispobj))
280                    * (th->control_stack_end-th->control_stack_start)) +
281                   BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
282                   32*SIGSTKSZ);
283 }
284
285 struct thread *find_thread_by_pid(pid_t pid) 
286 {
287     struct thread *th;
288     for_each_thread(th)
289         if(th->pid==pid) return th;
290     return 0;
291 }
292
293 #if defined LISP_FEATURE_SB_THREAD
294 /* This is not needed unless #+SB-THREAD, as there's a trivial null
295  * unithread definition. */
296
297 void mark_dead_threads() 
298 {
299     pid_t kid;
300     int status;
301     while(1) {
302         kid=waitpid(-1,&status,__WALL|WNOHANG);
303         if(kid<=0) break;
304         if(WIFEXITED(status) || WIFSIGNALED(status)) {
305             struct thread *th=find_thread_by_pid(kid);
306             if(th) th->state=STATE_DEAD;
307         }
308     }
309 }
310
311 void reap_dead_threads() 
312 {
313     struct thread *th,*next,*prev=0;
314     th=all_threads;
315     while(th) {
316         next=th->next;
317         if(th->state==STATE_DEAD) {
318             funcall1(SymbolFunction(HANDLE_THREAD_EXIT),make_fixnum(th->pid));
319 #ifdef LISP_FEATURE_GENCGC
320             gc_alloc_update_page_tables(0, &th->alloc_region);
321 #endif
322             get_spinlock(&all_threads_lock,th->pid);
323             if(prev) prev->next=next;
324             else all_threads=next;
325             release_spinlock(&all_threads_lock);
326             if(th->tls_cookie>=0) arch_os_thread_cleanup(th); 
327             os_invalidate((os_vm_address_t) th->control_stack_start,
328                           ((sizeof (lispobj))
329                            * (th->control_stack_end-th->control_stack_start)) +
330                           BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
331                           32*SIGSTKSZ);
332         } else 
333             prev=th;
334         th=next;
335     }
336 }
337
338 /* These are not needed unless #+SB-THREAD, and since sigwaitinfo()
339  * doesn't seem to be easily available everywhere (OpenBSD...) it's
340  * more trouble than it's worth to compile it when not needed. */
341 void block_sigcont(void)
342 {
343     /* don't allow ourselves to receive SIGCONT while we're in the
344      * "ambiguous" state of being on the queue but not actually stopped.
345      */
346     sigset_t newset;
347     sigemptyset(&newset);
348     sigaddset(&newset,SIG_DEQUEUE);
349     sigprocmask(SIG_BLOCK, &newset, 0); 
350 }
351
352 void unblock_sigcont_and_sleep(void)
353 {
354     sigset_t set;
355     sigemptyset(&set);
356     sigaddset(&set,SIG_DEQUEUE);
357     do {
358         errno=0;
359         sigwaitinfo(&set,0);
360     }while(errno==EINTR);
361     sigprocmask(SIG_UNBLOCK,&set,0);
362 }
363
364 int interrupt_thread(pid_t pid, lispobj function)
365 {
366     union sigval sigval;
367     struct thread *th;
368     sigval.sival_int=function;
369     for_each_thread(th) 
370         if((th->pid==pid) && (th->state != STATE_DEAD))
371             return sigqueue(pid, SIG_INTERRUPT_THREAD, sigval);
372     errno=EPERM; return -1;
373 }
374
375 int signal_thread_to_dequeue (pid_t pid)
376 {
377     return kill (pid, SIG_DEQUEUE);
378 }
379
380
381 /* stopping the world is a two-stage process.  From this thread we signal 
382  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
383  * the usual pseudo-atomic checks (we don't want to stop a thread while 
384  * it's in the middle of allocation) then kills _itself_ with SIGSTOP.
385  */
386
387 void gc_stop_the_world()
388 {
389     /* stop all other threads by sending them SIG_STOP_FOR_GC */
390     struct thread *p,*th=arch_os_get_current_thread();
391     pid_t old_pid;
392     int finished;
393     do {
394         finished=1;
395         for(p=all_threads,old_pid=p->pid; p; p=p->next) {
396             if(p==th) continue;
397             if(p->state==STATE_RUNNING) {
398                 p->state=STATE_STOPPING;
399                 if(kill(p->pid,SIG_STOP_FOR_GC)==-1) {
400                     /* we can't kill the process; assume because it
401                      * died already (and its parent is dead so never
402                      * saw the SIGCHLD) */
403                     p->state=STATE_DEAD;
404                 }
405             }
406             if((p->state!=STATE_STOPPED) &&
407                (p->state!=STATE_DEAD)) {
408                 finished=0;
409             }
410         }
411         if(old_pid!=all_threads->pid) {
412             finished=0;
413         }
414     } while(!finished);
415 }
416
417 void gc_start_the_world()
418 {
419     struct thread *p,*th=arch_os_get_current_thread();
420     /* if a resumed thread creates a new thread before we're done with
421      * this loop, the new thread will get consed on the front of *
422      * all_threads_lock, but it won't have been stopped so won't need
423      * restarting */
424     for(p=all_threads;p;p=p->next) {
425         if((p==th) || (p->state==STATE_DEAD)) continue;
426         p->state=STATE_RUNNING;
427         kill(p->pid,SIG_STOP_FOR_GC);
428     }
429 }
430 #endif