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