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