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
41 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);
49 link_thread(struct thread *th)
51 if (all_threads) all_threads->prev=th;
57 #ifdef LISP_FEATURE_SB_THREAD
59 unlink_thread(struct thread *th)
62 th->prev->next = th->next;
64 all_threads = th->next;
66 th->next->prev = th->prev;
71 initial_thread_trampoline(struct thread *th)
74 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
77 function = th->no_tls_value_marker;
78 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
79 if(arch_os_thread_init(th)==0) return 1;
81 th->os_thread=thread_self();
82 protect_control_stack_guard_page(1);
84 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
85 return call_into_lisp_first_time(function,args,0);
87 return funcall0(function);
91 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
92 ALIEN_STACK_SIZE + dynamic_values_bytes + \
95 #ifdef LISP_FEATURE_SB_THREAD
98 free_thread_stack_later(struct thread *thread_to_be_cleaned_up)
100 struct freeable_stack *new_freeable_stack = 0;
101 if (thread_to_be_cleaned_up) {
102 new_freeable_stack = (struct freeable_stack *)
103 os_validate(0, sizeof(struct freeable_stack));
104 new_freeable_stack->os_thread = thread_to_be_cleaned_up->os_thread;
105 new_freeable_stack->stack = (os_vm_address_t)
106 thread_to_be_cleaned_up->control_stack_start;
108 new_freeable_stack = (struct freeable_stack *)
109 swap_lispobjs((lispobj *)(void *)&freeable_stack,
110 (lispobj)new_freeable_stack);
111 if (new_freeable_stack) {
112 FSHOW((stderr,"/reaping %lu\n", new_freeable_stack->os_thread));
113 /* Under NPTL pthread_join really waits until the thread
114 * exists and the stack can be safely freed. This is sadly not
115 * mandated by the pthread spec. */
116 gc_assert(pthread_join(new_freeable_stack->os_thread, NULL) == 0);
117 os_invalidate(new_freeable_stack->stack, THREAD_STRUCT_SIZE);
118 os_invalidate((os_vm_address_t) new_freeable_stack,
119 sizeof(struct freeable_stack));
123 /* this is the first thing that runs in the child (which is why the
124 * silly calling convention). Basically it calls the user's requested
125 * lisp function after doing arch_os_thread_init and whatever other
126 * bookkeeping needs to be done
129 new_thread_trampoline(struct thread *th)
133 FSHOW((stderr,"/creating thread %lu\n", thread_self()));
134 function = th->no_tls_value_marker;
135 th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
136 if(arch_os_thread_init(th)==0) {
137 /* FIXME: handle error */
138 lose("arch_os_thread_init failed\n");
141 th->os_thread=thread_self();
142 protect_control_stack_guard_page(1);
143 /* Since GC can only know about this thread from the all_threads
144 * list and we're just adding this thread to it there is no danger
145 * of deadlocking even with SIG_STOP_FOR_GC blocked (which it is
147 pthread_mutex_lock(&all_threads_lock);
149 pthread_mutex_unlock(&all_threads_lock);
151 result = funcall0(function);
152 th->state=STATE_DEAD;
154 /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
155 * thread, but since we are already dead it won't wait long. */
156 pthread_mutex_lock(&all_threads_lock);
157 gc_alloc_update_page_tables(0, &th->alloc_region);
159 pthread_mutex_unlock(&all_threads_lock);
161 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
162 os_invalidate((os_vm_address_t)th->interrupt_data,
163 (sizeof (struct interrupt_data)));
164 free_thread_stack_later(th);
165 FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
169 #endif /* LISP_FEATURE_SB_THREAD */
172 free_thread_struct(struct thread *th)
174 if (th->interrupt_data)
175 os_invalidate((os_vm_address_t) th->interrupt_data,
176 (sizeof (struct interrupt_data)));
177 os_invalidate((os_vm_address_t) th->control_stack_start,
181 /* this is called from any other thread to create the new one, and
182 * initialize all parts of it that can be initialized from another
186 static struct thread *
187 create_thread_struct(lispobj initial_function) {
188 union per_thread_data *per_thread;
189 struct thread *th=0; /* subdue gcc */
191 #ifdef LISP_FEATURE_SB_THREAD
195 /* may as well allocate all the spaces at once: it saves us from
196 * having to decide what to do if only some of the allocations
198 spaces=os_validate(0, THREAD_STRUCT_SIZE);
201 per_thread=(union per_thread_data *)
203 THREAD_CONTROL_STACK_SIZE+
207 #ifdef LISP_FEATURE_SB_THREAD
208 for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
209 per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
210 if (all_threads == 0) {
211 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
214 /* FIXME: should be MAX_INTERRUPTS -1 ? */
215 make_fixnum(MAX_INTERRUPTS+
216 sizeof(struct thread)/sizeof(lispobj)),
218 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
220 #define STATIC_TLS_INIT(sym,field) \
221 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
222 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
224 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
225 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
226 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
227 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
228 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
229 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
230 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
231 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
233 #undef STATIC_TLS_INIT
237 th=&per_thread->thread;
238 th->control_stack_start = spaces;
239 th->binding_stack_start=
240 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
241 th->control_stack_end = th->binding_stack_start;
242 th->alien_stack_start=
243 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
244 th->binding_stack_pointer=th->binding_stack_start;
247 th->state=STATE_RUNNING;
248 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
249 th->alien_stack_pointer=((void *)th->alien_stack_start
250 + ALIEN_STACK_SIZE-N_WORD_BYTES);
252 th->alien_stack_pointer=((void *)th->alien_stack_start);
254 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
255 th->pseudo_atomic_interrupted=0;
256 th->pseudo_atomic_atomic=0;
258 #ifdef LISP_FEATURE_GENCGC
259 gc_set_region_empty(&th->alloc_region);
262 #ifndef LISP_FEATURE_SB_THREAD
263 /* the tls-points-into-struct-thread trick is only good for threaded
264 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
265 * appropriate values from struct thread here, and make sure that
266 * we use the appropriate SymbolValue macros to access any of the
267 * variable quantities from the C runtime. It's not quite OAOOM,
268 * it just feels like it */
269 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
270 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
271 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
272 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
273 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
274 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
275 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
276 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
278 current_binding_stack_pointer=th->binding_stack_pointer;
279 current_control_stack_pointer=th->control_stack_start;
282 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
283 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
284 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
285 bind_variable(INTERRUPT_PENDING, NIL,th);
286 bind_variable(INTERRUPTS_ENABLED,T,th);
287 bind_variable(GC_PENDING,NIL,th);
288 #ifdef LISP_FEATURE_SB_THREAD
289 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
292 th->interrupt_data = (struct interrupt_data *)
293 os_validate(0,(sizeof (struct interrupt_data)));
294 if (!th->interrupt_data) {
295 free_thread_struct(th);
298 th->interrupt_data->pending_handler = 0;
299 th->no_tls_value_marker=initial_function;
303 void create_initial_thread(lispobj initial_function) {
304 struct thread *th=create_thread_struct(initial_function);
306 initial_thread_trampoline(th); /* no return */
307 } else lose("can't create initial thread");
310 #ifdef LISP_FEATURE_SB_THREAD
312 #ifndef __USE_XOPEN2K
313 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
317 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
319 /* The new thread inherits the restrictive signal mask set here,
320 * and enables signals again when it is set up properly. */
322 sigset_t newset,oldset;
324 sigemptyset(&newset);
325 /* Blocking deferrable signals is enough, no need to block
326 * SIG_STOP_FOR_GC because the child process is not linked onto
327 * all_threads until it's ready. */
328 sigaddset_deferrable(&newset);
329 thread_sigmask(SIG_BLOCK, &newset, &oldset);
331 if((pthread_attr_init(&attr)) ||
332 (pthread_attr_setstack(&attr,th->control_stack_start,
333 THREAD_CONTROL_STACK_SIZE-16)) ||
335 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
337 thread_sigmask(SIG_SETMASK,&oldset,0);
341 os_thread_t create_thread(lispobj initial_function) {
345 if(linux_no_threads_p) return 0;
347 /* Assuming that a fresh thread struct has no lisp objects in it,
348 * linking it to all_threads can be left to the thread itself
349 * without fear of gc lossage. initial_function violates this
350 * assumption and must stay pinned until the child starts up. */
351 th = create_thread_struct(initial_function);
354 if (create_os_thread(th,&kid_tid)) {
357 free_thread_struct(th);
362 /* Send the signo to os_thread, retry if the rt signal queue is
364 static int kill_thread_safely(os_thread_t os_thread, int signo)
367 /* The man page does not mention EAGAIN as a valid return value
368 * for either pthread_kill or kill. But that's theory, this is
369 * practice. By waiting here we assume that the delivery of this
370 * signal is not necessary for the delivery of the signals in the
371 * queue. In other words, we _assume_ there are no deadlocks. */
372 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
373 /* wait a bit then try again in the hope of the rt signal
374 * queue not being full */
375 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
376 /* FIXME: some kind of backoff (random, exponential) would be
383 int signal_interrupt_thread(os_thread_t os_thread)
385 int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
388 } else if (status == ESRCH) {
391 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
392 os_thread, status, strerror(status));
396 /* stopping the world is a two-stage process. From this thread we signal
397 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
398 * the usual pseudo-atomic checks (we don't want to stop a thread while
399 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
402 /* To avoid deadlocks when gc stops the world all clients of each
403 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
404 * holding the lock, but they must agree on which. */
405 void gc_stop_the_world()
407 struct thread *p,*th=arch_os_get_current_thread();
409 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
411 /* keep threads from starting while the world is stopped. */
412 pthread_mutex_lock(&all_threads_lock); \
413 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
415 /* stop all other threads by sending them SIG_STOP_FOR_GC */
416 for(p=all_threads; p; p=p->next) {
417 gc_assert(p->os_thread != 0);
418 if((p!=th) && ((p->state==STATE_RUNNING))) {
419 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
421 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
423 /* This thread has exited. */
424 gc_assert(p->state==STATE_DEAD);
426 lose("cannot send suspend thread=%lu: %d, %s",
427 p->os_thread,status,strerror(status));
431 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
432 /* wait for the running threads to stop or finish */
433 for(p=all_threads;p;) {
434 if((p!=th) && (p->state==STATE_RUNNING)) {
440 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
443 void gc_start_the_world()
445 struct thread *p,*th=arch_os_get_current_thread();
447 /* if a resumed thread creates a new thread before we're done with
448 * this loop, the new thread will get consed on the front of
449 * all_threads, but it won't have been stopped so won't need
451 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
452 for(p=all_threads;p;p=p->next) {
453 gc_assert(p->os_thread!=0);
454 if((p!=th) && (p->state!=STATE_DEAD)) {
455 if(p->state!=STATE_SUSPENDED) {
456 lose("gc_start_the_world: wrong thread state is %d\n",
457 fixnum_value(p->state));
459 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
461 p->state=STATE_RUNNING;
462 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
464 lose("cannot resume thread=%lu: %d, %s",
465 p->os_thread,status,strerror(status));
469 /* If we waited here until all threads leave STATE_SUSPENDED, then
470 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
471 * performance implications, but does away with the 'rt signal
472 * queue full' problem. */
473 pthread_mutex_unlock(&all_threads_lock); \
474 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));