0.pre8.112:
[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 extern struct interrupt_data * global_interrupt_data;
28
29 void get_spinlock(lispobj *word,int value);
30
31 /* this is the first thing that clone() runs in the child (which is
32  * why the silly calling convention).  Basically it calls the user's
33  * requested lisp function after doing arch_os_thread_init and
34  * whatever other bookkeeping needs to be done
35  */
36
37 /* set go to 0 to stop the thread before it starts.  Convenient if you
38 * want to attach a debugger to it before it does anything */
39 volatile int go=1;              
40
41 int
42 new_thread_trampoline(struct thread *th)
43 {
44     lispobj function;
45     lispobj *args = NULL;
46     function = th->unbound_marker;
47     if(go==0) {
48         fprintf(stderr, "/pausing 0x%lx(%d,%d) before new_thread_trampoline(0x%lx)\n",
49                 (unsigned long)th,th->pid,getpid(),(unsigned long)function);
50         while(go==0) ;
51         fprintf(stderr, "/continue\n");
52     }
53     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
54 #ifdef LISP_FEATURE_SB_THREAD
55     /* wait here until our thread is linked into all_threads: see below */
56     while(th->pid<1) sched_yield();
57 #else
58     if(th->pid < 1)
59         lose("th->pid not set up right");
60 #endif
61
62     if(arch_os_thread_init(th)==0) 
63         return 1;               /* failure.  no, really */
64 #if !defined(LISP_FEATURE_SB_THREAD) && defined(LISP_FEATURE_X86)
65     return call_into_lisp_first_time(function,args,0);
66 #else
67     return funcall0(function);
68 #endif
69 }
70
71 /* this is called from any other thread to create the new one, and
72  * initialize all parts of it that can be initialized from another 
73  * thread 
74  */
75
76 pid_t create_thread(lispobj initial_function) {
77     union per_thread_data *per_thread;
78     struct thread *th=0;        /*  subdue gcc */
79     void *spaces=0;
80     pid_t kid_pid;
81
82     /* may as well allocate all the spaces at once: it saves us from
83      * having to decide what to do if only some of the allocations
84      * succeed */
85     spaces=os_validate(0,
86                        THREAD_CONTROL_STACK_SIZE+
87                        BINDING_STACK_SIZE+
88                        ALIEN_STACK_SIZE+
89                        dynamic_values_bytes+
90                        32*SIGSTKSZ
91                        );
92     if(!spaces) goto cleanup;
93     per_thread=(union per_thread_data *)
94         (spaces+
95          THREAD_CONTROL_STACK_SIZE+
96          BINDING_STACK_SIZE+
97          ALIEN_STACK_SIZE);
98
99     th=&per_thread->thread;
100     if(all_threads) {
101         memcpy(per_thread,arch_os_get_current_thread(),
102                dynamic_values_bytes);
103     } else {
104 #ifdef LISP_FEATURE_SB_THREAD
105         int i;
106         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
107             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
108         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
109             SetSymbolValue
110                 (FREE_TLS_INDEX,
111                  make_fixnum(MAX_INTERRUPTS+
112                              sizeof(struct thread)/sizeof(lispobj)),
113                  0);
114 #define STATIC_TLS_INIT(sym,field) \
115   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
116   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
117                                   
118         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
119         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
120         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
121         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
122         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
123 #ifdef LISP_FEATURE_X86
124         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
125         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
126 #endif
127 #undef STATIC_TLS_INIT
128 #endif
129     }
130
131     th->control_stack_start = spaces;
132     th->binding_stack_start=
133         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
134     th->control_stack_end = th->binding_stack_start;
135     th->alien_stack_start=
136         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
137     th->binding_stack_pointer=th->binding_stack_start;
138     th->this=th;
139     th->pid=0;
140 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
141     th->alien_stack_pointer=((void *)th->alien_stack_start
142                              + ALIEN_STACK_SIZE-4); /* naked 4.  FIXME */
143 #else
144     th->alien_stack_pointer=((void *)th->alien_stack_start);
145 #endif
146 #ifdef LISP_FEATURE_X86
147     th->pseudo_atomic_interrupted=0;
148     /* runtime.c used to set PSEUDO_ATOMIC_ATOMIC =1 globally.  I'm not
149      * sure why, but it appears to help */
150     th->pseudo_atomic_atomic=make_fixnum(1);
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,th->binding_stack_start,th);
164     SetSymbolValue(CONTROL_STACK_START,th->control_stack_start,th);
165     SetSymbolValue(CONTROL_STACK_END,th->control_stack_end,th);
166 #ifdef LISP_FEATURE_X86
167     SetSymbolValue(BINDING_STACK_POINTER,th->binding_stack_pointer,th);
168     SetSymbolValue(ALIEN_STACK,th->alien_stack_pointer,th);
169     SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,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 #ifdef LISP_FEATURE_SB_THREAD
193 #if defined(LISP_FEATURE_X86) && defined (LISP_FEATURE_LINUX)
194     kid_pid=
195         clone(new_thread_trampoline,
196               (((void*)th->control_stack_start)+THREAD_CONTROL_STACK_SIZE-4),
197               (((getpid()!=parent_pid)?(CLONE_PARENT):0)
198                |CLONE_FILES|SIGALRM|CLONE_VM),th);
199     if(kid_pid<=0) 
200         goto cleanup;
201 #else
202 #error this stuff presently only works on x86 Linux
203 #endif
204 #else
205     kid_pid=getpid();
206 #endif
207     get_spinlock(&all_threads_lock,kid_pid);
208     th->next=all_threads;
209     all_threads=th;
210     /* note that th->pid is 0 at this time.  We rely on all_threads_lock
211      * to ensure that we don't have >1 thread with pid=0 on the list at once
212      */
213     protect_control_stack_guard_page(th->pid,1);
214     all_threads_lock=0;
215     th->pid=kid_pid;            /* child will not start until this is set */
216 #ifndef LISP_FEATURE_SB_THREAD
217     new_thread_trampoline(all_threads); /*  call_into_lisp */
218     lose("Clever child?  Idiot savant, verging on the.");
219 #endif
220
221     return th->pid;
222  cleanup:
223     /* if(th && th->tls_cookie>=0) os_free_tls_pointer(th); */
224     if(spaces) os_invalidate(spaces,
225                              THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
226                              ALIEN_STACK_SIZE+dynamic_values_bytes);
227     return 0;
228 }
229
230 void destroy_thread (struct thread *th)
231 {
232     /* precondition: the unix task has already been killed and exited.
233      * This is called by the parent */
234 #ifdef LISP_FEATURE_GENCGC
235     gc_alloc_update_page_tables(0, &th->alloc_region);
236 #endif
237     get_spinlock(&all_threads_lock,th->pid);
238     if(th==all_threads) 
239         all_threads=th->next;
240     else {
241         struct thread *th1=all_threads;
242         while(th1->next!=th) th1=th1->next;
243         th1->next=th->next;     /* unlink */
244     }
245     all_threads_lock=0;
246     if(th && th->tls_cookie>=0) arch_os_thread_cleanup(th); 
247     os_invalidate((os_vm_address_t) th->control_stack_start,
248                   ((sizeof (lispobj))
249                    * (th->control_stack_end-th->control_stack_start)) +
250                   BINDING_STACK_SIZE+ALIEN_STACK_SIZE+dynamic_values_bytes+
251                   32*SIGSTKSZ);
252 }
253
254
255 struct thread *find_thread_by_pid(pid_t pid) 
256 {
257     struct thread *th;
258     for_each_thread(th)
259         if(th->pid==pid) return th;
260     return 0;
261 }
262
263 void block_sigcont(void)
264 {
265     /* don't allow ourselves to receive SIGCONT while we're in the
266      * "ambiguous" state of being on the queue but not actually stopped.
267      */
268     sigset_t newset;
269     sigemptyset(&newset);
270     sigaddset(&newset,SIGCONT);
271     sigprocmask(SIG_BLOCK, &newset, 0); 
272 }
273
274 /* This is not needed unless #+SB-THREAD, and since sigwaitinfo()
275  * doesn't seem to be easily available everywhere (OpenBSD...) it's
276  * more trouble than it's worth to compile it when not needed. */
277 #if defined LISP_FEATURE_SB_THREAD
278 void unblock_sigcont_and_sleep(void)
279 {
280     sigset_t set;
281     sigemptyset(&set);
282     sigaddset(&set,SIGCONT);
283     sigwaitinfo(&set,0);
284     sigprocmask(SIG_UNBLOCK,&set,0);
285 }
286 #endif