0.8.3.1
[sbcl.git] / src / runtime / thread.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sched.h>
4 #include <signal.h>
5 #include <stddef.h>
6 #ifndef CLONE_PARENT            /* lameass glibc 2.2  doesn't define this */
7 #define CLONE_PARENT 0x00008000 /* even though the manpage documents it */
8 #endif
9 #include "runtime.h"
10 #include "sbcl.h"
11 #include "validate.h"           /* for CONTROL_STACK_SIZE etc */
12 #include "thread.h"
13 #include "arch.h"
14 #include "target-arch-os.h"
15 #include "os.h"
16 #include "globals.h"
17 #ifdef LISP_FEATURE_GENCGC
18 #include "gencgc.h"
19 #endif
20 #include "dynbind.h"
21 #include "genesis/cons.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 lispobj all_threads_lock;
27 int countdown_to_gc;
28 extern struct interrupt_data * global_interrupt_data;
29
30 void get_spinlock(lispobj *word,int value);
31
32 /* this is the first thing that clone() runs in the child (which is
33  * why the silly calling convention).  Basically it calls the user's
34  * requested lisp function after doing arch_os_thread_init and
35  * whatever other bookkeeping needs to be done
36  */
37
38 /* set go to 0 to stop the thread before it starts.  Convenient if you
39 * want to attach a debugger to it before it does anything */
40 volatile int go=1;              
41
42 int
43 new_thread_trampoline(struct thread *th)
44 {
45     lispobj function;
46     lispobj *args = NULL;
47     function = th->unbound_marker;
48     if(go==0) {
49         fprintf(stderr, "/pausing 0x%lx(%d,%d) before new_thread_trampoline(0x%lx)\n",
50                 (unsigned long)th,th->pid,getpid(),(unsigned long)function);
51         while(go==0) ;
52         fprintf(stderr, "/continue\n");
53     }
54     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
55 #ifdef LISP_FEATURE_SB_THREAD
56     /* wait here until our thread is linked into all_threads: see below */
57     while(th->pid<1) sched_yield();
58 #else
59     if(th->pid < 1)
60         lose("th->pid not set up right");
61 #endif
62
63     if(arch_os_thread_init(th)==0) 
64         return 1;               /* failure.  no, really */
65 #if !defined(LISP_FEATURE_SB_THREAD) && defined(LISP_FEATURE_X86)
66     return call_into_lisp_first_time(function,args,0);
67 #else
68     return funcall0(function);
69 #endif
70 }
71
72 /* this is called from any other thread to create the new one, and
73  * initialize all parts of it that can be initialized from another 
74  * thread 
75  */
76
77 pid_t create_thread(lispobj initial_function) {
78     union per_thread_data *per_thread;
79     struct thread *th=0;        /*  subdue gcc */
80     void *spaces=0;
81     pid_t kid_pid;
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 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
142     th->alien_stack_pointer=((void *)th->alien_stack_start
143                              + ALIEN_STACK_SIZE-4); /* naked 4.  FIXME */
144 #else
145     th->alien_stack_pointer=((void *)th->alien_stack_start);
146 #endif
147 #ifdef LISP_FEATURE_X86
148     th->pseudo_atomic_interrupted=0;
149     /* runtime.c used to set PSEUDO_ATOMIC_ATOMIC =1 globally.  I'm not
150      * sure why, but it appears to help */
151     th->pseudo_atomic_atomic=make_fixnum(1);
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,th->binding_stack_start,th);
165     SetSymbolValue(CONTROL_STACK_START,th->control_stack_start,th);
166     SetSymbolValue(CONTROL_STACK_END,th->control_stack_end,th);
167 #ifdef LISP_FEATURE_X86
168     SetSymbolValue(BINDING_STACK_POINTER,th->binding_stack_pointer,th);
169     SetSymbolValue(ALIEN_STACK,th->alien_stack_pointer,th);
170     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,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=os_validate(0,(sizeof (struct interrupt_data)));
184     if(all_threads) 
185         memcpy(th->interrupt_data,
186                arch_os_get_current_thread()->interrupt_data,
187                sizeof (struct interrupt_data));
188     else 
189         memcpy(th->interrupt_data,global_interrupt_data,
190                sizeof (struct interrupt_data));
191
192     th->unbound_marker=initial_function;
193 #ifdef LISP_FEATURE_SB_THREAD
194 #if defined(LISP_FEATURE_X86) && defined (LISP_FEATURE_LINUX)
195     kid_pid=
196         clone(new_thread_trampoline,
197               (((void*)th->control_stack_start)+THREAD_CONTROL_STACK_SIZE-4),
198               (((getpid()!=parent_pid)?(CLONE_PARENT):0)
199                |CLONE_FILES|SIGALRM|CLONE_VM),th);
200     if(kid_pid<=0) 
201         goto cleanup;
202 #else
203 #error this stuff presently only works on x86 Linux
204 #endif
205 #else
206     kid_pid=getpid();
207 #endif
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     th->pid=kid_pid;            /* child will not start until this is set */
217 #ifndef LISP_FEATURE_SB_THREAD
218     new_thread_trampoline(all_threads); /*  call_into_lisp */
219     lose("Clever child?  Idiot savant, verging on the.");
220 #endif
221
222     return th->pid;
223  cleanup:
224     /* if(th && th->tls_cookie>=0) os_free_tls_pointer(th); */
225     if(spaces) os_invalidate(spaces,
226                              THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
227                              ALIEN_STACK_SIZE+dynamic_values_bytes);
228     return 0;
229 }
230
231 void destroy_thread (struct thread *th)
232 {
233     /* precondition: the unix task has already been killed and exited.
234      * This is called by the parent */
235 #ifdef LISP_FEATURE_GENCGC
236     gc_alloc_update_page_tables(0, &th->alloc_region);
237 #endif
238     get_spinlock(&all_threads_lock,th->pid);
239     if(countdown_to_gc>0) countdown_to_gc--;
240     if(th==all_threads) 
241         all_threads=th->next;
242     else {
243         struct thread *th1=all_threads;
244         while(th1->next!=th) th1=th1->next;
245         th1->next=th->next;     /* unlink */
246     }
247     release_spinlock(&all_threads_lock);
248     if(th && th->tls_cookie>=0) arch_os_thread_cleanup(th); 
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 }
255
256
257 struct thread *find_thread_by_pid(pid_t pid) 
258 {
259     struct thread *th;
260     for_each_thread(th)
261         if(th->pid==pid) return th;
262     return 0;
263 }
264
265 void block_sigcont(void)
266 {
267     /* don't allow ourselves to receive SIGCONT while we're in the
268      * "ambiguous" state of being on the queue but not actually stopped.
269      */
270     sigset_t newset;
271     sigemptyset(&newset);
272     sigaddset(&newset,SIGCONT);
273     sigprocmask(SIG_BLOCK, &newset, 0); 
274 }
275
276 /* This is not needed unless #+SB-THREAD, and since sigwaitinfo()
277  * doesn't seem to be easily available everywhere (OpenBSD...) it's
278  * more trouble than it's worth to compile it when not needed. */
279 #if defined LISP_FEATURE_SB_THREAD
280 void unblock_sigcont_and_sleep(void)
281 {
282     sigset_t set;
283     sigemptyset(&set);
284     sigaddset(&set,SIGCONT);
285     sigwaitinfo(&set,0);
286     sigprocmask(SIG_UNBLOCK,&set,0);
287 }
288
289 int interrupt_thread(pid_t pid, lispobj function)
290 {
291     union sigval sigval;
292     sigval.sival_int=function;
293
294     return sigqueue(pid, SIG_INTERRUPT_THREAD, sigval);
295 }
296
297 void gc_stop_the_world()
298 {
299     /* stop all other threads by sending them SIG_STOP_FOR_GC */
300     struct thread *p,*th=arch_os_get_current_thread();
301     struct thread *tail=0;
302     int finished=0;
303     do {
304         get_spinlock(&all_threads_lock,th->pid);
305         if(tail!=all_threads) {
306             /* new threads always get consed onto the front of all_threads,
307              * and may be created by any thread that we haven't signalled
308              * yet or hasn't received our signal and stopped yet.  So, check
309              * for them on each time around */
310             for(p=all_threads;p!=tail;p=p->next) {
311                 if(p==th) continue;
312                 countdown_to_gc++;
313                 kill(p->pid,SIG_STOP_FOR_GC);
314             }
315             tail=all_threads;
316         } else {
317             finished=(countdown_to_gc==0);
318         }
319         release_spinlock(&all_threads_lock);
320         sched_yield();
321     } while(!finished);
322 }
323
324 void gc_start_the_world()
325 {
326     struct thread *p,*th=arch_os_get_current_thread();
327     get_spinlock(&all_threads_lock,th->pid);
328     for(p=all_threads;p;p=p->next) {
329         if(p==th) continue;
330         kill(p->pid,SIGCONT);
331     }
332     release_spinlock(&all_threads_lock);
333 }
334 #endif