Port to x86-64 versions of Windows
[sbcl.git] / src / runtime / thread.c
1 /*
2  * This software is part of the SBCL system. See the README file for
3  * more information.
4  *
5  * This software is derived from the CMU CL system, which was
6  * written at Carnegie Mellon University and released into the
7  * public domain. The software is in the public domain and is
8  * provided with absolutely no warranty. See the COPYING and CREDITS
9  * files for more information.
10  */
11
12 #include "sbcl.h"
13
14 #include <stdlib.h>
15 #include <stdio.h>
16 #include <string.h>
17 #ifndef LISP_FEATURE_WIN32
18 #include <sched.h>
19 #endif
20 #include "runtime.h"
21 #include <stddef.h>
22 #include <errno.h>
23 #include <sys/types.h>
24 #ifndef LISP_FEATURE_WIN32
25 #include <sys/wait.h>
26 #endif
27
28 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
29 #include <mach/mach.h>
30 #include <mach/mach_error.h>
31 #include <mach/mach_types.h>
32 #endif
33
34 #include "runtime.h"
35 #include "validate.h"           /* for BINDING_STACK_SIZE etc */
36 #include "thread.h"
37 #include "arch.h"
38 #include "target-arch-os.h"
39 #include "os.h"
40 #include "globals.h"
41 #include "dynbind.h"
42 #include "genesis/cons.h"
43 #include "genesis/fdefn.h"
44 #include "interr.h"             /* for lose() */
45 #include "alloc.h"
46 #include "gc-internal.h"
47 #include "cpputil.h"
48 #include "pseudo-atomic.h"
49 #include "interrupt.h"
50 #include "lispregs.h"
51
52 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THREAD)
53 # define IMMEDIATE_POST_MORTEM
54 #endif
55
56 #if defined(LISP_FEATURE_DARWIN) && defined(LISP_FEATURE_SB_THREAD)
57 #define DELAY_THREAD_POST_MORTEM 5
58 #define LOCK_CREATE_THREAD
59 #endif
60
61 #ifdef LISP_FEATURE_FREEBSD
62 #define CREATE_CLEANUP_THREAD
63 #define LOCK_CREATE_THREAD
64 #endif
65
66 #ifdef LISP_FEATURE_SB_THREAD
67 struct thread_post_mortem {
68 #ifdef DELAY_THREAD_POST_MORTEM
69     struct thread_post_mortem *next;
70 #endif
71     os_thread_t os_thread;
72     pthread_attr_t *os_attr;
73     os_vm_address_t os_address;
74 };
75
76 #ifdef DELAY_THREAD_POST_MORTEM
77 static int pending_thread_post_mortem_count = 0;
78 pthread_mutex_t thread_post_mortem_lock = PTHREAD_MUTEX_INITIALIZER;
79 #endif
80 static struct thread_post_mortem * volatile pending_thread_post_mortem = 0;
81 #endif
82
83 int dynamic_values_bytes=TLS_SIZE*sizeof(lispobj);  /* same for all threads */
84 struct thread *all_threads;
85 extern struct interrupt_data * global_interrupt_data;
86
87 #ifdef LISP_FEATURE_SB_THREAD
88 pthread_mutex_t all_threads_lock = PTHREAD_MUTEX_INITIALIZER;
89 #ifdef LOCK_CREATE_THREAD
90 static pthread_mutex_t create_thread_lock = PTHREAD_MUTEX_INITIALIZER;
91 #endif
92 #ifdef LISP_FEATURE_GCC_TLS
93 __thread struct thread *current_thread;
94 #endif
95 pthread_key_t lisp_thread = 0;
96 #endif
97
98 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
99 extern lispobj call_into_lisp_first_time(lispobj fun, lispobj *args, int nargs)
100 # ifdef LISP_FEATURE_X86_64
101     __attribute__((sysv_abi))
102 # endif
103     ;
104 #endif
105
106 static void
107 link_thread(struct thread *th)
108 {
109     if (all_threads) all_threads->prev=th;
110     th->next=all_threads;
111     th->prev=0;
112     all_threads=th;
113 }
114
115 #ifdef LISP_FEATURE_SB_THREAD
116 static void
117 unlink_thread(struct thread *th)
118 {
119     if (th->prev)
120         th->prev->next = th->next;
121     else
122         all_threads = th->next;
123     if (th->next)
124         th->next->prev = th->prev;
125 }
126
127 #ifndef LISP_FEATURE_SB_SAFEPOINT
128 /* Only access thread state with blockables blocked. */
129 lispobj
130 thread_state(struct thread *thread)
131 {
132     lispobj state;
133     sigset_t old;
134     block_blockable_signals(NULL, &old);
135     os_sem_wait(thread->state_sem, "thread_state");
136     state = thread->state;
137     os_sem_post(thread->state_sem, "thread_state");
138     thread_sigmask(SIG_SETMASK, &old, NULL);
139     return state;
140 }
141
142 void
143 set_thread_state(struct thread *thread, lispobj state)
144 {
145     int i, waitcount = 0;
146     sigset_t old;
147     block_blockable_signals(NULL, &old);
148     os_sem_wait(thread->state_sem, "set_thread_state");
149     if (thread->state != state) {
150         if ((STATE_STOPPED==state) ||
151             (STATE_DEAD==state)) {
152             waitcount = thread->state_not_running_waitcount;
153             thread->state_not_running_waitcount = 0;
154             for (i=0; i<waitcount; i++)
155                 os_sem_post(thread->state_not_running_sem, "set_thread_state (not running)");
156         }
157         if ((STATE_RUNNING==state) ||
158             (STATE_DEAD==state)) {
159             waitcount = thread->state_not_stopped_waitcount;
160             thread->state_not_stopped_waitcount = 0;
161             for (i=0; i<waitcount; i++)
162                 os_sem_post(thread->state_not_stopped_sem, "set_thread_state (not stopped)");
163         }
164         thread->state = state;
165     }
166     os_sem_post(thread->state_sem, "set_thread_state");
167     thread_sigmask(SIG_SETMASK, &old, NULL);
168 }
169
170 void
171 wait_for_thread_state_change(struct thread *thread, lispobj state)
172 {
173     sigset_t old;
174     os_sem_t *wait_sem;
175     block_blockable_signals(NULL, &old);
176   start:
177     os_sem_wait(thread->state_sem, "wait_for_thread_state_change");
178     if (thread->state == state) {
179         switch (state) {
180         case STATE_RUNNING:
181             wait_sem = thread->state_not_running_sem;
182             thread->state_not_running_waitcount++;
183             break;
184         case STATE_STOPPED:
185             wait_sem = thread->state_not_stopped_sem;
186             thread->state_not_stopped_waitcount++;
187             break;
188         default:
189             lose("Invalid state in wait_for_thread_state_change: "OBJ_FMTX"\n", state);
190         }
191     } else {
192         wait_sem = NULL;
193     }
194     os_sem_post(thread->state_sem, "wait_for_thread_state_change");
195     if (wait_sem) {
196         os_sem_wait(wait_sem, "wait_for_thread_state_change");
197         goto start;
198     }
199     thread_sigmask(SIG_SETMASK, &old, NULL);
200 }
201 #endif /* sb-safepoint */
202 #endif /* sb-thread */
203
204 static int
205 initial_thread_trampoline(struct thread *th)
206 {
207     lispobj function;
208 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
209     lispobj *args = NULL;
210 #endif
211 #ifdef LISP_FEATURE_SB_THREAD
212     pthread_setspecific(lisp_thread, (void *)1);
213 #endif
214 #if defined(THREADS_USING_GCSIGNAL) && defined(LISP_FEATURE_PPC)
215     /* SIG_STOP_FOR_GC defaults to blocked on PPC? */
216     unblock_gc_signals(0,0);
217 #endif
218     function = th->no_tls_value_marker;
219     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
220     if(arch_os_thread_init(th)==0) return 1;
221     link_thread(th);
222     th->os_thread=thread_self();
223 #ifndef LISP_FEATURE_WIN32
224     protect_control_stack_hard_guard_page(1, NULL);
225 #endif
226     protect_binding_stack_hard_guard_page(1, NULL);
227     protect_alien_stack_hard_guard_page(1, NULL);
228 #ifndef LISP_FEATURE_WIN32
229     protect_control_stack_guard_page(1, NULL);
230 #endif
231     protect_binding_stack_guard_page(1, NULL);
232     protect_alien_stack_guard_page(1, NULL);
233
234 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
235     return call_into_lisp_first_time(function,args,0);
236 #else
237     return funcall0(function);
238 #endif
239 }
240
241 #ifdef LISP_FEATURE_SB_THREAD
242
243 # if defined(IMMEDIATE_POST_MORTEM)
244
245 /*
246  * If this feature is set, we are running on a stack managed by the OS,
247  * and no fancy delays are required for anything.  Just do it.
248  */
249 static void
250 schedule_thread_post_mortem(struct thread *corpse)
251 {
252     pthread_detach(pthread_self());
253     gc_assert(!pthread_attr_destroy(corpse->os_attr));
254     free(corpse->os_attr);
255 #if defined(LISP_FEATURE_WIN32)
256     os_invalidate_free(corpse->os_address, THREAD_STRUCT_SIZE);
257 #else
258     os_invalidate(corpse->os_address, THREAD_STRUCT_SIZE);
259 #endif
260 }
261
262 # else
263
264 /* THREAD POST MORTEM CLEANUP
265  *
266  * Memory allocated for the thread stacks cannot be reclaimed while
267  * the thread is still alive, so we need a mechanism for post mortem
268  * cleanups. FIXME: We actually have three, for historical reasons as
269  * the saying goes. Do we really need three? Nikodemus guesses that
270  * not anymore, now that we properly call pthread_attr_destroy before
271  * freeing the stack. */
272
273 static struct thread_post_mortem *
274 plan_thread_post_mortem(struct thread *corpse)
275 {
276     if (corpse) {
277         struct thread_post_mortem *post_mortem = malloc(sizeof(struct thread_post_mortem));
278         gc_assert(post_mortem);
279         post_mortem->os_thread = corpse->os_thread;
280         post_mortem->os_attr = corpse->os_attr;
281         post_mortem->os_address = corpse->os_address;
282 #ifdef DELAY_THREAD_POST_MORTEM
283         post_mortem->next = NULL;
284 #endif
285         return post_mortem;
286     } else {
287         /* FIXME: When does this happen? */
288         return NULL;
289     }
290 }
291
292 static void
293 perform_thread_post_mortem(struct thread_post_mortem *post_mortem)
294 {
295 #ifdef CREATE_POST_MORTEM_THREAD
296     pthread_detach(pthread_self());
297 #endif
298     if (post_mortem) {
299         gc_assert(!pthread_join(post_mortem->os_thread, NULL));
300         gc_assert(!pthread_attr_destroy(post_mortem->os_attr));
301         free(post_mortem->os_attr);
302         os_invalidate(post_mortem->os_address, THREAD_STRUCT_SIZE);
303         free(post_mortem);
304     }
305 }
306
307 static void
308 schedule_thread_post_mortem(struct thread *corpse)
309 {
310     struct thread_post_mortem *post_mortem = NULL;
311     if (corpse) {
312         post_mortem = plan_thread_post_mortem(corpse);
313
314 #ifdef DELAY_THREAD_POST_MORTEM
315         pthread_mutex_lock(&thread_post_mortem_lock);
316         /* First stick the new post mortem to the end of the queue. */
317         if (pending_thread_post_mortem) {
318             struct thread_post_mortem *next = pending_thread_post_mortem;
319             while (next->next) {
320                 next = next->next;
321             }
322             next->next = post_mortem;
323         } else {
324             pending_thread_post_mortem = post_mortem;
325         }
326         /* Then, if there are enough things in the queue, clean up one
327          * from the head -- or increment the count, and null out the
328          * post_mortem we have. */
329         if (pending_thread_post_mortem_count > DELAY_THREAD_POST_MORTEM) {
330             post_mortem = pending_thread_post_mortem;
331             pending_thread_post_mortem = post_mortem->next;
332         } else {
333             pending_thread_post_mortem_count++;
334             post_mortem = NULL;
335         }
336         pthread_mutex_unlock(&thread_post_mortem_lock);
337         /* Finally run, the cleanup, if any. */
338         perform_thread_post_mortem(post_mortem);
339 #elif defined(CREATE_POST_MORTEM_THREAD)
340         gc_assert(!pthread_create(&thread, NULL, perform_thread_post_mortem, post_mortem));
341 #else
342         post_mortem = (struct thread_post_mortem *)
343             swap_lispobjs((lispobj *)(void *)&pending_thread_post_mortem,
344                           (lispobj)post_mortem);
345         perform_thread_post_mortem(post_mortem);
346 #endif
347     }
348 }
349
350 # endif /* !IMMEDIATE_POST_MORTEM */
351
352 /* this is the first thing that runs in the child (which is why the
353  * silly calling convention).  Basically it calls the user's requested
354  * lisp function after doing arch_os_thread_init and whatever other
355  * bookkeeping needs to be done
356  */
357 int
358 new_thread_trampoline(struct thread *th)
359 {
360     lispobj function;
361     int result, lock_ret;
362
363     FSHOW((stderr,"/creating thread %lu\n", thread_self()));
364     check_deferrables_blocked_or_lose(0);
365 #ifndef LISP_FEATURE_SB_SAFEPOINT
366     check_gc_signals_unblocked_or_lose(0);
367 #endif
368     pthread_setspecific(lisp_thread, (void *)1);
369     function = th->no_tls_value_marker;
370     th->no_tls_value_marker = NO_TLS_VALUE_MARKER_WIDETAG;
371     if(arch_os_thread_init(th)==0) {
372         /* FIXME: handle error */
373         lose("arch_os_thread_init failed\n");
374     }
375
376     th->os_thread=thread_self();
377     protect_control_stack_guard_page(1, NULL);
378     protect_binding_stack_guard_page(1, NULL);
379     protect_alien_stack_guard_page(1, NULL);
380     /* Since GC can only know about this thread from the all_threads
381      * list and we're just adding this thread to it, there is no
382      * danger of deadlocking even with SIG_STOP_FOR_GC blocked (which
383      * it is not). */
384 #ifdef LISP_FEATURE_SB_SAFEPOINT
385     *th->csp_around_foreign_call = (lispobj)&function;
386 #endif
387     lock_ret = pthread_mutex_lock(&all_threads_lock);
388     gc_assert(lock_ret == 0);
389     link_thread(th);
390     lock_ret = pthread_mutex_unlock(&all_threads_lock);
391     gc_assert(lock_ret == 0);
392
393     /* Kludge: Changed the order of some steps between the safepoint/
394      * non-safepoint versions of this code.  Can we unify this more?
395      */
396 #ifdef LISP_FEATURE_SB_SAFEPOINT
397     gc_state_lock();
398     gc_state_wait(GC_NONE);
399     gc_state_unlock();
400     WITH_GC_AT_SAFEPOINTS_ONLY() {
401         result = funcall0(function);
402         block_blockable_signals(0, 0);
403         gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
404     }
405     lock_ret = pthread_mutex_lock(&all_threads_lock);
406     gc_assert(lock_ret == 0);
407     unlink_thread(th);
408     lock_ret = pthread_mutex_unlock(&all_threads_lock);
409     gc_assert(lock_ret == 0);
410 #else
411     result = funcall0(function);
412
413     /* Block GC */
414     block_blockable_signals(0, 0);
415     set_thread_state(th, STATE_DEAD);
416
417     /* SIG_STOP_FOR_GC is blocked and GC might be waiting for this
418      * thread, but since we are already dead it won't wait long. */
419     lock_ret = pthread_mutex_lock(&all_threads_lock);
420     gc_assert(lock_ret == 0);
421
422     gc_alloc_update_page_tables(BOXED_PAGE_FLAG, &th->alloc_region);
423     unlink_thread(th);
424     pthread_mutex_unlock(&all_threads_lock);
425     gc_assert(lock_ret == 0);
426 #endif
427
428     if(th->tls_cookie>=0) arch_os_thread_cleanup(th);
429 #ifndef LISP_FEATURE_SB_SAFEPOINT
430     os_sem_destroy(th->state_sem);
431     os_sem_destroy(th->state_not_running_sem);
432     os_sem_destroy(th->state_not_stopped_sem);
433 #endif
434
435 #if defined(LISP_FEATURE_WIN32)
436     free((os_vm_address_t)th->interrupt_data);
437 #else
438     os_invalidate((os_vm_address_t)th->interrupt_data,
439                   (sizeof (struct interrupt_data)));
440 #endif
441
442 #ifdef LISP_FEATURE_MACH_EXCEPTION_HANDLER
443     mach_lisp_thread_destroy(th);
444 #endif
445
446 #if defined(LISP_FEATURE_WIN32)
447     int i;
448     for (i = 0; i<
449              (int) (sizeof(th->private_events.events)/
450                     sizeof(th->private_events.events[0])); ++i) {
451       CloseHandle(th->private_events.events[i]);
452     }
453     TlsSetValue(OUR_TLS_INDEX,NULL);
454 #endif
455
456     schedule_thread_post_mortem(th);
457     FSHOW((stderr,"/exiting thread %lu\n", thread_self()));
458     return result;
459 }
460
461 #endif /* LISP_FEATURE_SB_THREAD */
462
463 static void
464 free_thread_struct(struct thread *th)
465 {
466 #if defined(LISP_FEATURE_WIN32)
467     if (th->interrupt_data) {
468         os_invalidate_free((os_vm_address_t) th->interrupt_data,
469                       (sizeof (struct interrupt_data)));
470     }
471     os_invalidate_free((os_vm_address_t) th->os_address,
472                   THREAD_STRUCT_SIZE);
473 #else
474     if (th->interrupt_data)
475         os_invalidate((os_vm_address_t) th->interrupt_data,
476                       (sizeof (struct interrupt_data)));
477     os_invalidate((os_vm_address_t) th->os_address,
478                   THREAD_STRUCT_SIZE);
479 #endif
480 }
481
482 #ifdef LISP_FEATURE_SB_THREAD
483 /* FIXME: should be MAX_INTERRUPTS -1 ? */
484 const unsigned int tls_index_start =
485   MAX_INTERRUPTS + sizeof(struct thread)/sizeof(lispobj);
486 #endif
487
488 /* this is called from any other thread to create the new one, and
489  * initialize all parts of it that can be initialized from another
490  * thread
491  */
492
493 static struct thread *
494 create_thread_struct(lispobj initial_function) {
495     union per_thread_data *per_thread;
496     struct thread *th=0;        /*  subdue gcc */
497     void *spaces=0;
498     void *aligned_spaces=0;
499 #if defined(LISP_FEATURE_SB_THREAD) || defined(LISP_FEATURE_WIN32)
500     unsigned int i;
501 #endif
502
503     /* May as well allocate all the spaces at once: it saves us from
504      * having to decide what to do if only some of the allocations
505      * succeed. SPACES must be appropriately aligned, since the GC
506      * expects the control stack to start at a page boundary -- and
507      * the OS may have even more rigorous requirements. We can't rely
508      * on the alignment passed from os_validate, since that might
509      * assume the current (e.g. 4k) pagesize, while we calculate with
510      * the biggest (e.g. 64k) pagesize allowed by the ABI. */
511     spaces=os_validate(0, THREAD_STRUCT_SIZE);
512     if(!spaces)
513         return NULL;
514     /* Aligning up is safe as THREAD_STRUCT_SIZE has
515      * THREAD_ALIGNMENT_BYTES padding. */
516     aligned_spaces = (void *)((((uword_t)(char *)spaces)
517                                + THREAD_ALIGNMENT_BYTES-1)
518                               &~(uword_t)(THREAD_ALIGNMENT_BYTES-1));
519     void* csp_page=
520         (aligned_spaces+
521          thread_control_stack_size+
522          BINDING_STACK_SIZE+
523          ALIEN_STACK_SIZE);
524     per_thread=(union per_thread_data *)
525         (csp_page + THREAD_CSP_PAGE_SIZE);
526     struct nonpointer_thread_data *nonpointer_data
527         = (void *) &per_thread->dynamic_values[TLS_SIZE];
528
529 #ifdef LISP_FEATURE_SB_THREAD
530     for(i = 0; i < (dynamic_values_bytes / sizeof(lispobj)); i++)
531         per_thread->dynamic_values[i] = NO_TLS_VALUE_MARKER_WIDETAG;
532     if (all_threads == 0) {
533         if(SymbolValue(FREE_TLS_INDEX,0)==UNBOUND_MARKER_WIDETAG) {
534             SetSymbolValue(FREE_TLS_INDEX,tls_index_start << WORD_SHIFT,0);
535             SetSymbolValue(TLS_INDEX_LOCK,make_fixnum(0),0);
536         }
537 #define STATIC_TLS_INIT(sym,field) \
538   ((struct symbol *)(sym-OTHER_POINTER_LOWTAG))->tls_index= \
539   (THREAD_SLOT_OFFSET_WORDS(field) << WORD_SHIFT)
540
541         STATIC_TLS_INIT(BINDING_STACK_START,binding_stack_start);
542 #ifdef BINDING_STACK_POINTER
543         STATIC_TLS_INIT(BINDING_STACK_POINTER,binding_stack_pointer);
544 #endif
545         STATIC_TLS_INIT(CONTROL_STACK_START,control_stack_start);
546         STATIC_TLS_INIT(CONTROL_STACK_END,control_stack_end);
547 #ifdef ALIEN_STACK
548         STATIC_TLS_INIT(ALIEN_STACK,alien_stack_pointer);
549 #endif
550 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
551         STATIC_TLS_INIT(PSEUDO_ATOMIC_BITS,pseudo_atomic_bits);
552 #endif
553 #undef STATIC_TLS_INIT
554     }
555 #endif
556
557     th=&per_thread->thread;
558     th->os_address = spaces;
559     th->control_stack_start = aligned_spaces;
560     th->binding_stack_start=
561         (lispobj*)((void*)th->control_stack_start+thread_control_stack_size);
562     th->control_stack_end = th->binding_stack_start;
563     th->control_stack_guard_page_protected = T;
564     th->alien_stack_start=
565         (lispobj*)((void*)th->binding_stack_start+BINDING_STACK_SIZE);
566     set_binding_stack_pointer(th,th->binding_stack_start);
567     th->this=th;
568     th->os_thread=0;
569
570 #ifdef LISP_FEATURE_SB_SAFEPOINT
571     th->pc_around_foreign_call = 0;
572     th->csp_around_foreign_call = csp_page;
573 #endif
574
575 #ifdef LISP_FEATURE_SB_THREAD
576     /* Contrary to the "allocate all the spaces at once" comment above,
577      * the os_attr is allocated separately.  We cannot put it into the
578      * nonpointer data, because it's used for post_mortem and freed
579      * separately */
580     th->os_attr=malloc(sizeof(pthread_attr_t));
581     th->nonpointer_data = nonpointer_data;
582 # ifndef LISP_FEATURE_SB_SAFEPOINT
583     th->state_sem=&nonpointer_data->state_sem;
584     th->state_not_running_sem=&nonpointer_data->state_not_running_sem;
585     th->state_not_stopped_sem=&nonpointer_data->state_not_stopped_sem;
586     os_sem_init(th->state_sem, 1);
587     os_sem_init(th->state_not_running_sem, 0);
588     os_sem_init(th->state_not_stopped_sem, 0);
589 # endif
590     th->state_not_running_waitcount = 0;
591     th->state_not_stopped_waitcount = 0;
592 #endif
593     th->state=STATE_RUNNING;
594 #ifdef LISP_FEATURE_STACK_GROWS_DOWNWARD_NOT_UPWARD
595     th->alien_stack_pointer=((void *)th->alien_stack_start
596                              + ALIEN_STACK_SIZE-N_WORD_BYTES);
597 #else
598     th->alien_stack_pointer=((void *)th->alien_stack_start);
599 #endif
600 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64) || defined(LISP_FEATURE_SB_THREAD)
601     th->pseudo_atomic_bits=0;
602 #endif
603 #ifdef LISP_FEATURE_GENCGC
604     gc_set_region_empty(&th->alloc_region);
605 #endif
606 #ifdef LISP_FEATURE_SB_THREAD
607     /* This parallels the same logic in globals.c for the
608      * single-threaded foreign_function_call_active, KLUDGE and
609      * all. */
610 #if defined(LISP_FEATURE_X86) || defined(LISP_FEATURE_X86_64)
611     th->foreign_function_call_active = 0;
612 #else
613     th->foreign_function_call_active = 1;
614 #endif
615 #endif
616
617 #ifndef LISP_FEATURE_SB_THREAD
618     /* the tls-points-into-struct-thread trick is only good for threaded
619      * sbcl, because unithread sbcl doesn't have tls.  So, we copy the
620      * appropriate values from struct thread here, and make sure that
621      * we use the appropriate SymbolValue macros to access any of the
622      * variable quantities from the C runtime.  It's not quite OAOOM,
623      * it just feels like it */
624     SetSymbolValue(BINDING_STACK_START,(lispobj)th->binding_stack_start,th);
625     SetSymbolValue(CONTROL_STACK_START,(lispobj)th->control_stack_start,th);
626     SetSymbolValue(CONTROL_STACK_END,(lispobj)th->control_stack_end,th);
627 #if defined(LISP_FEATURE_X86) || defined (LISP_FEATURE_X86_64)
628     SetSymbolValue(ALIEN_STACK,(lispobj)th->alien_stack_pointer,th);
629     SetSymbolValue(PSEUDO_ATOMIC_BITS,(lispobj)th->pseudo_atomic_bits,th);
630 #endif
631 #endif
632     bind_variable(CURRENT_CATCH_BLOCK,make_fixnum(0),th);
633     bind_variable(CURRENT_UNWIND_PROTECT_BLOCK,make_fixnum(0),th);
634     bind_variable(FREE_INTERRUPT_CONTEXT_INDEX,make_fixnum(0),th);
635     bind_variable(INTERRUPT_PENDING, NIL,th);
636     bind_variable(INTERRUPTS_ENABLED,T,th);
637     bind_variable(ALLOW_WITH_INTERRUPTS,T,th);
638     bind_variable(GC_PENDING,NIL,th);
639     bind_variable(ALLOC_SIGNAL,NIL,th);
640 #ifdef PINNED_OBJECTS
641     bind_variable(PINNED_OBJECTS,NIL,th);
642 #endif
643 #ifdef LISP_FEATURE_SB_THREAD
644     bind_variable(STOP_FOR_GC_PENDING,NIL,th);
645 #endif
646 #if defined(LISP_FEATURE_SB_SAFEPOINT)
647     bind_variable(GC_SAFE,NIL,th);
648     bind_variable(IN_SAFEPOINT,NIL,th);
649 #endif
650 #ifdef LISP_FEATURE_SB_THRUPTION
651     bind_variable(THRUPTION_PENDING,NIL,th);
652     bind_variable(RESTART_CLUSTERS,NIL,th);
653 #endif
654 #ifndef LISP_FEATURE_C_STACK_IS_CONTROL_STACK
655     access_control_stack_pointer(th)=th->control_stack_start;
656 #endif
657
658 #if defined(LISP_FEATURE_WIN32)
659     th->interrupt_data = (struct interrupt_data *)
660         calloc((sizeof (struct interrupt_data)),1);
661 #else
662     th->interrupt_data = (struct interrupt_data *)
663         os_validate(0,(sizeof (struct interrupt_data)));
664 #endif
665     if (!th->interrupt_data) {
666         free_thread_struct(th);
667         return 0;
668     }
669     th->interrupt_data->pending_handler = 0;
670     th->interrupt_data->gc_blocked_deferrables = 0;
671 #ifdef GENCGC_IS_PRECISE
672     th->interrupt_data->allocation_trap_context = 0;
673 #endif
674     th->no_tls_value_marker=initial_function;
675
676 #if defined(LISP_FEATURE_WIN32)
677     for (i = 0; i<sizeof(th->private_events.events)/
678            sizeof(th->private_events.events[0]); ++i) {
679       th->private_events.events[i] = CreateEvent(NULL,FALSE,FALSE,NULL);
680     }
681     th->synchronous_io_handle_and_flag = 0;
682 #endif
683     th->stepping = NIL;
684     return th;
685 }
686
687 void create_initial_thread(lispobj initial_function) {
688     struct thread *th=create_thread_struct(initial_function);
689 #ifdef LISP_FEATURE_SB_THREAD
690     pthread_key_create(&lisp_thread, 0);
691 #endif
692     if(th) {
693         initial_thread_trampoline(th); /* no return */
694     } else lose("can't create initial thread\n");
695 }
696
697 #ifdef LISP_FEATURE_SB_THREAD
698
699 #ifndef __USE_XOPEN2K
700 extern int pthread_attr_setstack (pthread_attr_t *__attr, void *__stackaddr,
701                                   size_t __stacksize);
702 #endif
703
704 boolean create_os_thread(struct thread *th,os_thread_t *kid_tid)
705 {
706     /* The new thread inherits the restrictive signal mask set here,
707      * and enables signals again when it is set up properly. */
708     sigset_t oldset;
709     boolean r=1;
710     int retcode = 0, initcode;
711
712     FSHOW_SIGNAL((stderr,"/create_os_thread: creating new thread\n"));
713
714     /* Blocking deferrable signals is enough, no need to block
715      * SIG_STOP_FOR_GC because the child process is not linked onto
716      * all_threads until it's ready. */
717     block_deferrable_signals(0, &oldset);
718
719 #ifdef LOCK_CREATE_THREAD
720     retcode = pthread_mutex_lock(&create_thread_lock);
721     gc_assert(retcode == 0);
722     FSHOW_SIGNAL((stderr,"/create_os_thread: got lock\n"));
723 #endif
724
725     if((initcode = pthread_attr_init(th->os_attr)) ||
726        /* call_into_lisp_first_time switches the stack for the initial
727         * thread. For the others, we use this. */
728 #if defined(LISP_FEATURE_WIN32)
729        (pthread_attr_setstacksize(th->os_attr, thread_control_stack_size)) ||
730 #else
731        (pthread_attr_setstack(th->os_attr,th->control_stack_start,
732                               thread_control_stack_size)) ||
733 #endif
734        (retcode = pthread_create
735         (kid_tid,th->os_attr,(void *(*)(void *))new_thread_trampoline,th))) {
736         FSHOW_SIGNAL((stderr, "init = %d\n", initcode));
737         FSHOW_SIGNAL((stderr, "pthread_create returned %d, errno %d\n",
738                       retcode, errno));
739         if(retcode < 0) {
740             perror("create_os_thread");
741         }
742         r=0;
743     }
744
745 #ifdef LOCK_CREATE_THREAD
746     retcode = pthread_mutex_unlock(&create_thread_lock);
747     gc_assert(retcode == 0);
748     FSHOW_SIGNAL((stderr,"/create_os_thread: released lock\n"));
749 #endif
750     thread_sigmask(SIG_SETMASK,&oldset,0);
751     return r;
752 }
753
754 os_thread_t create_thread(lispobj initial_function) {
755     struct thread *th, *thread = arch_os_get_current_thread();
756     os_thread_t kid_tid = 0;
757
758     /* Must defend against async unwinds. */
759     if (SymbolValue(INTERRUPTS_ENABLED, thread) != NIL)
760         lose("create_thread is not safe when interrupts are enabled.\n");
761
762     /* Assuming that a fresh thread struct has no lisp objects in it,
763      * linking it to all_threads can be left to the thread itself
764      * without fear of gc lossage. initial_function violates this
765      * assumption and must stay pinned until the child starts up. */
766     th = create_thread_struct(initial_function);
767     if (th && !create_os_thread(th,&kid_tid)) {
768         free_thread_struct(th);
769         kid_tid = 0;
770     }
771     return kid_tid;
772 }
773
774 /* stopping the world is a two-stage process.  From this thread we signal
775  * all the others with SIG_STOP_FOR_GC.  The handler for this signal does
776  * the usual pseudo-atomic checks (we don't want to stop a thread while
777  * it's in the middle of allocation) then waits for another SIG_STOP_FOR_GC.
778  */
779 /*
780  * (With SB-SAFEPOINT, see the definitions in safepoint.c instead.)
781  */
782 #ifndef LISP_FEATURE_SB_SAFEPOINT
783
784 /* To avoid deadlocks when gc stops the world all clients of each
785  * mutex must enable or disable SIG_STOP_FOR_GC for the duration of
786  * holding the lock, but they must agree on which. */
787 void gc_stop_the_world()
788 {
789     struct thread *p,*th=arch_os_get_current_thread();
790     int status, lock_ret;
791 #ifdef LOCK_CREATE_THREAD
792     /* KLUDGE: Stopping the thread during pthread_create() causes deadlock
793      * on FreeBSD. */
794     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on create_thread_lock\n"));
795     lock_ret = pthread_mutex_lock(&create_thread_lock);
796     gc_assert(lock_ret == 0);
797     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got create_thread_lock\n"));
798 #endif
799     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:waiting on lock\n"));
800     /* keep threads from starting while the world is stopped. */
801     lock_ret = pthread_mutex_lock(&all_threads_lock);      \
802     gc_assert(lock_ret == 0);
803
804     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:got lock\n"));
805     /* stop all other threads by sending them SIG_STOP_FOR_GC */
806     for(p=all_threads; p; p=p->next) {
807         gc_assert(p->os_thread != 0);
808         FSHOW_SIGNAL((stderr,"/gc_stop_the_world: thread=%lu, state=%x\n",
809                       p->os_thread, thread_state(p)));
810         if((p!=th) && ((thread_state(p)==STATE_RUNNING))) {
811             FSHOW_SIGNAL((stderr,"/gc_stop_the_world: suspending thread %lu\n",
812                           p->os_thread));
813             /* We already hold all_thread_lock, P can become DEAD but
814              * cannot exit, ergo it's safe to use pthread_kill. */
815             status=pthread_kill(p->os_thread,SIG_STOP_FOR_GC);
816             if (status==ESRCH) {
817                 /* This thread has exited. */
818                 gc_assert(thread_state(p)==STATE_DEAD);
819             } else if (status) {
820                 lose("cannot send suspend thread=%lu: %d, %s\n",
821                      p->os_thread,status,strerror(status));
822             }
823         }
824     }
825     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:signals sent\n"));
826     for(p=all_threads;p;p=p->next) {
827         if (p!=th) {
828             FSHOW_SIGNAL
829                 ((stderr,
830                   "/gc_stop_the_world: waiting for thread=%lu: state=%x\n",
831                   p->os_thread, thread_state(p)));
832             wait_for_thread_state_change(p, STATE_RUNNING);
833             if (p->state == STATE_RUNNING)
834                 lose("/gc_stop_the_world: unexpected state");
835         }
836     }
837     FSHOW_SIGNAL((stderr,"/gc_stop_the_world:end\n"));
838 }
839
840 void gc_start_the_world()
841 {
842     struct thread *p,*th=arch_os_get_current_thread();
843     int lock_ret;
844     /* if a resumed thread creates a new thread before we're done with
845      * this loop, the new thread will get consed on the front of
846      * all_threads, but it won't have been stopped so won't need
847      * restarting */
848     FSHOW_SIGNAL((stderr,"/gc_start_the_world:begin\n"));
849     for(p=all_threads;p;p=p->next) {
850         gc_assert(p->os_thread!=0);
851         if (p!=th) {
852             lispobj state = thread_state(p);
853             if (state != STATE_DEAD) {
854                 if(state != STATE_STOPPED) {
855                     lose("gc_start_the_world: wrong thread state is %d\n",
856                          fixnum_value(state));
857                 }
858                 FSHOW_SIGNAL((stderr, "/gc_start_the_world: resuming %lu\n",
859                               p->os_thread));
860                 set_thread_state(p, STATE_RUNNING);
861             }
862         }
863     }
864
865     lock_ret = pthread_mutex_unlock(&all_threads_lock);
866     gc_assert(lock_ret == 0);
867 #ifdef LOCK_CREATE_THREAD
868     lock_ret = pthread_mutex_unlock(&create_thread_lock);
869     gc_assert(lock_ret == 0);
870 #endif
871
872     FSHOW_SIGNAL((stderr,"/gc_start_the_world:end\n"));
873 }
874
875 #endif /* !LISP_FEATURE_SB_SAFEPOINT */
876 #endif /* !LISP_FEATURE_SB_THREAD */
877
878 int
879 thread_yield()
880 {
881 #ifdef LISP_FEATURE_SB_THREAD
882     return sched_yield();
883 #else
884     return 0;
885 #endif
886 }
887
888 int
889 wake_thread(os_thread_t os_thread)
890 {
891 #if defined(LISP_FEATURE_WIN32)
892     return kill_safely(os_thread, 1);
893 #elif !defined(LISP_FEATURE_SB_THRUPTION)
894     return kill_safely(os_thread, SIGPIPE);
895 #else
896     return wake_thread_posix(os_thread);
897 #endif
898 }
899
900 /* If the thread id given does not belong to a running thread (it has
901  * exited or never even existed) pthread_kill _may_ fail with ESRCH,
902  * but it is also allowed to just segfault, see
903  * <http://udrepper.livejournal.com/16844.html>.
904  *
905  * Relying on thread ids can easily backfire since ids are recycled
906  * (NPTL recycles them extremely fast) so a signal can be sent to
907  * another process if the one it was sent to exited.
908  *
909  * For these reasons, we must make sure that the thread is still alive
910  * when the pthread_kill is called and return if the thread is
911  * exiting.
912  *
913  * Note (DFL, 2011-06-22): At the time of writing, this function is only
914  * used for INTERRUPT-THREAD, hence the wake_thread special-case for
915  * Windows is OK. */
916 int
917 kill_safely(os_thread_t os_thread, int signal)
918 {
919     FSHOW_SIGNAL((stderr,"/kill_safely: %lu, %d\n", os_thread, signal));
920     {
921 #ifdef LISP_FEATURE_SB_THREAD
922         sigset_t oldset;
923         struct thread *thread;
924         /* Frequent special case: resignalling to self.  The idea is
925          * that leave_region safepoint will acknowledge the signal, so
926          * there is no need to take locks, roll thread to safepoint
927          * etc. */
928         /* Kludge (on safepoint builds): At the moment, this isn't just
929          * an optimization; rather it masks the fact that
930          * gc_stop_the_world() grabs the all_threads mutex without
931          * releasing it, and since we're not using recursive pthread
932          * mutexes, the pthread_mutex_lock() around the all_threads loop
933          * would go wrong.  Why are we running interruptions while
934          * stopping the world though?  Test case is (:ASYNC-UNWIND
935          * :SPECIALS), especially with s/10/100/ in both loops. */
936         if (os_thread == pthread_self()) {
937             pthread_kill(os_thread, signal);
938 #ifdef LISP_FEATURE_WIN32
939             check_pending_thruptions(NULL);
940 #endif
941             return 0;
942         }
943
944         /* pthread_kill is not async signal safe and we don't want to be
945          * interrupted while holding the lock. */
946         block_deferrable_signals(0, &oldset);
947         pthread_mutex_lock(&all_threads_lock);
948         for (thread = all_threads; thread; thread = thread->next) {
949             if (thread->os_thread == os_thread) {
950                 int status = pthread_kill(os_thread, signal);
951                 if (status)
952                     lose("kill_safely: pthread_kill failed with %d\n", status);
953 #if defined(LISP_FEATURE_WIN32) && defined(LISP_FEATURE_SB_THRUPTION)
954                 wake_thread_win32(thread);
955 #endif
956                 break;
957             }
958         }
959         pthread_mutex_unlock(&all_threads_lock);
960         thread_sigmask(SIG_SETMASK,&oldset,0);
961         if (thread)
962             return 0;
963         else
964             return -1;
965 #elif defined(LISP_FEATURE_WIN32)
966         return 0;
967 #else
968         int status;
969         if (os_thread != 0)
970             lose("kill_safely: who do you want to kill? %d?\n", os_thread);
971         /* Dubious (as in don't know why it works) workaround for the
972          * signal sometimes not being generated on darwin. */
973 #ifdef LISP_FEATURE_DARWIN
974         {
975             sigset_t oldset;
976             sigprocmask(SIG_BLOCK, &deferrable_sigset, &oldset);
977             status = raise(signal);
978             sigprocmask(SIG_SETMASK,&oldset,0);
979         }
980 #else
981         status = raise(signal);
982 #endif
983         if (status == 0) {
984             return 0;
985         } else {
986             lose("cannot raise signal %d, %d %s\n",
987                  signal, status, strerror(errno));
988         }
989 #endif
990     }
991 }