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 int dynamic_values_bytes=4096*sizeof(lispobj); /* same for all threads */
29 struct thread * volatile all_threads;
30 extern struct interrupt_data * global_interrupt_data;
31 extern int linux_no_threads_p;
33 #ifdef LISP_FEATURE_SB_THREAD
35 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
37 /* When trying to get all_threads_lock one should make sure that
38 * sig_stop_for_gc is not blocked. Else there would be a possible
39 * deadlock: gc locks it, other thread blocks signals, gc sends stop
40 * request to other thread and waits, other thread blocks on lock. */
41 void check_sig_stop_for_gc_can_arrive_or_lose()
43 /* Get the current sigmask, by blocking the empty set. */
44 sigset_t empty,current;
46 thread_sigmask(SIG_BLOCK, &empty, ¤t);
47 if (sigismember(¤t,SIG_STOP_FOR_GC))
48 lose("SIG_STOP_FOR_GC cannot arrive: it is blocked\n");
49 if (SymbolValue(GC_INHIBIT,arch_os_get_current_thread()) != NIL)
50 lose("SIG_STOP_FOR_GC cannot arrive: gc is inhibited\n");
51 if (arch_pseudo_atomic_atomic(NULL))
52 lose("SIG_STOP_FOR_GC cannot arrive: in pseudo atomic\n");
55 #define GET_ALL_THREADS_LOCK(name) \
57 sigset_t _newset,_oldset; \
58 sigemptyset(&_newset); \
59 sigaddset_deferrable(&_newset); \
60 thread_sigmask(SIG_BLOCK, &_newset, &_oldset); \
61 check_sig_stop_for_gc_can_arrive_or_lose(); \
62 FSHOW_SIGNAL((stderr,"/%s:waiting on lock=%ld, thread=%lu\n",name, \
63 all_threads_lock,arch_os_get_current_thread()->os_thread)); \
64 pthread_mutex_lock(&all_threads_lock); \
65 FSHOW_SIGNAL((stderr,"/%s:got lock, thread=%lu\n", \
66 name,arch_os_get_current_thread()->os_thread));
68 #define RELEASE_ALL_THREADS_LOCK(name) \
69 FSHOW_SIGNAL((stderr,"/%s:released lock\n",name)); \
70 pthread_mutex_unlock(&all_threads_lock); \
71 thread_sigmask(SIG_SETMASK,&_oldset,0); \
76 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
77 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs);
81 initial_thread_trampoline(struct thread *th)
84 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
87 function = th->unbound_marker;
88 th->unbound_marker = UNBOUND_MARKER_WIDETAG;
89 if(arch_os_thread_init(th)==0) return 1;
91 if(th->os_thread < 1) lose("th->os_thread not set up right");
92 th->state=STATE_RUNNING;
93 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
94 return call_into_lisp_first_time(function,args,0);
96 return funcall0(function);
100 #ifdef LISP_FEATURE_SB_THREAD
102 /* this is the first thing that runs in the child (which is why the
103 * silly calling convention). Basically it calls the user's requested
104 * lisp function after doing arch_os_thread_init and whatever other
105 * bookkeeping needs to be done
108 new_thread_trampoline(struct thread *th)
112 function = th->unbound_marker;
113 th->unbound_marker = UNBOUND_MARKER_WIDETAG;
114 if(arch_os_thread_init(th)==0) {
115 /* FIXME: handle error */
116 lose("arch_os_thread_init failed\n");
119 /* wait here until our thread is linked into all_threads: see below */
121 volatile os_thread_t *tid=&th->os_thread;
122 while(*tid<1) sched_yield();
125 th->state=STATE_RUNNING;
126 result = funcall0(function);
127 th->state=STATE_DEAD;
130 #endif /* LISP_FEATURE_SB_THREAD */
132 #define THREAD_STRUCT_SIZE (THREAD_CONTROL_STACK_SIZE + BINDING_STACK_SIZE + \
133 ALIEN_STACK_SIZE + dynamic_values_bytes + \
137 free_thread_struct(struct thread *th)
139 if (th->interrupt_data)
140 os_invalidate((os_vm_address_t) th->interrupt_data,
141 (sizeof (struct interrupt_data)));
142 os_invalidate((os_vm_address_t) th->control_stack_start,
146 /* this is called from any other thread to create the new one, and
147 * initialize all parts of it that can be initialized from another
151 static struct thread *
152 create_thread_struct(lispobj initial_function) {
153 union per_thread_data *per_thread;
154 struct thread *th=0; /* subdue gcc */
157 /* may as well allocate all the spaces at once: it saves us from
158 * having to decide what to do if only some of the allocations
160 spaces=os_validate(0, THREAD_STRUCT_SIZE);
163 per_thread=(union per_thread_data *)
165 THREAD_CONTROL_STACK_SIZE+
170 memcpy(per_thread,arch_os_get_current_thread(),
171 dynamic_values_bytes);
173 #ifdef LISP_FEATURE_SB_THREAD
175 for(i=0;i<(dynamic_values_bytes/sizeof(lispobj));i++)
176 per_thread->dynamic_values[i]=UNBOUND_MARKER_WIDETAG;
177 if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG)
180 make_fixnum(MAX_INTERRUPTS+
181 sizeof(struct thread)/sizeof(lispobj)),
183 #define STATIC_TLS_INIT(sym,field) \
184 ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
185 make_fixnum(THREAD_SLOT_OFFSET_WORDS(field))
187 STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
188 STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
189 STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
190 STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
191 STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
192 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
193 STATIC_TLS_INIT(PSEUDO_ATOMIC_ATOMIC,pseudo_atomic_atomic);
194 STATIC_TLS_INIT(PSEUDO_ATOMIC_INTERRUPTED,pseudo_atomic_interrupted);
196 #undef STATIC_TLS_INIT
200 th=&per_thread->thread;
201 th->control_stack_start = spaces;
202 th->binding_stack_start=
203 (lispobj*)((void*)th->control_stack_start+THREAD_CONTROL_STACK_SIZE);
204 th->control_stack_end = th->binding_stack_start;
205 th->alien_stack_start=
206 (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
207 th->binding_stack_pointer=th->binding_stack_start;
210 th->interrupt_fun=NIL;
211 th->interrupt_fun_lock=0;
212 th->state=STATE_STARTING;
213 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
214 th->alien_stack_pointer=((void *)th->alien_stack_start
215 + ALIEN_STACK_SIZE-N_WORD_BYTES);
217 th->alien_stack_pointer=((void *)th->alien_stack_start);
219 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
220 th->pseudo_atomic_interrupted=0;
221 th->pseudo_atomic_atomic=0;
223 #ifdef LISP_FEATURE_GENCGC
224 gc_set_region_empty(&th->alloc_region);
227 #ifndef LISP_FEATURE_SB_THREAD
228 /* the tls-points-into-struct-thread trick is only good for threaded
229 * sbcl, because unithread sbcl doesn't have tls. So, we copy the
230 * appropriate values from struct thread here, and make sure that
231 * we use the appropriate SymbolValue macros to access any of the
232 * variable quantities from the C runtime. It's not quite OAOOM,
233 * it just feels like it */
234 SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
235 SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
236 SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
237 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
238 SetSymbolValue(BINDING_STACK_POINTER,(lispobj)th->binding_stack_pointer,th);
239 SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
240 SetSymbolValue(PSEUDO_ATOMIC_ATOMIC,(lispobj)th->pseudo_atomic_atomic,th);
241 SetSymbolValue(PSEUDO_ATOMIC_INTERRUPTED,th->pseudo_atomic_interrupted,th);
243 current_binding_stack_pointer=th->binding_stack_pointer;
244 current_control_stack_pointer=th->control_stack_start;
247 bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
248 bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
249 bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
250 bind_variable(INTERRUPT_PENDING, NIL,th);
251 bind_variable(INTERRUPTS_ENABLED,T,th);
252 bind_variable(GC_PENDING,NIL,th);
253 #ifdef LISP_FEATURE_SB_THREAD
254 bind_variable(STOP_FOR_GC_PENDING,NIL,th);
257 th->interrupt_data = (struct interrupt_data *)
258 os_validate(0,(sizeof (struct interrupt_data)));
259 if (!th->interrupt_data) {
260 free_thread_struct(th);
264 memcpy(th->interrupt_data,
265 arch_os_get_current_thread()->interrupt_data,
266 sizeof (struct interrupt_data));
268 memcpy(th->interrupt_data,global_interrupt_data,
269 sizeof (struct interrupt_data));
271 th->unbound_marker=initial_function;
276 link_thread(struct thread *th,os_thread_t kid_tid)
278 if (all_threads) all_threads->prev=th;
279 th->next=all_threads;
282 /* note that th->os_thread is 0 at this time. We rely on
283 * all_threads_lock to ensure that we don't have >1 thread with
284 * os_thread=0 on the list at once
286 protect_control_stack_guard_page(th,1);
287 /* child will not start until this is set */
288 th->os_thread=kid_tid;
289 FSHOW((stderr,"/created thread %lu\n",kid_tid));
292 void create_initial_thread(lispobj initial_function) {
293 struct thread *th=create_thread_struct(initial_function);
294 os_thread_t kid_tid=thread_self();
295 if(th && kid_tid>0) {
296 link_thread(th,kid_tid);
297 initial_thread_trampoline(all_threads); /* no return */
298 } else lose("can't create initial thread");
301 #ifdef LISP_FEATURE_SB_THREAD
303 #ifndef __USE_XOPEN2K
304 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
308 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
310 /* The new thread inherits the restrictive signal mask set here,
311 * and enables signals again when it is set up properly. */
313 sigset_t newset,oldset;
315 sigemptyset(&newset);
316 /* Blocking deferrable signals is enough, since gc_stop_the_world
317 * waits until the child leaves STATE_STARTING. And why not let gc
318 * proceed as soon as possible? */
319 sigaddset_deferrable(&newset);
320 thread_sigmask(SIG_BLOCK, &newset, &oldset);
322 if((pthread_attr_init(&attr)) ||
323 (pthread_attr_setstack(&attr,th->control_stack_start,
324 THREAD_CONTROL_STACK_SIZE-16)) ||
326 (kid_tid,&attr,(void *(*)(void *))new_thread_trampoline,th)))
328 thread_sigmask(SIG_SETMASK,&oldset,0);
332 struct thread *create_thread(lispobj initial_function) {
334 os_thread_t kid_tid=0;
337 if(linux_no_threads_p) return 0;
339 th=create_thread_struct(initial_function);
342 /* we must not be interrupted here after a successful
343 * create_os_thread, because the kid will be waiting for its
344 * thread struct to be linked */
345 GET_ALL_THREADS_LOCK("create_thread")
347 success=create_os_thread(th,&kid_tid);
349 link_thread(th,kid_tid);
351 free_thread_struct(th);
353 RELEASE_ALL_THREADS_LOCK("create_thread")
361 /* called from lisp from the thread object finalizer */
362 void reap_dead_thread(struct thread *th)
364 if(th->state!=STATE_DEAD)
365 lose("thread %p is not joinable, state=%d\n",th,th->state);
366 #ifdef LISP_FEATURE_GENCGC
368 sigset_t newset,oldset;
369 sigemptyset(&newset);
370 sigaddset_blockable(&newset);
371 thread_sigmask(SIG_BLOCK, &newset, &oldset);
372 gc_alloc_update_page_tables(0, &th->alloc_region);
373 thread_sigmask(SIG_SETMASK,&oldset,0);
376 GET_ALL_THREADS_LOCK("reap_dead_thread")
377 FSHOW((stderr,"/reap_dead_thread: reaping %lu\n",th->os_thread));
379 th->prev->next=th->next;
380 else all_threads=th->next;
382 th->next->prev=th->prev;
383 RELEASE_ALL_THREADS_LOCK("reap_dead_thread")
384 if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
385 gc_assert(pthread_join(th->os_thread,NULL)==0);
386 free_thread_struct(th);
389 /* Send the signo to os_thread, retry if the rt signal queue is
391 static int kill_thread_safely(os_thread_t os_thread, int signo)
394 /* The man page does not mention EAGAIN as a valid return value
395 * for either pthread_kill or kill. But that's theory, this is
396 * practice. By waiting here we assume that the delivery of this
397 * signal is not necessary for the delivery of the signals in the
398 * queue. In other words, we _assume_ there are no deadlocks. */
399 while ((r=pthread_kill(os_thread,signo))==EAGAIN) {
400 /* wait a bit then try again in the hope of the rt signal
401 * queue not being full */
402 FSHOW_SIGNAL((stderr,"/rt signal queue full\n"));
403 /* FIXME: some kind of backoff (random, exponential) would be
410 int interrupt_thread(struct thread *th, lispobj function)
412 /* In clone_threads, if A and B both interrupt C at approximately
413 * the same time, it does not matter: the second signal will be
414 * masked until the handler has returned from the first one. In
415 * pthreads though, we can't put the knowledge of what function to
416 * call into the siginfo, so we have to store it in the
417 * destination thread, and do it in such a way that A won't
418 * clobber B's interrupt. Hence, this stupid linked list.
420 * This does depend on SIG_INTERRUPT_THREAD being queued (as POSIX
421 * RT signals are): we need to keep interrupt_fun data for exactly
422 * as many signals as are going to be received by the destination
425 lispobj c=alloc_cons(function,NIL);
426 sigset_t newset,oldset;
427 sigemptyset(&newset);
428 /* interrupt_thread_handler locks this spinlock with blockables
429 * blocked (it does so for the sake of
430 * arrange_return_to_lisp_function), so we must also block them or
431 * else SIG_STOP_FOR_GC and all_threads_lock will find a way to
433 sigaddset_blockable(&newset);
434 thread_sigmask(SIG_BLOCK, &newset, &oldset);
435 if (th == arch_os_get_current_thread())
436 lose("cannot interrupt current thread");
437 get_spinlock(&th->interrupt_fun_lock,
438 (long)arch_os_get_current_thread());
439 ((struct cons *)native_pointer(c))->cdr=th->interrupt_fun;
441 release_spinlock(&th->interrupt_fun_lock);
442 thread_sigmask(SIG_SETMASK,&oldset,0);
443 /* Called from lisp with the thread object as a parameter. Thus,
444 * the object cannot be garbage collected and consequently reaped
445 * and joined. Because it's not joined, kill should work (even if
446 * the thread has died/exited). */
448 int status=kill_thread_safely(th->os_thread,SIG_INTERRUPT_THREAD);
451 } else if (status==ESRCH) {
452 /* This thread has exited. */
453 th->interrupt_fun=NIL;
457 lose("cannot send SIG_INTERRUPT_THREAD to thread=%lu: %d, %s",
458 th->os_thread,status,strerror(status));
463 /* stopping the world is a two-stage process. From this thread we signal
464 * all the others with SIG_STOP_FOR_GC. The handler for this signal does
465 * the usual pseudo-atomic checks (we don't want to stop a thread while
466 * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
469 /* To avoid deadlocks when gc stops the world all clients of each
470 * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
471 * holding the lock, but they must agree on which. */
472 void gc_stop_the_world()
474 struct thread *p,*th=arch_os_get_current_thread();
476 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock, thread=%lu\n",
478 /* keep threads from starting while the world is stopped. */
479 pthread_mutex_lock(&all_threads_lock); \
480 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock, thread=%lu\n",
482 /* stop all other threads by sending them SIG_STOP_FOR_GC */
483 for(p=all_threads; p; p=p->next) {
484 while(p->state==STATE_STARTING) sched_yield();
485 if((p!=th) && (p->state==STATE_RUNNING)) {
486 FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending %lu\n",
488 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
490 /* This thread has exited. */
491 gc_assert(p->state==STATE_DEAD);
493 lose("cannot send suspend thread=%lu: %d, %s",
494 p->os_thread,status,strerror(status));
498 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
499 /* wait for the running threads to stop or finish */
500 for(p=all_threads;p;) {
501 gc_assert(p->os_thread!=0);
502 gc_assert(p->state!=STATE_STARTING);
503 if((p==th) || (p->state==STATE_SUSPENDED) ||
504 (p->state==STATE_DEAD)) {
510 FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
513 void gc_start_the_world()
515 struct thread *p,*th=arch_os_get_current_thread();
517 /* if a resumed thread creates a new thread before we're done with
518 * this loop, the new thread will get consed on the front of
519 * all_threads, but it won't have been stopped so won't need
521 FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
522 for(p=all_threads;p;p=p->next) {
523 gc_assert(p->os_thread!=0);
524 if((p!=th) && (p->state!=STATE_DEAD)) {
525 if(p->state!=STATE_SUSPENDED) {
526 lose("gc_start_the_world: wrong thread state is %d\n",
527 fixnum_value(p->state));
529 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
531 p->state=STATE_RUNNING;
532 status=kill_thread_safely(p->os_thread,SIG_STOP_FOR_GC);
534 lose("cannot resume thread=%lu: %d, %s",
535 p->os_thread,status,strerror(status));
539 /* If we waited here until all threads leave STATE_SUSPENDED, then
540 * SIG_STOP_FOR_GC wouldn't need to be a rt signal. That has some
541 * performance implications, but does away with the 'rt signal
542 * queue full' problem. */
543 pthread_mutex_unlock(&all_threads_lock); \
544 FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));