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