10b4d4af3c9595df2f476591f633c7e2ddcc00a7
[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 void *
65 gc_general_alloc(long bytes, int page_type_flag, int quick_p) {
66     lispobj *new=new_space_free_pointer;
67     new_space_free_pointer+=(bytes/N_WORD_BYTES);
68     return new;
69 }
70
71 lispobj  copy_large_unboxed_object(lispobj object, long nwords) {
72     return copy_object(object,nwords);
73 }
74 lispobj  copy_unboxed_object(lispobj object, long nwords) {
75     return copy_object(object,nwords);
76 }
77 lispobj  copy_large_object(lispobj object, long nwords) {
78     return copy_object(object,nwords);
79 }
80
81 /* Note: The generic GC interface we're implementing passes us a
82  * last_generation argument. That's meaningless for us, since we're
83  * not a generational GC. So we ignore it. */
84 void
85 collect_garbage(generation_index_t ignore)
86 {
87 #ifdef PRINTNOISE
88     struct timeval start_tv, stop_tv;
89     struct rusage start_rusage, stop_rusage;
90     double real_time, system_time, user_time;
91     double percent_retained, gc_rate;
92     unsigned long size_discarded;
93 #endif
94     unsigned long size_retained;
95     lispobj *current_static_space_free_pointer;
96     unsigned long static_space_size;
97     unsigned long control_stack_size, binding_stack_size;
98     sigset_t tmp, old;
99     struct thread *th=arch_os_get_current_thread();
100
101 #ifdef PRINTNOISE
102     printf("[Collecting garbage ... \n");
103
104     getrusage(RUSAGE_SELF, &start_rusage);
105     gettimeofday(&start_tv, (struct timezone *) 0);
106 #endif
107
108     /* it's possible that signals are blocked already if this was called
109      * from a signal handler (e.g. with the sigsegv gc_trigger stuff) */
110     block_blockable_signals(0, &old);
111
112     current_static_space_free_pointer =
113         (lispobj *) ((unsigned long)
114                      SymbolValue(STATIC_SPACE_FREE_POINTER,0));
115
116
117     /* Set up from space and new space pointers. */
118
119     from_space = current_dynamic_space;
120     from_space_free_pointer = dynamic_space_free_pointer;
121
122 #ifdef PRINTNOISE
123     fprintf(stderr,"from_space = %lx\n",
124             (unsigned long) current_dynamic_space);
125 #endif
126     if (current_dynamic_space == (lispobj *) DYNAMIC_0_SPACE_START)
127         new_space = (lispobj *)DYNAMIC_1_SPACE_START;
128     else if (current_dynamic_space == (lispobj *) DYNAMIC_1_SPACE_START)
129         new_space = (lispobj *) DYNAMIC_0_SPACE_START;
130     else {
131         lose("GC lossage.  Current dynamic space is bogus!\n");
132     }
133     new_space_free_pointer = new_space;
134
135     /* Initialize the weak pointer list. */
136     weak_pointers = (struct weak_pointer *) NULL;
137
138
139     /* Scavenge all of the roots. */
140 #ifdef PRINTNOISE
141     printf("Scavenging interrupt contexts ...\n");
142 #endif
143     scavenge_interrupt_contexts(th);
144
145 #ifdef PRINTNOISE
146     printf("Scavenging interrupt handlers (%d bytes) ...\n",
147            (int)sizeof(interrupt_handlers));
148 #endif
149     scavenge((lispobj *) interrupt_handlers,
150              sizeof(interrupt_handlers) / sizeof(lispobj));
151
152     /* _size quantities are in units of sizeof(lispobj) - i.e. 4 */
153     control_stack_size =
154         current_control_stack_pointer-
155         (lispobj *)th->control_stack_start;
156 #ifdef PRINTNOISE
157     printf("Scavenging the control stack at %p (%ld words) ...\n",
158            ((lispobj *)th->control_stack_start),
159            control_stack_size);
160 #endif
161     scavenge(((lispobj *)th->control_stack_start), control_stack_size);
162
163
164     binding_stack_size =
165         current_binding_stack_pointer -
166         (lispobj *)th->binding_stack_start;
167 #ifdef PRINTNOISE
168     printf("Scavenging the binding stack %x - %x (%d words) ...\n",
169            th->binding_stack_start,current_binding_stack_pointer,
170            (int)(binding_stack_size));
171 #endif
172     scavenge(((lispobj *)th->binding_stack_start), binding_stack_size);
173
174     static_space_size =
175         current_static_space_free_pointer - (lispobj *) STATIC_SPACE_START;
176 #ifdef PRINTNOISE
177     printf("Scavenging static space %x - %x (%d words) ...\n",
178            STATIC_SPACE_START,current_static_space_free_pointer,
179            (int)(static_space_size));
180 #endif
181     scavenge(((lispobj *)STATIC_SPACE_START), static_space_size);
182
183     /* Scavenge newspace. */
184 #ifdef PRINTNOISE
185     printf("Scavenging new space (%d bytes) ...\n",
186            (int)((new_space_free_pointer - new_space) * sizeof(lispobj)));
187 #endif
188     scavenge_newspace();
189
190
191 #if defined(DEBUG_PRINT_GARBAGE)
192     print_garbage(from_space, from_space_free_pointer);
193 #endif
194
195     /* Scan the weak pointers. */
196 #ifdef PRINTNOISE
197     printf("Scanning weak hash tables ...\n");
198 #endif
199     scan_weak_hash_tables();
200
201     /* Scan the weak pointers. */
202 #ifdef PRINTNOISE
203     printf("Scanning weak pointers ...\n");
204 #endif
205     scan_weak_pointers();
206
207     /* Flip spaces. */
208 #ifdef PRINTNOISE
209     printf("Flipping spaces ...\n");
210 #endif
211
212     /* Maybe FIXME: it's possible that we could significantly reduce
213      * RSS by zeroing the from_space or madvise(MADV_DONTNEED) or
214      * similar os-dependent tricks here */
215 #ifdef LISP_FEATURE_HPUX
216     /* hpux cant handle unmapping areas that are not 100% mapped */
217     clear_auto_gc_trigger();
218 #endif
219     os_zero((os_vm_address_t) from_space,
220             (os_vm_size_t) dynamic_space_size);
221
222     current_dynamic_space = new_space;
223     dynamic_space_free_pointer = new_space_free_pointer;
224
225 #ifdef PRINTNOISE
226     size_discarded = (from_space_free_pointer - from_space) * sizeof(lispobj);
227 #endif
228     size_retained = (new_space_free_pointer - new_space) * sizeof(lispobj);
229
230     os_flush_icache((os_vm_address_t)new_space, size_retained);
231
232     /* Zero stack. */
233 #ifdef PRINTNOISE
234     printf("Zeroing empty part of control stack ...\n");
235 #endif
236     scrub_control_stack();
237     set_auto_gc_trigger(size_retained+bytes_consed_between_gcs);
238     thread_sigmask(SIG_SETMASK, &old, 0);
239
240
241 #ifdef PRINTNOISE
242     gettimeofday(&stop_tv, (struct timezone *) 0);
243     getrusage(RUSAGE_SELF, &stop_rusage);
244
245     printf("done.]\n");
246
247     percent_retained = (((float) size_retained) /
248                         ((float) size_discarded)) * 100.0;
249
250     printf("Total of %ld bytes out of %ld bytes retained (%3.2f%%).\n",
251            size_retained, size_discarded, percent_retained);
252
253     real_time = tv_diff(&stop_tv, &start_tv);
254     user_time = tv_diff(&stop_rusage.ru_utime, &start_rusage.ru_utime);
255     system_time = tv_diff(&stop_rusage.ru_stime, &start_rusage.ru_stime);
256
257     printf("Statistics: %10.2fs real, %10.2fs user, %10.2fs system.\n",
258            real_time, user_time, system_time);
259
260     gc_rate = ((float) size_retained / (float) (1<<20)) / real_time;
261
262     printf("%10.2f M bytes/sec collected.\n", gc_rate);
263 #endif
264 }
265
266 \f
267 /* scavenging */
268
269 static void
270 scavenge_newspace(void)
271 {
272     lispobj *here, *next;
273
274     here = new_space;
275     while (here < new_space_free_pointer) {
276         /*      printf("here=%lx, new_space_free_pointer=%lx\n",
277                 here,new_space_free_pointer); */
278         next = new_space_free_pointer;
279         scavenge(here, next - here);
280         scav_weak_hash_tables();
281         here = next;
282     }
283     /* printf("done with newspace\n"); */
284 }
285 \f
286 /* debugging code */
287
288 void
289 print_garbage(lispobj *from_space, lispobj *from_space_free_pointer)
290 {
291     lispobj *start;
292     int total_words_not_copied;
293
294     printf("Scanning from space ...\n");
295
296     total_words_not_copied = 0;
297     start = from_space;
298     while (start < from_space_free_pointer) {
299         lispobj object;
300         int forwardp, type, nwords;
301         lispobj header;
302
303         object = *start;
304         forwardp = is_lisp_pointer(object) && new_space_p(object);
305
306         if (forwardp) {
307             int tag;
308             lispobj *pointer;
309
310             tag = lowtag_of(object);
311
312             switch (tag) {
313             case LIST_POINTER_LOWTAG:
314                 nwords = 2;
315                 break;
316             case INSTANCE_POINTER_LOWTAG:
317                 printf("Don't know about instances yet!\n");
318                 nwords = 1;
319                 break;
320             case FUN_POINTER_LOWTAG:
321                 nwords = 1;
322                 break;
323             case OTHER_POINTER_LOWTAG:
324                 pointer = (lispobj *) native_pointer(object);
325                 header = *pointer;
326                 type = widetag_of(header);
327                 nwords = (sizetab[type])(pointer);
328                 break;
329             default: nwords=1;  /* shut yer whinging, gcc */
330             }
331         } else {
332             type = widetag_of(object);
333             nwords = (sizetab[type])(start);
334             total_words_not_copied += nwords;
335             printf("%4d words not copied at 0x%16lx; ",
336                    nwords, (unsigned long) start);
337             printf("Header word is 0x%08x\n",
338                    (unsigned int) object);
339         }
340         start += nwords;
341     }
342     printf("%d total words not copied.\n", total_words_not_copied);
343 }
344
345 \f
346 /* weak pointers */
347
348 #define WEAK_POINTER_NWORDS \
349         CEILING((sizeof(struct weak_pointer) / sizeof(lispobj)), 2)
350
351 static long
352 scav_weak_pointer(lispobj *where, lispobj object)
353 {
354     /* Do not let GC scavenge the value slot of the weak pointer */
355     /* (that is why it is a weak pointer).  Note:  we could use */
356     /* the scav_unboxed method here. */
357
358     return WEAK_POINTER_NWORDS;
359 }
360 \f
361 lispobj *
362 search_read_only_space(void *pointer)
363 {
364     lispobj* start = (lispobj*)READ_ONLY_SPACE_START;
365     lispobj* end = (lispobj*)SymbolValue(READ_ONLY_SPACE_FREE_POINTER,0);
366     if ((pointer < (void *)start) || (pointer >= (void *)end))
367         return NULL;
368     return (gc_search_space(start,
369                             (((lispobj *)pointer)+2)-start,
370                             (lispobj *)pointer));
371 }
372
373 lispobj *
374 search_static_space(void *pointer)
375 {
376     lispobj* start = (lispobj*)STATIC_SPACE_START;
377     lispobj* end = (lispobj*)SymbolValue(STATIC_SPACE_FREE_POINTER,0);
378     if ((pointer < (void *)start) || (pointer >= (void *)end))
379         return NULL;
380     return (gc_search_space(start,
381                             (((lispobj *)pointer)+2)-start,
382                             (lispobj *)pointer));
383 }
384
385 lispobj *
386 search_dynamic_space(void *pointer)
387 {
388     lispobj *start = (lispobj *) current_dynamic_space;
389     lispobj *end = (lispobj *) dynamic_space_free_pointer;
390     if ((pointer < (void *)start) || (pointer >= (void *)end))
391         return NULL;
392     return (gc_search_space(start,
393                             (((lispobj *)pointer)+2)-start,
394                             (lispobj *)pointer));
395 }
396 \f
397 /* initialization.  if gc_init can be moved to after core load, we could
398  * combine these two functions */
399
400 void
401 gc_init(void)
402 {
403     gc_init_tables();
404     scavtab[WEAK_POINTER_WIDETAG] = scav_weak_pointer;
405 }
406
407 void
408 gc_initialize_pointers(void)
409 {
410     /* FIXME: We do nothing here.  We (briefly) misguidedly attempted
411        to set current_dynamic_space to DYNAMIC_0_SPACE_START here,
412        forgetting that (a) actually it could be the other and (b) it's
413        set in coreparse.c anyway.  There's a FIXME note left here to
414        note that current_dynamic_space is a violation of OAOO: we can
415        tell which dynamic space we're currently in by looking at
416        dynamic_space_free_pointer.  -- CSR, 2002-08-09 */
417 }
418
419
420
421 \f
422 /* noise to manipulate the gc trigger stuff */
423
424 /* Functions that substantially change the dynamic space free pointer
425  * (collect_garbage, purify) are responsible also for resetting the
426  * auto_gc_trigger */
427 void set_auto_gc_trigger(os_vm_size_t dynamic_usage)
428 {
429     os_vm_address_t addr;
430     os_vm_size_t length;
431
432     addr = os_round_up_to_page((os_vm_address_t)current_dynamic_space
433                                + dynamic_usage);
434     if (addr < (os_vm_address_t)dynamic_space_free_pointer)
435         lose("set_auto_gc_trigger: tried to set gc trigger too low! (%ld < 0x%08lx)\n",
436              (unsigned long)dynamic_usage,
437              (unsigned long)((os_vm_address_t)dynamic_space_free_pointer
438                              - (os_vm_address_t)current_dynamic_space));
439
440     length = os_trunc_size_to_page(dynamic_space_size - dynamic_usage);
441     if (length < 0)
442         lose("set_auto_gc_trigger: tried to set gc trigger too high! (0x%08lx)\n",
443              (unsigned long)dynamic_usage);
444
445 #if defined(SUNOS) || defined(SOLARIS) || defined(LISP_FEATURE_HPUX)
446     os_invalidate(addr, length);
447 #else
448     os_protect(addr, length, 0);
449 #endif
450
451     current_auto_gc_trigger = (lispobj *)addr;
452 }
453
454 void clear_auto_gc_trigger(void)
455 {
456     os_vm_address_t addr;
457     os_vm_size_t length;
458
459     if (current_auto_gc_trigger == NULL)
460         return;
461
462     addr = (os_vm_address_t)current_auto_gc_trigger;
463     length = dynamic_space_size + (os_vm_address_t)current_dynamic_space - addr;
464
465 #if defined(SUNOS) || defined(SOLARIS) || defined(LISP_FEATURE_HPUX)
466     /* don't want to force whole space into swapping mode... */
467     os_validate(addr, length);
468 #else
469     os_protect(addr, length, OS_VM_PROT_ALL);
470 #endif
471
472     current_auto_gc_trigger = NULL;
473 }
474
475 static boolean
476 gc_trigger_hit(void *addr)
477 {
478     if (current_auto_gc_trigger == NULL)
479         return 0;
480     else{
481         return (addr >= (void *)current_auto_gc_trigger &&
482                 addr <((void *)current_dynamic_space + dynamic_space_size));
483     }
484 }
485
486 boolean
487 cheneygc_handle_wp_violation(os_context_t *context, void *addr)
488 {
489     if(!foreign_function_call_active && gc_trigger_hit(addr)){
490         struct thread *thread=arch_os_get_current_thread();
491         clear_auto_gc_trigger();
492         /* Don't flood the system with interrupts if the need to gc is
493          * already noted. This can happen for example when SUB-GC
494          * allocates or after a gc triggered in a WITHOUT-GCING. */
495         if (SymbolValue(GC_PENDING,thread) == NIL) {
496             if (SymbolValue(GC_INHIBIT,thread) == NIL) {
497                 if (arch_pseudo_atomic_atomic(context)) {
498                     /* set things up so that GC happens when we finish
499                      * the PA section */
500                     SetSymbolValue(GC_PENDING,T,thread);
501                     arch_set_pseudo_atomic_interrupted(context);
502                     maybe_save_gc_mask_and_block_deferrables
503                         (os_context_sigmask_addr(context));
504                 } else {
505                     maybe_gc(context);
506                 }
507             } else {
508                 SetSymbolValue(GC_PENDING,T,thread);
509             }
510         }
511         return 1;
512     }
513     return 0;
514 }