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