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 */
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 make_fixnum(MAX_INTERRUPTS+
215 sizeof(struct thread)/sizeof(lispobj)),
217 SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
219 #define STATIC_TLS_INIT(sym,field) \
220 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
221 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
223 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
224 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
225 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
226 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
227 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
228 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
229 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
230 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
232 #undef STATIC_TLS_INIT
236 th=&per_thread->thread;
237 th->control_stack_start = spaces;
238 th->binding_stack_start=
239 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
240 th->control_stack_end = th->binding_stack_start;
241 th->alien_stack_start=
242 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
243 th->binding_stack_pointer=th->binding_stack_start;
246 th->state=STATE_RUNNING;
247 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
248 th->alien_stack_pointer=((void *)th->alien_stack_start
249 + ALIEN_STACK_SIZE-N_WORD_BYTES);
251 th->alien_stack_pointer=((void *)th->alien_stack_start);
253 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
254 th->pseudo_atomic_interrupted=0;
255 th->pseudo_atomic_atomic=0;
257 #ifdef LISP_FEATURE_GENCGC
258 gc_set_region_empty(&th->alloc_region);
261 #ifndef LISP_FEATURE_SB_THREAD
262 /* the tls-points-into-struct-thread trick is only good for threaded
263 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
264 * appropriate values from struct thread here, and make sure that
265 * we use the appropriate SymbolValue macros to access any of the
266 * variable quantities from the C runtime. It's not quite OAOOM,
267 * it just feels like it */
268 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
269 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
270 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
271 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
272 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
273 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
274 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
275 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
277 current_binding_stack_pointer=th->binding_stack_pointer;
278 current_control_stack_pointer=th->control_stack_start;
281 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
282 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
283 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
284 bind_variable(INTERRUPT_PENDING, NIL,th);
285 bind_variable(INTERRUPTS_ENABLED,T,th);
286 bind_variable(GC_PENDING,NIL,th);
287 #ifdef LISP_FEATURE_SB_THREAD
288 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
291 th->interrupt_data = (struct interrupt_data *)
292 os_validate(0,(sizeof (struct interrupt_data)));
293 if (!th->interrupt_data) {
294 free_thread_struct(th);
297 th->interrupt_data->pending_handler = 0;
298 th->no_tls_value_marker=initial_function;
302 void create_initial_thread(lispobj initial_function) {
303 struct thread *th=create_thread_struct(initial_function);
305 initial_thread_trampoline(th); /* no return */
306 } else lose("can't create initial thread");
309 #ifdef LISP_FEATURE_SB_THREAD
311 #ifndef __USE_XOPEN2K
312 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
316 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
318 /* The new thread inherits the restrictive signal mask set here,
319 * and enables signals again when it is set up properly. */
321 sigset_t newset,oldset;
323 sigemptyset(&newset);
324 /* Blocking deferrable signals is enough, no need to block
325 * SIG_STOP_FOR_GC because the child process is not linked onto
326 * all_threads until it's ready. */
327 sigaddset_deferrable(&newset);
328 thread_sigmask(SIG_BLOCK, &newset, &oldset);
330 if((pthread_attr_init(&attr)) ||
331 (pthread_attr_setstack(&attr,th->control_stack_start,
332 THREAD_CONTROL_STACK_SIZE-16)) ||
334 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
336 thread_sigmask(SIG_SETMASK,&oldset,0);
340 os_thread_t create_thread(lispobj initial_function) {
344 if(linux_no_threads_p) return 0;
346 /* Assuming that a fresh thread struct has no lisp objects in it,
347 * linking it to all_threads can be left to the thread itself
348 * without fear of gc lossage. initial_function violates this
349 * assumption and must stay pinned until the child starts up. */
350 th = create_thread_struct(initial_function);
353 if (create_os_thread(th,&kid_tid)) {
356 free_thread_struct(th);
361 /* Send the signo to os_thread, retry if the rt signal queue is
363 static int kill_thread_safely(os_thread_t os_thread, int signo)
366 /* The man page does not mention EAGAIN as a valid return value
367 * for either pthread_kill or kill. But that's theory, this is
368 * practice. By waiting here we assume that the delivery of this
369 * signal is not necessary for the delivery of the signals in the
370 * queue. In other words, we _assume_ there are no deadlocks. */
371 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
372 /* wait a bit then try again in the hope of the rt signal
373 * queue not being full */
374 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
375 /* FIXME: some kind of backoff (random, exponential) would be
382 int signal_interrupt_thread(os_thread_t os_thread)
384 int status = kill_thread_safely(os_thread, SIG_INTERRUPT_THREAD);
387 } else if (status == ESRCH) {
390 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
391 os_thread, status, strerror(status));
395 /* stopping the world is a two-stage process. From this thread we signal
396 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
397 * the usual pseudo-atomic checks (we don't want to stop a thread while
398 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
401 /* To avoid deadlocks when gc stops the world all clients of each
402 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
403 * holding the lock, but they must agree on which. */
404 void gc_stop_the_world()
406 struct thread *p,*th=arch_os_get_current_thread();
408 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
410 /* keep threads from starting while the world is stopped. */
411 pthread_mutex_lock(&all_threads_lock); \
412 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
414 /* stop all other threads by sending them SIG_STOP_FOR_GC */
415 for(p=all_threads; p; p=p->next) {
416 gc_assert(p->os_thread != 0);
417 if((p!=th) && ((p->state==STATE_RUNNING))) {
418 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
420 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
422 /* This thread has exited. */
423 gc_assert(p->state==STATE_DEAD);
425 lose("cannot send suspend thread=%lu: %d, %s",
426 p->os_thread,status,strerror(status));
430 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
431 /* wait for the running threads to stop or finish */
432 for(p=all_threads;p;) {
433 if((p!=th) && (p->state==STATE_RUNNING)) {
439 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
442 void gc_start_the_world()
444 struct thread *p,*th=arch_os_get_current_thread();
446 /* if a resumed thread creates a new thread before we're done with
447 * this loop, the new thread will get consed on the front of
448 * all_threads, but it won't have been stopped so won't need
450 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
451 for(p=all_threads;p;p=p->next) {
452 gc_assert(p->os_thread!=0);
453 if((p!=th) && (p->state!=STATE_DEAD)) {
454 if(p->state!=STATE_SUSPENDED) {
455 lose("gc_start_the_world: wrong thread state is %d\n",
456 fixnum_value(p->state));
458 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
460 p->state=STATE_RUNNING;
461 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
463 lose("cannot resume thread=%lu: %d, %s",
464 p->os_thread,status,strerror(status));
468 /* If we waited here until all threads leave STATE_SUSPENDED, then
469 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
470 * performance implications, but does away with the 'rt signal
471 * queue full' problem. */
472 pthread_mutex_unlock(&all_threads_lock); \
473 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));