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