40d3afebf7640e7f9e9c600271bb8a2d1a2afc6a
[sbcl.git] / src / runtime / thread.c
1 #include <stdlib.h>
2 #include <stdio.h>
3 #include <sched.h>
4 #include <stddef.h>
5 #ifndef CLONE_PARENT            /* lameass glibc 2.2  doesn't define this */
6 #define CLONE_PARENT 0x00008000 /* even though the manpage documents it */
7 #endif
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 #ifdef LISP_FEATURE_GENCGC
17 #include "gencgc.h"
18 #endif
19 #include "dynbind.h"
20 #include "genesis/cons.h"
21 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
22
23 int dynamic_values_bytes=4096*sizeof(lispobj);  /* same for all threads */
24 struct thread *all_threads;
25 lispobj all_threads_lock;
26 extern struct interrupt_data * global_interrupt_data;
27
28 void get_spinlock(lispobj *word,int value);
29
30 /* this is the first thing that clone() runs in the child (which is
31  * why the silly calling convention).  Basically it calls the user's
32  * requested lisp function after doing arch_os_thread_init and
33  * whatever other bookkeeping needs to be done
34  */
35
36 /* set go to 0 to stop the thread before it starts.  Convenient if you
37 * want to attach a debugger to it before it does anything */
38 volatile int go=1;              
39
40 int
41 new_thread_trampoline(struct thread *th)
42 {
43     lispobj function;
44     function = th->unbound_marker;
45     if(go==0) {
46         fprintf(stderr, "/pausing 0x%lx(%d,%d) before new_thread_trampoline(0x%lx)\n",
47                 (unsigned long)th,th->pid,getpid(),(unsigned long)function);
48         while(go==0) ;
49         fprintf(stderr, "/continue\n");
50     }
51     th->unbound_marker = UNBOUND_MARKER_WIDETAG;
52     /* wait here until our thread is linked into all_threads: see below */
53     while(th->pid<1) sched_yield();
54
55     if(arch_os_thread_init(th)==0) 
56         return 1;               /* failure.  no, really */
57     return funcall0(function);
58 }
59
60 /* this is called from any other thread to create the new one, and
61  * initialize all parts of it that can be initialized from another 
62  * thread 
63  */
64
65 pid_t create_thread(lispobj initial_function) {
66     union per_thread_data *per_thread;
67     struct thread *th=0;        /*  subdue gcc */
68     void *spaces=0;
69     pid_t kid_pid;
70
71     /* may as well allocate all the spaces at once: it saves us from
72      * having to decide what to do if only some of the allocations
73      * succeed */
74     spaces=os_validate(0,
75                        THREAD_CONTROL_STACK_SIZE+
76                        BINDING_STACK_SIZE+
77                        ALIEN_STACK_SIZE+
78                        dynamic_values_bytes+
79                        32*SIGSTKSZ
80                        );
81     if(!spaces) goto cleanup;
82     per_thread=(union per_thread_data *)
83         (spaces+
84          THREAD_CONTROL_STACK_SIZE+
85          BINDING_STACK_SIZE+
86          ALIEN_STACK_SIZE);
87
88     th=&per_thread->thread;
89     if(all_threads) {
90         memcpy(per_thread,arch_os_get_current_thread(),
91                dynamic_values_bytes);
92     } else {
93         int i;
94         for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
95             per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
96         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) 
97             SetSymbolValue
98                 (FREE_TLS_INDEX,
99                  make_fixnum(MAX_INTERRUPTS+
100                              sizeof(struct thread)/sizeof(lispobj)),
101                  0);
102 #define STATIC_TLS_INIT(sym,field) \
103   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
104   make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
105                                   
106         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
107         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
108         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
109         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
110         STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
111         STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
112 #undef STATIC_TLS_INIT
113     }
114
115     th->control_stack_start = spaces;
116     th->binding_stack_start=
117         (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
118     th->alien_stack_start=
119         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
120     th->binding_stack_pointer=th->binding_stack_start;
121     th->this=th;
122     th->pid=0;
123 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
124     th->alien_stack_pointer=((void *)th->alien_stack_start
125                              + ALIEN_STACK_SIZE-4); /* naked 4.  FIXME */
126 #else
127     th->alien_stack_pointer=((void *)th->alien_stack_start);
128 #endif
129     th->pseudo_atomic_interrupted=0;
130     /* runtime.c used to set PSEUDO_ATOMIC_ATOMIC =1 globally.  I'm not
131      * sure why, but it appears to help */
132     th->pseudo_atomic_atomic=make_fixnum(1);
133     gc_set_region_empty(&th->alloc_region);
134     
135     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
136     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th); 
137     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
138     bind_variable(INTERRUPT_PENDING, NIL,th);
139     bind_variable(INTERRUPTS_ENABLED,T,th);
140
141     th->interrupt_data=malloc(sizeof (struct interrupt_data));
142     if(all_threads) 
143         memcpy(th->interrupt_data,arch_os_get_current_thread()->interrupt_data,
144                sizeof (struct interrupt_data));
145     else 
146         memcpy(th->interrupt_data,global_interrupt_data,
147                sizeof (struct interrupt_data));
148
149
150 #if defined(LISP_FEATURE_X86) && defined (LISP_FEATURE_LINUX)
151     th->unbound_marker=initial_function;
152     kid_pid=
153         clone(new_thread_trampoline,
154               (((void*)th->control_stack_start)+THREAD_CONTROL_STACK_SIZE-4),
155               (((getpid()!=parent_pid)?(CLONE_PARENT):0)
156                |CLONE_FILES|SIGALRM|CLONE_VM),th);
157     if(kid_pid<=0) 
158         goto cleanup;
159 #else
160 #error this stuff presently only works on x86 Linux
161 #endif
162
163     get_spinlock(&all_threads_lock,kid_pid);
164     th->next=all_threads;
165     all_threads=th;
166     /* note that th->pid is 0 at this time.  We rely on all_threads_lock
167      * to ensure that we don't have >1 thread with pid=0 on the list at once
168      */
169     protect_control_stack_guard_page(th->pid,1);
170     all_threads_lock=0;
171     th->pid=kid_pid;            /* child will not start until this is set */
172     return th->pid;
173  cleanup:
174     /* if(th && th->tls_cookie>=0) os_free_tls_pointer(th); */
175     if(spaces) os_invalidate(spaces,
176                              THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
177                              ALIEN_STACK_SIZE+dynamic_values_bytes);
178     return 0;
179 }
180
181 void destroy_thread (struct thread *th)
182 {
183     /* precondition: the unix task has already been killed and exited.
184      * This is called by the parent */
185     gc_alloc_update_page_tables(0, &th->alloc_region);
186     get_spinlock(&all_threads_lock,th->pid);
187     if(th==all_threads) 
188         all_threads=th->next;
189     else {
190         struct thread *th1=all_threads;
191         while(th1->next!=th) th1=th1->next;
192         th1->next=th->next;     /* unlink */
193     }
194     all_threads_lock=0;
195     if(th && th->tls_cookie>=0) arch_os_thread_cleanup(th); 
196     os_invalidate((os_vm_address_t) th->control_stack_start,
197                   THREAD_CONTROL_STACK_SIZE+BINDING_STACK_SIZE+
198                   ALIEN_STACK_SIZE+dynamic_values_bytes+
199                   32*SIGSTKSZ);
200 }
201
202
203 struct thread *find_thread_by_pid(pid_t pid) 
204 {
205     struct thread *th;
206     for_each_thread(th)
207         if(th->pid==pid) return th;
208     return 0;
209 }
210
211
212 void get_spinlock(lispobj *word,int value)
213 {
214     u32 eax=0;
215     do {
216         asm ("xor %0,%0;cmpxchg %1,%2" 
217              : "=a" (eax)
218              : "r" (value), "m" (*word)
219              : "memory", "cc");
220     } while(eax!=0);
221 }
222
223 void block_sigcont(void)
224 {
225     /* don't allow ourselves to receive SIGCONT while we're in the
226      * "ambiguous" state of being on the queue but not actually stopped.
227      */
228     sigset_t newset;
229     sigemptyset(&newset);
230     sigaddset(&newset,SIGCONT);
231     sigprocmask(SIG_BLOCK, &newset, 0); 
232 }
233
234 void unblock_sigcont_and_sleep(void)
235 {
236     sigset_t set;
237     sigemptyset(&set);
238     sigaddset(&set,SIGCONT);
239     sigwaitinfo(&set,0);
240     sigprocmask(SIG_UNBLOCK,&set,0);
241 }
242