1.0.26.15: interrupt.c refactoring
[sbcl.git] / src / runtime / cheneygc.c
1 /*
2  * stop and copy GC based on Cheney's algorithm
3  */
4
5 /*
6  * This software is part of the SBCL system. See the README file for
7  * more information.
8  *
9  * This software is derived from the CMU CL system, which was
10  * written at Carnegie Mellon University and released into the
11  * public domain. The software is in the public domain and is
12  * provided with absolutely no warranty. See the COPYING and CREDITS
13  * files for more information.
14  */
15
16 #include <stdio.h>
17 #include <sys/time.h>
18 #include <sys/resource.h>
19 #include <signal.h>
20 #include "sbcl.h"
21 #include "runtime.h"
22 #include "os.h"
23 #include "gc.h"
24 #include "gc-internal.h"
25 #include "globals.h"
26 #include "interrupt.h"
27 #include "validate.h"
28 #include "lispregs.h"
29 #include "interr.h"
30 #include "genesis/static-symbols.h"
31 #include "genesis/primitive-objects.h"
32 #include "thread.h"
33 #include "arch.h"
34
35 /* So you need to debug? */
36 #if 0
37 #define PRINTNOISE
38 #define DEBUG_SPACE_PREDICATES
39 #define DEBUG_SCAVENGE_VERBOSE
40 #define DEBUG_COPY_VERBOSE
41 #define DEBUG_CODE_GC
42 #endif
43
44 lispobj *from_space;
45 lispobj *from_space_free_pointer;
46
47 lispobj *new_space;
48 lispobj *new_space_free_pointer;
49
50 static void scavenge_newspace(void);
51
52 \f
53 /* collecting garbage */
54
55 #ifdef PRINTNOISE
56 static double
57 tv_diff(struct timeval *x, struct timeval *y)
58 {
59     return (((double) x->tv_sec + (double) x->tv_usec * 1.0e-6) -
60             ((double) y->tv_sec + (double) y->tv_usec * 1.0e-6));
61 }
62 #endif
63
64 #define BYTES_ZERO_BEFORE_END (1<<12)
65
66 /* FIXME do we need this?  Doesn't it duplicate lisp code in
67  * scrub-control-stack? */
68
69 static void
70 zero_stack(void)
71 {
72     lispobj *ptr = current_control_stack_pointer;
73  search:
74     do {
75         if (*ptr)
76             goto fill;
77         ptr++;
78     } while (((unsigned long)ptr) & (BYTES_ZERO_BEFORE_END-1));
79     return;
80  fill:
81     do {
82         *ptr++ = 0;
83     } while (((unsigned long)ptr) & (BYTES_ZERO_BEFORE_END-1));
84
85     goto search;
86 }
87
88
89 void *
90 gc_general_alloc(long bytes, int page_type_flag, int quick_p) {
91     lispobj *new=new_space_free_pointer;
92     new_space_free_pointer+=(bytes/N_WORD_BYTES);
93     return new;
94 }
95
96 lispobj  copy_large_unboxed_object(lispobj object, long nwords) {
97     return copy_object(object,nwords);
98 }
99 lispobj  copy_unboxed_object(lispobj object, long nwords) {
100     return copy_object(object,nwords);
101 }
102 lispobj  copy_large_object(lispobj object, long nwords) {
103     return copy_object(object,nwords);
104 }
105
106 /* Note: The generic GC interface we're implementing passes us a
107  * last_generation argument. That's meaningless for us, since we're
108  * not a generational GC. So we ignore it. */
109 void
110 collect_garbage(generation_index_t ignore)
111 {
112 #ifdef PRINTNOISE
113     struct timeval start_tv, stop_tv;
114     struct rusage start_rusage, stop_rusage;
115     double real_time, system_time, user_time;
116     double percent_retained, gc_rate;
117     unsigned long size_discarded;
118 #endif
119     unsigned long size_retained;
120     lispobj *current_static_space_free_pointer;
121     unsigned long static_space_size;
122     unsigned long control_stack_size, binding_stack_size;
123     sigset_t tmp, old;
124     struct thread *th=arch_os_get_current_thread();
125
126 #ifdef PRINTNOISE
127     printf("[Collecting garbage ... \n");
128
129     getrusage(RUSAGE_SELF, &start_rusage);
130     gettimeofday(&start_tv, (struct timezone *) 0);
131 #endif
132
133     /* it's possible that signals are blocked already if this was called
134      * from a signal handler (e.g. with the sigsegv gc_trigger stuff) */
135     block_blockable_signals(0, &old);
136
137     current_static_space_free_pointer =
138         (lispobj *) ((unsigned long)
139                      SymbolValue(STATIC_SPACE_FREE_POINTER,0));
140
141
142     /* Set up from space and new space pointers. */
143
144     from_space = current_dynamic_space;
145     from_space_free_pointer = dynamic_space_free_pointer;
146
147 #ifdef PRINTNOISE
148     fprintf(stderr,"from_space = %lx\n",
149             (unsigned long) current_dynamic_space);
150 #endif
151     if (current_dynamic_space == (lispobj *) DYNAMIC_0_SPACE_START)
152         new_space = (lispobj *)DYNAMIC_1_SPACE_START;
153     else if (current_dynamic_space == (lispobj *) DYNAMIC_1_SPACE_START)
154         new_space = (lispobj *) DYNAMIC_0_SPACE_START;
155     else {
156         lose("GC lossage.  Current dynamic space is bogus!\n");
157     }
158     new_space_free_pointer = new_space;
159
160     /* Initialize the weak pointer list. */
161     weak_pointers = (struct weak_pointer *) NULL;
162
163
164     /* Scavenge all of the roots. */
165 #ifdef PRINTNOISE
166     printf("Scavenging interrupt contexts ...\n");
167 #endif
168     scavenge_interrupt_contexts();
169
170 #ifdef PRINTNOISE
171     printf("Scavenging interrupt handlers (%d bytes) ...\n",
172            (int)sizeof(interrupt_handlers));
173 #endif
174     scavenge((lispobj *) interrupt_handlers,
175              sizeof(interrupt_handlers) / sizeof(lispobj));
176
177     /* _size quantities are in units of sizeof(lispobj) - i.e. 4 */
178     control_stack_size =
179         current_control_stack_pointer-
180         (lispobj *)th->control_stack_start;
181 #ifdef PRINTNOISE
182     printf("Scavenging the control stack at %p (%ld words) ...\n",
183            ((lispobj *)th->control_stack_start),
184            control_stack_size);
185 #endif
186     scavenge(((lispobj *)th->control_stack_start), control_stack_size);
187
188
189     binding_stack_size =
190         current_binding_stack_pointer -
191         (lispobj *)th->binding_stack_start;
192 #ifdef PRINTNOISE
193     printf("Scavenging the binding stack %x - %x (%d words) ...\n",
194            th->binding_stack_start,current_binding_stack_pointer,
195            (int)(binding_stack_size));
196 #endif
197     scavenge(((lispobj *)th->binding_stack_start), binding_stack_size);
198
199     static_space_size =
200         current_static_space_free_pointer - (lispobj *) STATIC_SPACE_START;
201 #ifdef PRINTNOISE
202     printf("Scavenging static space %x - %x (%d words) ...\n",
203            STATIC_SPACE_START,current_static_space_free_pointer,
204            (int)(static_space_size));
205 #endif
206     scavenge(((lispobj *)STATIC_SPACE_START), static_space_size);
207
208     /* Scavenge newspace. */
209 #ifdef PRINTNOISE
210     printf("Scavenging new space (%d bytes) ...\n",
211            (int)((new_space_free_pointer - new_space) * sizeof(lispobj)));
212 #endif
213     scavenge_newspace();
214
215
216 #if defined(DEBUG_PRINT_GARBAGE)
217     print_garbage(from_space, from_space_free_pointer);
218 #endif
219
220     /* Scan the weak pointers. */
221 #ifdef PRINTNOISE
222     printf("Scanning weak hash tables ...\n");
223 #endif
224     scan_weak_hash_tables();
225
226     /* Scan the weak pointers. */
227 #ifdef PRINTNOISE
228     printf("Scanning weak pointers ...\n");
229 #endif
230     scan_weak_pointers();
231
232     /* Flip spaces. */
233 #ifdef PRINTNOISE
234     printf("Flipping spaces ...\n");
235 #endif
236
237     /* Maybe FIXME: it's possible that we could significantly reduce
238      * RSS by zeroing the from_space or madvise(MADV_DONTNEED) or
239      * similar os-dependent tricks here */
240 #ifdef LISP_FEATURE_HPUX
241     /* hpux cant handle unmapping areas that are not 100% mapped */
242     clear_auto_gc_trigger();
243 #endif
244     os_zero((os_vm_address_t) from_space,
245             (os_vm_size_t) dynamic_space_size);
246
247     current_dynamic_space = new_space;
248     dynamic_space_free_pointer = new_space_free_pointer;
249
250 #ifdef PRINTNOISE
251     size_discarded = (from_space_free_pointer - from_space) * sizeof(lispobj);
252 #endif
253     size_retained = (new_space_free_pointer - new_space) * sizeof(lispobj);
254
255     os_flush_icache((os_vm_address_t)new_space, size_retained);
256
257     /* Zero stack. */
258 #ifdef PRINTNOISE
259     printf("Zeroing empty part of control stack ...\n");
260 #endif
261     zero_stack();
262     set_auto_gc_trigger(size_retained+bytes_consed_between_gcs);
263     thread_sigmask(SIG_SETMASK, &old, 0);
264
265
266 #ifdef PRINTNOISE
267     gettimeofday(&stop_tv, (struct timezone *) 0);
268     getrusage(RUSAGE_SELF, &stop_rusage);
269
270     printf("done.]\n");
271
272     percent_retained = (((float) size_retained) /
273                         ((float) size_discarded)) * 100.0;
274
275     printf("Total of %ld bytes out of %ld bytes retained (%3.2f%%).\n",
276            size_retained, size_discarded, percent_retained);
277
278     real_time = tv_diff(&stop_tv, &start_tv);
279     user_time = tv_diff(&stop_rusage.ru_utime, &start_rusage.ru_utime);
280     system_time = tv_diff(&stop_rusage.ru_stime, &start_rusage.ru_stime);
281
282     printf("Statistics: %10.2fs real, %10.2fs user, %10.2fs system.\n",
283            real_time, user_time, system_time);
284
285     gc_rate = ((float) size_retained / (float) (1<<20)) / real_time;
286
287     printf("%10.2f M bytes/sec collected.\n", gc_rate);
288 #endif
289 }
290
291 \f
292 /* scavenging */
293
294 static void
295 scavenge_newspace(void)
296 {
297     lispobj *here, *next;
298
299     here = new_space;
300     while (here < new_space_free_pointer) {
301         /*      printf("here=%lx, new_space_free_pointer=%lx\n",
302                 here,new_space_free_pointer); */
303         next = new_space_free_pointer;
304         scavenge(here, next - here);
305         scav_weak_hash_tables();
306         here = next;
307     }
308     /* printf("done with newspace\n"); */
309 }
310 \f
311 /* scavenging interrupt contexts */
312
313 static int boxed_registers[] = BOXED_REGISTERS;
314
315 static void
316 scavenge_interrupt_context(os_context_t *context)
317 {
318     int i;
319 #ifdef reg_LIP
320     unsigned long lip;
321     unsigned long lip_offset;
322     int lip_register_pair;
323 #endif
324     unsigned long pc_code_offset;
325 #ifdef ARCH_HAS_LINK_REGISTER
326     unsigned long lr_code_offset;
327 #endif
328 #ifdef ARCH_HAS_NPC_REGISTER
329     unsigned long npc_code_offset;
330 #endif
331 #ifdef DEBUG_SCAVENGE_VERBOSE
332     fprintf(stderr, "Scavenging interrupt context at 0x%x\n",context);
333 #endif
334     /* Find the LIP's register pair and calculate its offset */
335     /* before we scavenge the context. */
336 #ifdef reg_LIP
337     lip = *os_context_register_addr(context, reg_LIP);
338     /* 0x7FFFFFFF on 32-bit platforms;
339        0x7FFFFFFFFFFFFFFF on 64-bit platforms */
340     lip_offset = (((unsigned long)1) << (N_WORD_BITS - 1)) - 1;
341     lip_register_pair = -1;
342     for (i = 0; i < (int)(sizeof(boxed_registers) / sizeof(int)); i++) {
343         unsigned long reg;
344         unsigned long offset;
345         int index;
346
347         index = boxed_registers[i];
348         reg = *os_context_register_addr(context, index);
349         /* would be using PTR if not for integer length issues */
350         if ((reg & ~((1L<<N_LOWTAG_BITS)-1)) <= lip) {
351             offset = lip - reg;
352             if (offset < lip_offset) {
353                 lip_offset = offset;
354                 lip_register_pair = index;
355             }
356         }
357     }
358 #endif /* reg_LIP */
359
360     /* Compute the PC's offset from the start of the CODE */
361     /* register. */
362     pc_code_offset =
363         *os_context_pc_addr(context) -
364         *os_context_register_addr(context, reg_CODE);
365 #ifdef ARCH_HAS_NPC_REGISTER
366     npc_code_offset =
367         *os_context_npc_addr(context) -
368         *os_context_register_addr(context, reg_CODE);
369 #endif
370 #ifdef ARCH_HAS_LINK_REGISTER
371     lr_code_offset =
372         *os_context_lr_addr(context) -
373         *os_context_register_addr(context, reg_CODE);
374 #endif
375
376     /* Scavenge all boxed registers in the context. */
377     for (i = 0; i < (int)(sizeof(boxed_registers) / sizeof(int)); i++) {
378         int index;
379         lispobj foo;
380
381         index = boxed_registers[i];
382         foo = *os_context_register_addr(context,index);
383         scavenge((lispobj *) &foo, 1);
384         *os_context_register_addr(context,index) = foo;
385
386         /* this is unlikely to work as intended on bigendian
387          * 64 bit platforms */
388
389         scavenge((lispobj *)
390                  os_context_register_addr(context, index), 1);
391     }
392
393 #ifdef reg_LIP
394     /* Fix the LIP */
395     *os_context_register_addr(context, reg_LIP) =
396         *os_context_register_addr(context, lip_register_pair) + lip_offset;
397 #endif /* reg_LIP */
398
399     /* Fix the PC if it was in from space */
400     if (from_space_p(*os_context_pc_addr(context)))
401         *os_context_pc_addr(context) =
402             *os_context_register_addr(context, reg_CODE) + pc_code_offset;
403 #ifdef ARCH_HAS_LINK_REGISTER
404     /* Fix the LR ditto; important if we're being called from
405      * an assembly routine that expects to return using blr, otherwise
406      * harmless */
407     if (from_space_p(*os_context_lr_addr(context)))
408         *os_context_lr_addr(context) =
409             *os_context_register_addr(context, reg_CODE) + lr_code_offset;
410 #endif
411
412 #ifdef ARCH_HAS_NPC_REGISTER
413     if (from_space_p(*os_context_npc_addr(context)))
414         *os_context_npc_addr(context) =
415             *os_context_register_addr(context, reg_CODE) + npc_code_offset;
416 #endif
417 }
418
419 void scavenge_interrupt_contexts(void)
420 {
421     int i, index;
422     os_context_t *context;
423
424     struct thread *th=arch_os_get_current_thread();
425
426     index = fixnum_value(SymbolValue(FREE_INTERRUPT_CONTEXT_INDEX,0));
427
428
429 #ifdef DEBUG_SCAVENGE_VERBOSE
430     fprintf(stderr, "%d interrupt contexts to scan\n",index);
431 #endif
432     for (i = 0; i < index; i++) {
433         context = th->interrupt_contexts[i];
434         scavenge_interrupt_context(context);
435     }
436 }
437
438 \f
439 /* debugging code */
440
441 void
442 print_garbage(lispobj *from_space, lispobj *from_space_free_pointer)
443 {
444     lispobj *start;
445     int total_words_not_copied;
446
447     printf("Scanning from space ...\n");
448
449     total_words_not_copied = 0;
450     start = from_space;
451     while (start < from_space_free_pointer) {
452         lispobj object;
453         int forwardp, type, nwords;
454         lispobj header;
455
456         object = *start;
457         forwardp = is_lisp_pointer(object) && new_space_p(object);
458
459         if (forwardp) {
460             int tag;
461             lispobj *pointer;
462
463             tag = lowtag_of(object);
464
465             switch (tag) {
466             case LIST_POINTER_LOWTAG:
467                 nwords = 2;
468                 break;
469             case INSTANCE_POINTER_LOWTAG:
470                 printf("Don't know about instances yet!\n");
471                 nwords = 1;
472                 break;
473             case FUN_POINTER_LOWTAG:
474                 nwords = 1;
475                 break;
476             case OTHER_POINTER_LOWTAG:
477                 pointer = (lispobj *) native_pointer(object);
478                 header = *pointer;
479                 type = widetag_of(header);
480                 nwords = (sizetab[type])(pointer);
481                 break;
482             default: nwords=1;  /* shut yer whinging, gcc */
483             }
484         } else {
485             type = widetag_of(object);
486             nwords = (sizetab[type])(start);
487             total_words_not_copied += nwords;
488             printf("%4d words not copied at 0x%16lx; ",
489                    nwords, (unsigned long) start);
490             printf("Header word is 0x%08x\n",
491                    (unsigned int) object);
492         }
493         start += nwords;
494     }
495     printf("%d total words not copied.\n", total_words_not_copied);
496 }
497
498 \f
499 /* weak pointers */
500
501 #define WEAK_POINTER_NWORDS \
502         CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
503
504 static long
505 scav_weak_pointer(lispobj *where, lispobj object)
506 {
507     /* Do not let GC scavenge the value slot of the weak pointer */
508     /* (that is why it is a weak pointer).  Note:  we could use */
509     /* the scav_unboxed method here. */
510
511     return WEAK_POINTER_NWORDS;
512 }
513 \f
514 lispobj *
515 search_read_only_space(void *pointer)
516 {
517     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
518     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
519     if ((pointer < (void *)start) || (pointer >= (void *)end))
520         return NULL;
521     return (gc_search_space(start,
522                             (((lispobj *)pointer)+2)-start,
523                             (lispobj *)pointer));
524 }
525
526 lispobj *
527 search_static_space(void *pointer)
528 {
529     lispobj* start = (lispobj*)STATIC_SPACE_START;
530     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
531     if ((pointer < (void *)start) || (pointer >= (void *)end))
532         return NULL;
533     return (gc_search_space(start,
534                             (((lispobj *)pointer)+2)-start,
535                             (lispobj *)pointer));
536 }
537
538 lispobj *
539 search_dynamic_space(void *pointer)
540 {
541     lispobj *start = (lispobj *) current_dynamic_space;
542     lispobj *end = (lispobj *) dynamic_space_free_pointer;
543     if ((pointer < (void *)start) || (pointer >= (void *)end))
544         return NULL;
545     return (gc_search_space(start,
546                             (((lispobj *)pointer)+2)-start,
547                             (lispobj *)pointer));
548 }
549 \f
550 /* initialization.  if gc_init can be moved to after core load, we could
551  * combine these two functions */
552
553 void
554 gc_init(void)
555 {
556     gc_init_tables();
557     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
558 }
559
560 void
561 gc_initialize_pointers(void)
562 {
563     /* FIXME: We do nothing here.  We (briefly) misguidedly attempted
564        to set current_dynamic_space to DYNAMIC_0_SPACE_START here,
565        forgetting that (a) actually it could be the other and (b) it's
566        set in coreparse.c anyway.  There's a FIXME note left here to
567        note that current_dynamic_space is a violation of OAOO: we can
568        tell which dynamic space we're currently in by looking at
569        dynamic_space_free_pointer.  -- CSR, 2002-08-09 */
570 }
571
572
573
574 \f
575 /* noise to manipulate the gc trigger stuff */
576
577 /* Functions that substantially change the dynamic space free pointer
578  * (collect_garbage, purify) are responsible also for resetting the
579  * auto_gc_trigger */
580 void set_auto_gc_trigger(os_vm_size_t dynamic_usage)
581 {
582     os_vm_address_t addr;
583     os_vm_size_t length;
584
585     addr = os_round_up_to_page((os_vm_address_t)current_dynamic_space
586                                + dynamic_usage);
587     if (addr < (os_vm_address_t)dynamic_space_free_pointer)
588         lose("set_auto_gc_trigger: tried to set gc trigger too low! (%ld < 0x%08lx)\n",
589              (unsigned long)dynamic_usage,
590              (unsigned long)((os_vm_address_t)dynamic_space_free_pointer
591                              - (os_vm_address_t)current_dynamic_space));
592
593     length = os_trunc_size_to_page(dynamic_space_size - dynamic_usage);
594     if (length < 0)
595         lose("set_auto_gc_trigger: tried to set gc trigger too high! (0x%08lx)\n",
596              (unsigned long)dynamic_usage);
597
598 #if defined(SUNOS) || defined(SOLARIS) || defined(LISP_FEATURE_HPUX)
599     os_invalidate(addr, length);
600 #else
601     os_protect(addr, length, 0);
602 #endif
603
604     current_auto_gc_trigger = (lispobj *)addr;
605 }
606
607 void clear_auto_gc_trigger(void)
608 {
609     os_vm_address_t addr;
610     os_vm_size_t length;
611
612     if (current_auto_gc_trigger == NULL)
613         return;
614
615     addr = (os_vm_address_t)current_auto_gc_trigger;
616     length = dynamic_space_size + (os_vm_address_t)current_dynamic_space - addr;
617
618 #if defined(SUNOS) || defined(SOLARIS) || defined(LISP_FEATURE_HPUX)
619     /* don't want to force whole space into swapping mode... */
620     os_validate(addr, length);
621 #else
622     os_protect(addr, length, OS_VM_PROT_ALL);
623 #endif
624
625     current_auto_gc_trigger = NULL;
626 }
627
628 static boolean
629 gc_trigger_hit(void *addr)
630 {
631     if (current_auto_gc_trigger == NULL)
632         return 0;
633     else{
634         return (addr >= (void *)current_auto_gc_trigger &&
635                 addr <((void *)current_dynamic_space + dynamic_space_size));
636     }
637 }
638
639 boolean
640 cheneygc_handle_wp_violation(os_context_t *context, void *addr)
641 {
642     if(!foreign_function_call_active && gc_trigger_hit(addr)){
643         struct thread *thread=arch_os_get_current_thread();
644         clear_auto_gc_trigger();
645         /* Don't flood the system with interrupts if the need to gc is
646          * already noted. This can happen for example when SUB-GC
647          * allocates or after a gc triggered in a WITHOUT-GCING. */
648         if (SymbolValue(GC_PENDING,thread) == NIL) {
649             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
650                 if (arch_pseudo_atomic_atomic(context)) {
651                     /* set things up so that GC happens when we finish
652                      * the PA section */
653                     SetSymbolValue(GC_PENDING,T,thread);
654                     arch_set_pseudo_atomic_interrupted(context);
655                     maybe_save_gc_mask_and_block_deferrables
656                         (os_context_sigmask_addr(context));
657                 } else {
658                     maybe_gc(context);
659                 }
660             } else {
661                 SetSymbolValue(GC_PENDING,T,thread);
662             }
663         }
664         return 1;
665     }
666     return 0;
667 }