13 #include "validate.h" /* for CONTROL_STACK_SIZE etc */
17 #include "target-arch-os.h"
21 #include "genesis/cons.h"
22 #include "genesis/fdefn.h"
23 #include "interr.h" /* for lose() */
24 #include "gc-internal.h"
26 #define ALIEN_STACK_SIZE (1*1024*1024) /* 1Mb size chosen at random */
28 struct freeable_stack {
29 os_thread_t os_thread;
30 os_vm_address_t stack;
33 static struct freeable_stack * volatile freeable_stack = 0;
35 int dynamic_values_bytes=4096*sizeof(lispobj); /* same for all threads */
36 struct thread * volatile all_threads;
37 extern struct interrupt_data * global_interrupt_data;
38 extern int linux_no_threads_p;
40 #ifdef LISP_FEATURE_SB_THREAD
42 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
44 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
45 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs);
51 link_thread(struct thread *th)
53 if (all_threads) all_threads->prev=th;
59 #ifdef LISP_FEATURE_SB_THREAD
61 unlink_thread(struct thread *th)
64 th->prev->next = th->next;
66 all_threads = th->next;
68 th->next->prev = th->prev;
73 initial_thread_trampoline(struct thread *th)
76 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
79 function = th->no_tls_value_marker;
80 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
81 if(arch_os_thread_init(th)==0) return 1;
83 th->os_thread=thread_self();
84 protect_control_stack_guard_page(1);
86 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
87 return call_into_lisp_first_time(function,args,0);
89 return funcall0(function);
93 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
94 ALIEN_STACK_SIZE + dynamic_values_bytes + \
97 #ifdef LISP_FEATURE_SB_THREAD
100 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
102 struct freeable_stack *new_freeable_stack = 0;
103 if (thread_to_be_cleaned_up) {
104 new_freeable_stack = (struct freeable_stack *)
105 os_validate(0, sizeof(struct freeable_stack));
106 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
107 new_freeable_stack->stack = (os_vm_address_t)
108 thread_to_be_cleaned_up->control_stack_start;
110 new_freeable_stack = (struct freeable_stack *)
111 swap_lispobjs((lispobj *)(void *)&freeable_stack,
112 (lispobj)new_freeable_stack);
113 if (new_freeable_stack) {
114 FSHOW((stderr,"/reaping %lu\n", new_freeable_stack->os_thread));
115 /* Under NPTL pthread_join really waits until the thread
116 * exists and the stack can be safely freed. This is sadly not
117 * mandated by the pthread spec. */
118 gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
119 os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
120 os_invalidate((os_vm_address_t) new_freeable_stack,
121 sizeof(struct freeable_stack));
125 /* this is the first thing that runs in the child (which is why the
126 * silly calling convention). Basically it calls the user's requested
127 * lisp function after doing arch_os_thread_init and whatever other
128 * bookkeeping needs to be done
131 new_thread_trampoline(struct thread *th)
135 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
136 function = th->no_tls_value_marker;
137 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
138 if(arch_os_thread_init(th)==0) {
139 /* FIXME: handle error */
140 lose("arch_os_thread_init failed\n");
143 th->os_thread=thread_self();
144 protect_control_stack_guard_page(1);
145 /* Since GC can only know about this thread from the all_threads
146 * list and we're just adding this thread to it there is no danger
147 * of deadlocking even with SIG_STOP_FOR_GC blocked (which it is
149 pthread_mutex_lock(&all_threads_lock);
151 pthread_mutex_unlock(&all_threads_lock);
153 result = funcall0(function);
154 th->state=STATE_DEAD;
156 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
157 * thread, but since we are already dead it won't wait long. */
158 pthread_mutex_lock(&all_threads_lock);
159 gc_alloc_update_page_tables(0, &th->alloc_region);
161 pthread_mutex_unlock(&all_threads_lock);
163 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
164 os_invalidate((os_vm_address_t)th->interrupt_data,
165 (sizeof (struct interrupt_data)));
166 free_thread_stack_later(th);
167 FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
171 #endif /* LISP_FEATURE_SB_THREAD */
174 free_thread_struct(struct thread *th)
176 if (th->interrupt_data)
177 os_invalidate((os_vm_address_t) th->interrupt_data,
178 (sizeof (struct interrupt_data)));
179 os_invalidate((os_vm_address_t) th->control_stack_start,
183 /* this is called from any other thread to create the new one, and
184 * initialize all parts of it that can be initialized from another
188 static struct thread *
189 create_thread_struct(lispobj initial_function) {
190 union per_thread_data *per_thread;
191 struct thread *th=0; /* subdue gcc */
193 #ifdef LISP_FEATURE_SB_THREAD
197 /* may as well allocate all the spaces at once: it saves us from
198 * having to decide what to do if only some of the allocations
200 spaces=os_validate(0, THREAD_STRUCT_SIZE);
203 per_thread=(union per_thread_data *)
205 THREAD_CONTROL_STACK_SIZE+
209 #ifdef LISP_FEATURE_SB_THREAD
210 for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
211 per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
212 if (all_threads == 0) {
213 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
216 make_fixnum(MAX_INTERRUPTS+
217 sizeof(struct thread)/sizeof(lispobj)),
219 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
221 #define STATIC_TLS_INIT(sym,field) \
222 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
223 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
225 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
226 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
227 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
228 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
229 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
230 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
231 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
232 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
234 #undef STATIC_TLS_INIT
238 th=&per_thread->thread;
239 th->control_stack_start = spaces;
240 th->binding_stack_start=
241 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
242 th->control_stack_end = th->binding_stack_start;
243 th->alien_stack_start=
244 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
245 th->binding_stack_pointer=th->binding_stack_start;
248 th->state=STATE_RUNNING;
249 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
250 th->alien_stack_pointer=((void *)th->alien_stack_start
251 + ALIEN_STACK_SIZE-N_WORD_BYTES);
253 th->alien_stack_pointer=((void *)th->alien_stack_start);
255 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
256 th->pseudo_atomic_interrupted=0;
257 th->pseudo_atomic_atomic=0;
259 #ifdef LISP_FEATURE_GENCGC
260 gc_set_region_empty(&th->alloc_region);
263 #ifndef LISP_FEATURE_SB_THREAD
264 /* the tls-points-into-struct-thread trick is only good for threaded
265 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
266 * appropriate values from struct thread here, and make sure that
267 * we use the appropriate SymbolValue macros to access any of the
268 * variable quantities from the C runtime. It's not quite OAOOM,
269 * it just feels like it */
270 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
271 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
272 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
273 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
274 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
275 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
276 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
277 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
279 current_binding_stack_pointer=th->binding_stack_pointer;
280 current_control_stack_pointer=th->control_stack_start;
283 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
284 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
285 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
286 bind_variable(INTERRUPT_PENDING, NIL,th);
287 bind_variable(INTERRUPTS_ENABLED,T,th);
288 bind_variable(GC_PENDING,NIL,th);
289 #ifdef LISP_FEATURE_SB_THREAD
290 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
293 th->interrupt_data = (struct interrupt_data *)
294 os_validate(0,(sizeof (struct interrupt_data)));
295 if (!th->interrupt_data) {
296 free_thread_struct(th);
299 th->interrupt_data->pending_handler = 0;
300 th->no_tls_value_marker=initial_function;
304 void create_initial_thread(lispobj initial_function) {
305 struct thread *th=create_thread_struct(initial_function);
307 initial_thread_trampoline(th); /* no return */
308 } else lose("can't create initial thread");
311 #ifdef LISP_FEATURE_SB_THREAD
313 #ifndef __USE_XOPEN2K
314 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
318 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
320 /* The new thread inherits the restrictive signal mask set here,
321 * and enables signals again when it is set up properly. */
323 sigset_t newset,oldset;
325 sigemptyset(&newset);
326 /* Blocking deferrable signals is enough, no need to block
327 * SIG_STOP_FOR_GC because the child process is not linked onto
328 * all_threads until it's ready. */
329 sigaddset_deferrable(&newset);
330 thread_sigmask(SIG_BLOCK, &newset, &oldset);
332 if((pthread_attr_init(&attr)) ||
333 (pthread_attr_setstack(&attr,th->control_stack_start,
334 THREAD_CONTROL_STACK_SIZE-16)) ||
336 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
338 thread_sigmask(SIG_SETMASK,&oldset,0);
342 os_thread_t create_thread(lispobj initial_function) {
346 if(linux_no_threads_p) return 0;
348 /* Assuming that a fresh thread struct has no lisp objects in it,
349 * linking it to all_threads can be left to the thread itself
350 * without fear of gc lossage. initial_function violates this
351 * assumption and must stay pinned until the child starts up. */
352 th = create_thread_struct(initial_function);
355 if (create_os_thread(th,&kid_tid)) {
358 free_thread_struct(th);
363 /* Send the signo to os_thread, retry if the rt signal queue is
365 static int kill_thread_safely(os_thread_t os_thread, int signo)
368 /* The man page does not mention EAGAIN as a valid return value
369 * for either pthread_kill or kill. But that's theory, this is
370 * practice. By waiting here we assume that the delivery of this
371 * signal is not necessary for the delivery of the signals in the
372 * queue. In other words, we _assume_ there are no deadlocks. */
373 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
374 /* wait a bit then try again in the hope of the rt signal
375 * queue not being full */
376 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
377 /* FIXME: some kind of backoff (random, exponential) would be
384 int signal_interrupt_thread(os_thread_t os_thread)
386 int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
389 } else if (status == ESRCH) {
392 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
393 os_thread, status, strerror(status));
397 /* stopping the world is a two-stage process. From this thread we signal
398 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
399 * the usual pseudo-atomic checks (we don't want to stop a thread while
400 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
403 /* To avoid deadlocks when gc stops the world all clients of each
404 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
405 * holding the lock, but they must agree on which. */
406 void gc_stop_the_world()
408 struct thread *p,*th=arch_os_get_current_thread();
410 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
412 /* keep threads from starting while the world is stopped. */
413 pthread_mutex_lock(&all_threads_lock); \
414 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
416 /* stop all other threads by sending them SIG_STOP_FOR_GC */
417 for(p=all_threads; p; p=p->next) {
418 gc_assert(p->os_thread != 0);
419 if((p!=th) && ((p->state==STATE_RUNNING))) {
420 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
422 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
424 /* This thread has exited. */
425 gc_assert(p->state==STATE_DEAD);
427 lose("cannot send suspend thread=%lu: %d, %s",
428 p->os_thread,status,strerror(status));
432 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
433 /* wait for the running threads to stop or finish */
434 for(p=all_threads;p;) {
435 if((p!=th) && (p->state==STATE_RUNNING)) {
441 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
444 void gc_start_the_world()
446 struct thread *p,*th=arch_os_get_current_thread();
448 /* if a resumed thread creates a new thread before we're done with
449 * this loop, the new thread will get consed on the front of
450 * all_threads, but it won't have been stopped so won't need
452 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
453 for(p=all_threads;p;p=p->next) {
454 gc_assert(p->os_thread!=0);
455 if((p!=th) && (p->state!=STATE_DEAD)) {
456 if(p->state!=STATE_SUSPENDED) {
457 lose("gc_start_the_world: wrong thread state is %d\n",
458 fixnum_value(p->state));
460 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
462 p->state=STATE_RUNNING;
463 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
465 lose("cannot resume thread=%lu: %d, %s",
466 p->os_thread,status,strerror(status));
470 /* If we waited here until all threads leave STATE_SUSPENDED, then
471 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
472 * performance implications, but does away with the 'rt signal
473 * queue full' problem. */
474 pthread_mutex_unlock(&all_threads_lock); \
475 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));