Fix omission bug: Add `heap_segment' forward decl
[bpt/guile.git] / libguile / gc.c
1 /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001 Free Software Foundation, Inc.
2 *
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2, or (at your option)
6 * any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License
14 * along with this software; see the file COPYING. If not, write to
15 * the Free Software Foundation, Inc., 59 Temple Place, Suite 330,
16 * Boston, MA 02111-1307 USA
17 *
18 * As a special exception, the Free Software Foundation gives permission
19 * for additional uses of the text contained in its release of GUILE.
20 *
21 * The exception is that, if you link the GUILE library with other files
22 * to produce an executable, this does not by itself cause the
23 * resulting executable to be covered by the GNU General Public License.
24 * Your use of that executable is in no way restricted on account of
25 * linking the GUILE library code into it.
26 *
27 * This exception does not however invalidate any other reasons why
28 * the executable file might be covered by the GNU General Public License.
29 *
30 * This exception applies only to the code released by the
31 * Free Software Foundation under the name GUILE. If you copy
32 * code from other Free Software Foundation releases into a copy of
33 * GUILE, as the General Public License permits, the exception does
34 * not apply to the code that you add in this way. To avoid misleading
35 * anyone as to the status of such modified files, you must delete
36 * this exception notice from them.
37 *
38 * If you write modifications of your own for GUILE, it is your choice
39 * whether to permit this exception to apply to your modifications.
40 * If you do not wish that, delete this exception notice. */
41
42
43 /* #define DEBUGINFO */
44
45 /* SECTION: This code is compiled once.
46 */
47
48 #ifndef MARK_DEPENDENCIES
49
50 \f
51 #include <stdio.h>
52 #include <errno.h>
53 #include <string.h>
54
55 #include "libguile/_scm.h"
56 #include "libguile/eval.h"
57 #include "libguile/stime.h"
58 #include "libguile/stackchk.h"
59 #include "libguile/struct.h"
60 #include "libguile/smob.h"
61 #include "libguile/unif.h"
62 #include "libguile/async.h"
63 #include "libguile/ports.h"
64 #include "libguile/root.h"
65 #include "libguile/strings.h"
66 #include "libguile/vectors.h"
67 #include "libguile/weaks.h"
68 #include "libguile/hashtab.h"
69 #include "libguile/tags.h"
70
71 #include "libguile/validate.h"
72 #include "libguile/deprecation.h"
73 #include "libguile/gc.h"
74
75 #ifdef GUILE_DEBUG_MALLOC
76 #include "libguile/debug-malloc.h"
77 #endif
78
79 #ifdef HAVE_MALLOC_H
80 #include <malloc.h>
81 #endif
82
83 #ifdef HAVE_UNISTD_H
84 #include <unistd.h>
85 #endif
86
87 #ifdef __STDC__
88 #include <stdarg.h>
89 #define var_start(x, y) va_start(x, y)
90 #else
91 #include <varargs.h>
92 #define var_start(x, y) va_start(x)
93 #endif
94
95 \f
96
97 unsigned int scm_gc_running_p = 0;
98
99 \f
100
101 #if (SCM_DEBUG_CELL_ACCESSES == 1)
102
103 scm_t_bits scm_tc16_allocated;
104
105 /* Set this to != 0 if every cell that is accessed shall be checked:
106 */
107 unsigned int scm_debug_cell_accesses_p = 1;
108
109 /* Set this to 0 if no additional gc's shall be performed, otherwise set it to
110 * the number of cell accesses after which a gc shall be called.
111 */
112 static unsigned int debug_cells_gc_interval = 0;
113
114
115 /* If an allocated cell is detected during garbage collection, this means that
116 * some code has just obtained the object but was preempted before the
117 * initialization of the object was completed. This meanst that some entries
118 * of the allocated cell may already contain SCM objects. Therefore,
119 * allocated cells are scanned conservatively. */
120 static SCM
121 allocated_mark (SCM allocated)
122 {
123 scm_gc_mark_cell_conservatively (allocated);
124 return SCM_BOOL_F;
125 }
126
127
128 /* Assert that the given object is a valid reference to a valid cell. This
129 * test involves to determine whether the object is a cell pointer, whether
130 * this pointer actually points into a heap segment and whether the cell
131 * pointed to is not a free cell. Further, additional garbage collections may
132 * get executed after a user defined number of cell accesses. This helps to
133 * find places in the C code where references are dropped for extremely short
134 * periods.
135 */
136 void
137 scm_assert_cell_valid (SCM cell)
138 {
139 static unsigned int already_running = 0;
140
141 if (scm_debug_cell_accesses_p && !already_running)
142 {
143 already_running = 1; /* set to avoid recursion */
144
145 if (!scm_cellp (cell))
146 {
147 fprintf (stderr, "scm_assert_cell_valid: Not a cell object: %lux\n",
148 (unsigned long) SCM_UNPACK (cell));
149 abort ();
150 }
151 else if (!scm_gc_running_p)
152 {
153 /* Dirk::FIXME:: During garbage collection there occur references to
154 free cells. This is allright during conservative marking, but
155 should not happen otherwise (I think). The case of free cells
156 accessed during conservative marking is handled in function
157 scm_mark_locations. However, there still occur accesses to free
158 cells during gc. I don't understand why this happens. If it is
159 a bug and gets fixed, the following test should also work while
160 gc is running.
161 */
162 if (SCM_FREE_CELL_P (cell))
163 {
164 fprintf (stderr, "scm_assert_cell_valid: Accessing free cell: %lux\n",
165 (unsigned long) SCM_UNPACK (cell));
166 abort ();
167 }
168
169 /* If desired, perform additional garbage collections after a user
170 * defined number of cell accesses.
171 */
172 if (debug_cells_gc_interval)
173 {
174 static unsigned int counter = 0;
175
176 if (counter != 0)
177 {
178 --counter;
179 }
180 else
181 {
182 counter = debug_cells_gc_interval;
183 scm_igc ("scm_assert_cell_valid");
184 }
185 }
186 }
187 already_running = 0; /* re-enable */
188 }
189 }
190
191
192 SCM_DEFINE (scm_set_debug_cell_accesses_x, "set-debug-cell-accesses!", 1, 0, 0,
193 (SCM flag),
194 "If @var{flag} is @code{#f}, cell access checking is disabled.\n"
195 "If @var{flag} is @code{#t}, cell access checking is enabled,\n"
196 "but no additional calls to garbage collection are issued.\n"
197 "If @var{flag} is a number, cell access checking is enabled,\n"
198 "with an additional garbage collection after the given\n"
199 "number of cell accesses.\n"
200 "This procedure only exists when the compile-time flag\n"
201 "@code{SCM_DEBUG_CELL_ACCESSES} was set to 1.")
202 #define FUNC_NAME s_scm_set_debug_cell_accesses_x
203 {
204 if (SCM_FALSEP (flag)) {
205 scm_debug_cell_accesses_p = 0;
206 } else if (SCM_EQ_P (flag, SCM_BOOL_T)) {
207 debug_cells_gc_interval = 0;
208 scm_debug_cell_accesses_p = 1;
209 } else if (SCM_INUMP (flag)) {
210 long int f = SCM_INUM (flag);
211 if (f <= 0) SCM_OUT_OF_RANGE (1, flag);
212 debug_cells_gc_interval = f;
213 scm_debug_cell_accesses_p = 1;
214 } else {
215 SCM_WRONG_TYPE_ARG (1, flag);
216 }
217 return SCM_UNSPECIFIED;
218 }
219 #undef FUNC_NAME
220
221 #endif /* SCM_DEBUG_CELL_ACCESSES == 1 */
222
223 \f
224
225 /* {heap tuning parameters}
226 *
227 * These are parameters for controlling memory allocation. The heap
228 * is the area out of which scm_cons, and object headers are allocated.
229 *
230 * Each heap cell is 8 bytes on a 32 bit machine and 16 bytes on a
231 * 64 bit machine. The units of the _SIZE parameters are bytes.
232 * Cons pairs and object headers occupy one heap cell.
233 *
234 * SCM_INIT_HEAP_SIZE is the initial size of heap. If this much heap is
235 * allocated initially the heap will grow by half its current size
236 * each subsequent time more heap is needed.
237 *
238 * If SCM_INIT_HEAP_SIZE heap cannot be allocated initially, SCM_HEAP_SEG_SIZE
239 * will be used, and the heap will grow by SCM_HEAP_SEG_SIZE when more
240 * heap is needed. SCM_HEAP_SEG_SIZE must fit into type size_t. This code
241 * is in scm_init_storage() and alloc_some_heap() in sys.c
242 *
243 * If SCM_INIT_HEAP_SIZE can be allocated initially, the heap will grow by
244 * SCM_EXPHEAP(scm_heap_size) when more heap is needed.
245 *
246 * SCM_MIN_HEAP_SEG_SIZE is minimum size of heap to accept when more heap
247 * is needed.
248 *
249 * INIT_MALLOC_LIMIT is the initial amount of malloc usage which will
250 * trigger a GC.
251 *
252 * SCM_MTRIGGER_HYSTERESIS is the amount of malloc storage that must be
253 * reclaimed by a GC triggered by must_malloc. If less than this is
254 * reclaimed, the trigger threshold is raised. [I don't know what a
255 * good value is. I arbitrarily chose 1/10 of the INIT_MALLOC_LIMIT to
256 * work around a oscillation that caused almost constant GC.]
257 */
258
259 /*
260 * Heap size 45000 and 40% min yield gives quick startup and no extra
261 * heap allocation. Having higher values on min yield may lead to
262 * large heaps, especially if code behaviour is varying its
263 * maximum consumption between different freelists.
264 */
265
266 #define SCM_DATA_CELLS2CARDS(n) (((n) + SCM_GC_CARD_N_DATA_CELLS - 1) / SCM_GC_CARD_N_DATA_CELLS)
267 #define SCM_CARDS_PER_CLUSTER SCM_DATA_CELLS2CARDS (2000L)
268 #define SCM_CLUSTER_SIZE_1 (SCM_CARDS_PER_CLUSTER * SCM_GC_CARD_N_DATA_CELLS)
269 size_t scm_default_init_heap_size_1 = (((SCM_DATA_CELLS2CARDS (45000L) + SCM_CARDS_PER_CLUSTER - 1)
270 / SCM_CARDS_PER_CLUSTER) * SCM_GC_CARD_SIZE);
271 int scm_default_min_yield_1 = 40;
272
273 #define SCM_CLUSTER_SIZE_2 (SCM_CARDS_PER_CLUSTER * (SCM_GC_CARD_N_DATA_CELLS / 2))
274 size_t scm_default_init_heap_size_2 = (((SCM_DATA_CELLS2CARDS (2500L * 2) + SCM_CARDS_PER_CLUSTER - 1)
275 / SCM_CARDS_PER_CLUSTER) * SCM_GC_CARD_SIZE);
276 /* The following value may seem large, but note that if we get to GC at
277 * all, this means that we have a numerically intensive application
278 */
279 int scm_default_min_yield_2 = 40;
280
281 size_t scm_default_max_segment_size = 2097000L;/* a little less (adm) than 2 Mb */
282
283 #define SCM_MIN_HEAP_SEG_SIZE (8 * SCM_GC_CARD_SIZE)
284 #ifdef _QC
285 # define SCM_HEAP_SEG_SIZE 32768L
286 #else
287 # ifdef sequent
288 # define SCM_HEAP_SEG_SIZE (7000L * sizeof (scm_cell))
289 # else
290 # define SCM_HEAP_SEG_SIZE (16384L * sizeof (scm_cell))
291 # endif
292 #endif
293 /* Make heap grow with factor 1.5 */
294 #define SCM_EXPHEAP(scm_heap_size) (scm_heap_size / 2)
295 #define SCM_INIT_MALLOC_LIMIT 100000
296 #define SCM_MTRIGGER_HYSTERESIS (SCM_INIT_MALLOC_LIMIT/10)
297
298 /* CELL_UP and CELL_DN are used by scm_init_heap_seg to find (scm_cell * span)
299 aligned inner bounds for allocated storage */
300
301 #ifdef PROT386
302 /*in 386 protected mode we must only adjust the offset */
303 # define CELL_UP(p, span) MK_FP(FP_SEG(p), ~(8*(span)-1)&(FP_OFF(p)+8*(span)-1))
304 # define CELL_DN(p, span) MK_FP(FP_SEG(p), ~(8*(span)-1)&FP_OFF(p))
305 #else
306 # ifdef _UNICOS
307 # define CELL_UP(p, span) (SCM_CELLPTR)(~(span) & ((long)(p)+(span)))
308 # define CELL_DN(p, span) (SCM_CELLPTR)(~(span) & (long)(p))
309 # else
310 # define CELL_UP(p, span) (SCM_CELLPTR)(~(sizeof(scm_cell)*(span)-1L) & ((long)(p)+sizeof(scm_cell)*(span)-1L))
311 # define CELL_DN(p, span) (SCM_CELLPTR)(~(sizeof(scm_cell)*(span)-1L) & (long)(p))
312 # endif /* UNICOS */
313 #endif /* PROT386 */
314
315 #define DOUBLECELL_ALIGNED_P(x) (((2 * sizeof (scm_cell) - 1) & SCM_UNPACK (x)) == 0)
316
317 #define ALIGNMENT_SLACK(freelist) (SCM_GC_CARD_SIZE - 1)
318 #define CLUSTER_SIZE_IN_BYTES(freelist) \
319 (((freelist)->cluster_size / (SCM_GC_CARD_N_DATA_CELLS / (freelist)->span)) * SCM_GC_CARD_SIZE)
320
321 \f
322 /* scm_freelists
323 */
324
325 typedef struct scm_t_freelist {
326 /* collected cells */
327 SCM cells;
328 /* number of cells left to collect before cluster is full */
329 unsigned int left_to_collect;
330 /* number of clusters which have been allocated */
331 unsigned int clusters_allocated;
332 /* a list of freelists, each of size cluster_size,
333 * except the last one which may be shorter
334 */
335 SCM clusters;
336 SCM *clustertail;
337 /* this is the number of objects in each cluster, including the spine cell */
338 unsigned int cluster_size;
339 /* indicates that we should grow heap instead of GC:ing
340 */
341 int grow_heap_p;
342 /* minimum yield on this list in order not to grow the heap
343 */
344 long min_yield;
345 /* defines min_yield as percent of total heap size
346 */
347 int min_yield_fraction;
348 /* number of cells per object on this list */
349 int span;
350 /* number of collected cells during last GC */
351 unsigned long collected;
352 /* number of collected cells during penultimate GC */
353 unsigned long collected_1;
354 /* total number of cells in heap segments
355 * belonging to this list.
356 */
357 unsigned long heap_size;
358 } scm_t_freelist;
359
360 SCM scm_freelist = SCM_EOL;
361 scm_t_freelist scm_master_freelist = {
362 SCM_EOL, 0, 0, SCM_EOL, 0, SCM_CLUSTER_SIZE_1, 0, 0, 0, 1, 0, 0, 0
363 };
364 SCM scm_freelist2 = SCM_EOL;
365 scm_t_freelist scm_master_freelist2 = {
366 SCM_EOL, 0, 0, SCM_EOL, 0, SCM_CLUSTER_SIZE_2, 0, 0, 0, 2, 0, 0, 0
367 };
368
369 /* scm_mtrigger
370 * is the number of bytes of must_malloc allocation needed to trigger gc.
371 */
372 unsigned long scm_mtrigger;
373
374 /* scm_gc_heap_lock
375 * If set, don't expand the heap. Set only during gc, during which no allocation
376 * is supposed to take place anyway.
377 */
378 int scm_gc_heap_lock = 0;
379
380 /* GC Blocking
381 * Don't pause for collection if this is set -- just
382 * expand the heap.
383 */
384 int scm_block_gc = 1;
385
386 /* During collection, this accumulates objects holding
387 * weak references.
388 */
389 SCM scm_weak_vectors;
390
391 /* During collection, this accumulates structures which are to be freed.
392 */
393 SCM scm_structs_to_free;
394
395 /* GC Statistics Keeping
396 */
397 unsigned long scm_cells_allocated = 0;
398 unsigned long scm_mallocated = 0;
399 unsigned long scm_gc_cells_collected;
400 unsigned long scm_gc_yield;
401 static unsigned long scm_gc_yield_1 = 0; /* previous GC yield */
402 unsigned long scm_gc_malloc_collected;
403 unsigned long scm_gc_ports_collected;
404 unsigned long scm_gc_time_taken = 0;
405 static unsigned long t_before_gc;
406 static unsigned long t_before_sweep;
407 unsigned long scm_gc_mark_time_taken = 0;
408 unsigned long scm_gc_sweep_time_taken = 0;
409 unsigned long scm_gc_times = 0;
410 unsigned long scm_gc_cells_swept = 0;
411 double scm_gc_cells_marked_acc = 0.;
412 double scm_gc_cells_swept_acc = 0.;
413
414 SCM_SYMBOL (sym_cells_allocated, "cells-allocated");
415 SCM_SYMBOL (sym_heap_size, "cell-heap-size");
416 SCM_SYMBOL (sym_mallocated, "bytes-malloced");
417 SCM_SYMBOL (sym_mtrigger, "gc-malloc-threshold");
418 SCM_SYMBOL (sym_heap_segments, "cell-heap-segments");
419 SCM_SYMBOL (sym_gc_time_taken, "gc-time-taken");
420 SCM_SYMBOL (sym_gc_mark_time_taken, "gc-mark-time-taken");
421 SCM_SYMBOL (sym_gc_sweep_time_taken, "gc-sweep-time-taken");
422 SCM_SYMBOL (sym_times, "gc-times");
423 SCM_SYMBOL (sym_cells_marked, "cells-marked");
424 SCM_SYMBOL (sym_cells_swept, "cells-swept");
425
426 typedef struct scm_t_heap_seg_data
427 {
428 /* lower and upper bounds of the segment */
429 SCM_CELLPTR bounds[2];
430
431 /* address of the head-of-freelist pointer for this segment's cells.
432 All segments usually point to the same one, scm_freelist. */
433 scm_t_freelist *freelist;
434
435 /* number of cells per object in this segment */
436 int span;
437 } scm_t_heap_seg_data;
438
439
440
441 static size_t init_heap_seg (SCM_CELLPTR, size_t, scm_t_freelist *);
442
443 typedef enum { return_on_error, abort_on_error } policy_on_error;
444 static void alloc_some_heap (scm_t_freelist *, policy_on_error);
445
446
447 #define SCM_HEAP_SIZE \
448 (scm_master_freelist.heap_size + scm_master_freelist2.heap_size)
449 #define SCM_MAX(A, B) ((A) > (B) ? (A) : (B))
450
451 #define BVEC_GROW_SIZE 256
452 #define BVEC_GROW_SIZE_IN_LIMBS (SCM_GC_CARD_BVEC_SIZE_IN_LIMBS * BVEC_GROW_SIZE)
453 #define BVEC_GROW_SIZE_IN_BYTES (BVEC_GROW_SIZE_IN_LIMBS * sizeof (scm_t_c_bvec_limb))
454
455 /* mark space allocation */
456
457 typedef struct scm_t_mark_space
458 {
459 scm_t_c_bvec_limb *bvec_space;
460 struct scm_t_mark_space *next;
461 } scm_t_mark_space;
462
463 static scm_t_mark_space *current_mark_space;
464 static scm_t_mark_space **mark_space_ptr;
465 static ptrdiff_t current_mark_space_offset;
466 static scm_t_mark_space *mark_space_head;
467
468 static scm_t_c_bvec_limb *
469 get_bvec ()
470 #define FUNC_NAME "get_bvec"
471 {
472 scm_t_c_bvec_limb *res;
473
474 if (!current_mark_space)
475 {
476 SCM_SYSCALL (current_mark_space = (scm_t_mark_space *) malloc (sizeof (scm_t_mark_space)));
477 if (!current_mark_space)
478 SCM_MISC_ERROR ("could not grow heap", SCM_EOL);
479
480 current_mark_space->bvec_space = NULL;
481 current_mark_space->next = NULL;
482
483 *mark_space_ptr = current_mark_space;
484 mark_space_ptr = &(current_mark_space->next);
485
486 return get_bvec ();
487 }
488
489 if (!(current_mark_space->bvec_space))
490 {
491 SCM_SYSCALL (current_mark_space->bvec_space =
492 (scm_t_c_bvec_limb *) calloc (BVEC_GROW_SIZE_IN_BYTES, 1));
493 if (!(current_mark_space->bvec_space))
494 SCM_MISC_ERROR ("could not grow heap", SCM_EOL);
495
496 current_mark_space_offset = 0;
497
498 return get_bvec ();
499 }
500
501 if (current_mark_space_offset == BVEC_GROW_SIZE_IN_LIMBS)
502 {
503 current_mark_space = NULL;
504
505 return get_bvec ();
506 }
507
508 res = current_mark_space->bvec_space + current_mark_space_offset;
509 current_mark_space_offset += SCM_GC_CARD_BVEC_SIZE_IN_LIMBS;
510
511 return res;
512 }
513 #undef FUNC_NAME
514
515
516 static void
517 clear_mark_space ()
518 {
519 scm_t_mark_space *ms;
520
521 for (ms = mark_space_head; ms; ms = ms->next)
522 memset (ms->bvec_space, 0, BVEC_GROW_SIZE_IN_BYTES);
523 }
524
525
526 \f
527 /* Debugging functions. */
528
529 #if defined (GUILE_DEBUG) || defined (GUILE_DEBUG_FREELIST)
530
531 static long int heap_segment (SCM obj); /* forw decl: non-debugging func */
532
533 static void
534 map_free_list (scm_t_freelist *master, SCM freelist)
535 {
536 long last_seg = -1, count = 0;
537 SCM f;
538
539 for (f = freelist; !SCM_NULLP (f); f = SCM_FREE_CELL_CDR (f))
540 {
541 long int this_seg = heap_segment (f);
542
543 if (this_seg == -1)
544 {
545 fprintf (stderr,
546 "map_free_list: can't find segment containing cell %lux\n",
547 (unsigned long int) SCM_UNPACK (f));
548 abort ();
549 }
550 else if (this_seg != last_seg)
551 {
552 if (last_seg != -1)
553 fprintf (stderr, " %5ld %d-cells in segment %ld\n",
554 (long) count, master->span, (long) last_seg);
555 last_seg = this_seg;
556 count = 0;
557 }
558 count++;
559 }
560 if (last_seg != -1)
561 fprintf (stderr, " %5ld %d-cells in segment %ld\n",
562 (long) count, master->span, (long) last_seg);
563 }
564
565 SCM_DEFINE (scm_map_free_list, "map-free-list", 0, 0, 0,
566 (),
567 "Print debugging information about the free-list.\n"
568 "@code{map-free-list} is only included in\n"
569 "@code{--enable-guile-debug} builds of Guile.")
570 #define FUNC_NAME s_scm_map_free_list
571 {
572 size_t i;
573
574 fprintf (stderr, "%ld segments total (%d:%ld",
575 (long) scm_n_heap_segs,
576 scm_heap_table[0].span,
577 (long) (scm_heap_table[0].bounds[1] - scm_heap_table[0].bounds[0]));
578
579 for (i = 1; i != scm_n_heap_segs; i++)
580 fprintf (stderr, ", %d:%ld",
581 scm_heap_table[i].span,
582 (long) (scm_heap_table[i].bounds[1] - scm_heap_table[i].bounds[0]));
583 fprintf (stderr, ")\n");
584 map_free_list (&scm_master_freelist, scm_freelist);
585 map_free_list (&scm_master_freelist2, scm_freelist2);
586 fflush (stderr);
587
588 return SCM_UNSPECIFIED;
589 }
590 #undef FUNC_NAME
591
592 static long last_cluster;
593 static long last_size;
594
595 static long
596 free_list_length (char *title, long i, SCM freelist)
597 {
598 SCM ls;
599 long n = 0;
600 for (ls = freelist; !SCM_NULLP (ls); ls = SCM_FREE_CELL_CDR (ls))
601 if (SCM_FREE_CELL_P (ls))
602 ++n;
603 else
604 {
605 fprintf (stderr, "bad cell in %s at position %ld\n", title, (long) n);
606 abort ();
607 }
608 if (n != last_size)
609 {
610 if (i > 0)
611 {
612 if (last_cluster == i - 1)
613 fprintf (stderr, "\t%ld\n", (long) last_size);
614 else
615 fprintf (stderr, "-%ld\t%ld\n", (long) (i - 1), (long) last_size);
616 }
617 if (i >= 0)
618 fprintf (stderr, "%s %ld", title, (long) i);
619 else
620 fprintf (stderr, "%s\t%ld\n", title, (long) n);
621 last_cluster = i;
622 last_size = n;
623 }
624 return n;
625 }
626
627 static void
628 free_list_lengths (char *title, scm_t_freelist *master, SCM freelist)
629 {
630 SCM clusters;
631 long i = 0, len, n = 0;
632 fprintf (stderr, "%s\n\n", title);
633 n += free_list_length ("free list", -1, freelist);
634 for (clusters = master->clusters;
635 SCM_NNULLP (clusters);
636 clusters = SCM_CDR (clusters))
637 {
638 len = free_list_length ("cluster", i++, SCM_CAR (clusters));
639 n += len;
640 }
641 if (last_cluster == i - 1)
642 fprintf (stderr, "\t%ld\n", (long) last_size);
643 else
644 fprintf (stderr, "-%ld\t%ld\n", (long) (i - 1), (long) last_size);
645 fprintf (stderr, "\ntotal %ld objects\n\n", (long) n);
646 }
647
648 SCM_DEFINE (scm_free_list_length, "free-list-length", 0, 0, 0,
649 (),
650 "Print debugging information about the free-list.\n"
651 "@code{free-list-length} is only included in\n"
652 "@code{--enable-guile-debug} builds of Guile.")
653 #define FUNC_NAME s_scm_free_list_length
654 {
655 free_list_lengths ("1-cells", &scm_master_freelist, scm_freelist);
656 free_list_lengths ("2-cells", &scm_master_freelist2, scm_freelist2);
657 return SCM_UNSPECIFIED;
658 }
659 #undef FUNC_NAME
660
661 #endif /* defined (GUILE_DEBUG) || defined (GUILE_DEBUG_FREELIST) */
662
663 #ifdef GUILE_DEBUG_FREELIST
664
665 /* Non-zero if freelist debugging is in effect. Set this via
666 `gc-set-debug-check-freelist!'. */
667 static int scm_debug_check_freelist = 0;
668
669 /* Number of calls to SCM_NEWCELL since startup. */
670 static unsigned long scm_newcell_count;
671 static unsigned long scm_newcell2_count;
672
673 /* Search freelist for anything that isn't marked as a free cell.
674 Abort if we find something. */
675 static void
676 scm_check_freelist (SCM freelist)
677 {
678 SCM f;
679 long i = 0;
680
681 for (f = freelist; !SCM_NULLP (f); f = SCM_FREE_CELL_CDR (f), i++)
682 if (!SCM_FREE_CELL_P (f))
683 {
684 fprintf (stderr, "Bad cell in freelist on newcell %lu: %lu'th elt\n",
685 (long) scm_newcell_count, (long) i);
686 abort ();
687 }
688 }
689
690 SCM_DEFINE (scm_gc_set_debug_check_freelist_x, "gc-set-debug-check-freelist!", 1, 0, 0,
691 (SCM flag),
692 "If @var{flag} is @code{#t}, check the freelist for consistency\n"
693 "on each cell allocation. This procedure only exists when the\n"
694 "@code{GUILE_DEBUG_FREELIST} compile-time flag was selected.")
695 #define FUNC_NAME s_scm_gc_set_debug_check_freelist_x
696 {
697 /* [cmm] I did a double-take when I read this code the first time.
698 well, FWIW. */
699 SCM_VALIDATE_BOOL_COPY (1, flag, scm_debug_check_freelist);
700 return SCM_UNSPECIFIED;
701 }
702 #undef FUNC_NAME
703
704
705 SCM
706 scm_debug_newcell (void)
707 {
708 SCM new;
709
710 scm_newcell_count++;
711 if (scm_debug_check_freelist)
712 {
713 scm_check_freelist (scm_freelist);
714 scm_gc();
715 }
716
717 /* The rest of this is supposed to be identical to the SCM_NEWCELL
718 macro. */
719 if (SCM_NULLP (scm_freelist))
720 {
721 new = scm_gc_for_newcell (&scm_master_freelist, &scm_freelist);
722 SCM_GC_SET_ALLOCATED (new);
723 }
724 else
725 {
726 new = scm_freelist;
727 scm_freelist = SCM_FREE_CELL_CDR (scm_freelist);
728 SCM_GC_SET_ALLOCATED (new);
729 }
730
731 return new;
732 }
733
734 SCM
735 scm_debug_newcell2 (void)
736 {
737 SCM new;
738
739 scm_newcell2_count++;
740 if (scm_debug_check_freelist)
741 {
742 scm_check_freelist (scm_freelist2);
743 scm_gc ();
744 }
745
746 /* The rest of this is supposed to be identical to the SCM_NEWCELL
747 macro. */
748 if (SCM_NULLP (scm_freelist2))
749 {
750 new = scm_gc_for_newcell (&scm_master_freelist2, &scm_freelist2);
751 SCM_GC_SET_ALLOCATED (new);
752 }
753 else
754 {
755 new = scm_freelist2;
756 scm_freelist2 = SCM_FREE_CELL_CDR (scm_freelist2);
757 SCM_GC_SET_ALLOCATED (new);
758 }
759
760 return new;
761 }
762
763 #endif /* GUILE_DEBUG_FREELIST */
764
765 \f
766
767 static unsigned long
768 master_cells_allocated (scm_t_freelist *master)
769 {
770 /* the '- 1' below is to ignore the cluster spine cells. */
771 long objects = master->clusters_allocated * (master->cluster_size - 1);
772 if (SCM_NULLP (master->clusters))
773 objects -= master->left_to_collect;
774 return master->span * objects;
775 }
776
777 static unsigned long
778 freelist_length (SCM freelist)
779 {
780 long n;
781 for (n = 0; !SCM_NULLP (freelist); freelist = SCM_FREE_CELL_CDR (freelist))
782 ++n;
783 return n;
784 }
785
786 static unsigned long
787 compute_cells_allocated ()
788 {
789 return (scm_cells_allocated
790 + master_cells_allocated (&scm_master_freelist)
791 + master_cells_allocated (&scm_master_freelist2)
792 - scm_master_freelist.span * freelist_length (scm_freelist)
793 - scm_master_freelist2.span * freelist_length (scm_freelist2));
794 }
795
796 /* {Scheme Interface to GC}
797 */
798
799 SCM_DEFINE (scm_gc_stats, "gc-stats", 0, 0, 0,
800 (),
801 "Return an association list of statistics about Guile's current\n"
802 "use of storage.")
803 #define FUNC_NAME s_scm_gc_stats
804 {
805 long i;
806 long n;
807 SCM heap_segs;
808 unsigned long int local_scm_mtrigger;
809 unsigned long int local_scm_mallocated;
810 unsigned long int local_scm_heap_size;
811 unsigned long int local_scm_cells_allocated;
812 unsigned long int local_scm_gc_time_taken;
813 unsigned long int local_scm_gc_times;
814 unsigned long int local_scm_gc_mark_time_taken;
815 unsigned long int local_scm_gc_sweep_time_taken;
816 double local_scm_gc_cells_swept;
817 double local_scm_gc_cells_marked;
818 SCM answer;
819
820 SCM_DEFER_INTS;
821
822 ++scm_block_gc;
823
824 retry:
825 heap_segs = SCM_EOL;
826 n = scm_n_heap_segs;
827 for (i = scm_n_heap_segs; i--; )
828 heap_segs = scm_cons (scm_cons (scm_ulong2num ((unsigned long)scm_heap_table[i].bounds[1]),
829 scm_ulong2num ((unsigned long)scm_heap_table[i].bounds[0])),
830 heap_segs);
831 if (scm_n_heap_segs != n)
832 goto retry;
833
834 --scm_block_gc;
835
836 /* Below, we cons to produce the resulting list. We want a snapshot of
837 * the heap situation before consing.
838 */
839 local_scm_mtrigger = scm_mtrigger;
840 local_scm_mallocated = scm_mallocated;
841 local_scm_heap_size = SCM_HEAP_SIZE;
842 local_scm_cells_allocated = compute_cells_allocated ();
843 local_scm_gc_time_taken = scm_gc_time_taken;
844 local_scm_gc_mark_time_taken = scm_gc_mark_time_taken;
845 local_scm_gc_sweep_time_taken = scm_gc_sweep_time_taken;
846 local_scm_gc_times = scm_gc_times;
847 local_scm_gc_cells_swept = scm_gc_cells_swept_acc;
848 local_scm_gc_cells_marked = scm_gc_cells_marked_acc;
849
850 answer = scm_list_n (scm_cons (sym_gc_time_taken, scm_ulong2num (local_scm_gc_time_taken)),
851 scm_cons (sym_cells_allocated, scm_ulong2num (local_scm_cells_allocated)),
852 scm_cons (sym_heap_size, scm_ulong2num (local_scm_heap_size)),
853 scm_cons (sym_mallocated, scm_ulong2num (local_scm_mallocated)),
854 scm_cons (sym_mtrigger, scm_ulong2num (local_scm_mtrigger)),
855 scm_cons (sym_times, scm_ulong2num (local_scm_gc_times)),
856 scm_cons (sym_gc_mark_time_taken, scm_ulong2num (local_scm_gc_mark_time_taken)),
857 scm_cons (sym_gc_sweep_time_taken, scm_ulong2num (local_scm_gc_sweep_time_taken)),
858 scm_cons (sym_cells_marked, scm_i_dbl2big (local_scm_gc_cells_marked)),
859 scm_cons (sym_cells_swept, scm_i_dbl2big (local_scm_gc_cells_swept)),
860 scm_cons (sym_heap_segments, heap_segs),
861 SCM_UNDEFINED);
862 SCM_ALLOW_INTS;
863 return answer;
864 }
865 #undef FUNC_NAME
866
867
868 static void
869 gc_start_stats (const char *what SCM_UNUSED)
870 {
871 t_before_gc = scm_c_get_internal_run_time ();
872 scm_gc_cells_swept = 0;
873 scm_gc_cells_collected = 0;
874 scm_gc_yield_1 = scm_gc_yield;
875 scm_gc_yield = (scm_cells_allocated
876 + master_cells_allocated (&scm_master_freelist)
877 + master_cells_allocated (&scm_master_freelist2));
878 scm_gc_malloc_collected = 0;
879 scm_gc_ports_collected = 0;
880 }
881
882
883 static void
884 gc_end_stats ()
885 {
886 unsigned long t = scm_c_get_internal_run_time ();
887 scm_gc_time_taken += (t - t_before_gc);
888 scm_gc_sweep_time_taken += (t - t_before_sweep);
889 ++scm_gc_times;
890
891 scm_gc_cells_marked_acc += scm_gc_cells_swept - scm_gc_cells_collected;
892 scm_gc_cells_swept_acc += scm_gc_cells_swept;
893 }
894
895
896 SCM_DEFINE (scm_object_address, "object-address", 1, 0, 0,
897 (SCM obj),
898 "Return an integer that for the lifetime of @var{obj} is uniquely\n"
899 "returned by this function for @var{obj}")
900 #define FUNC_NAME s_scm_object_address
901 {
902 return scm_ulong2num ((unsigned long) SCM_UNPACK (obj));
903 }
904 #undef FUNC_NAME
905
906
907 SCM_DEFINE (scm_gc, "gc", 0, 0, 0,
908 (),
909 "Scans all of SCM objects and reclaims for further use those that are\n"
910 "no longer accessible.")
911 #define FUNC_NAME s_scm_gc
912 {
913 SCM_DEFER_INTS;
914 scm_igc ("call");
915 SCM_ALLOW_INTS;
916 return SCM_UNSPECIFIED;
917 }
918 #undef FUNC_NAME
919
920
921 \f
922 /* {C Interface For When GC is Triggered}
923 */
924
925 static void
926 adjust_min_yield (scm_t_freelist *freelist)
927 {
928 /* min yield is adjusted upwards so that next predicted total yield
929 * (allocated cells actually freed by GC) becomes
930 * `min_yield_fraction' of total heap size. Note, however, that
931 * the absolute value of min_yield will correspond to `collected'
932 * on one master (the one which currently is triggering GC).
933 *
934 * The reason why we look at total yield instead of cells collected
935 * on one list is that we want to take other freelists into account.
936 * On this freelist, we know that (local) yield = collected cells,
937 * but that's probably not the case on the other lists.
938 *
939 * (We might consider computing a better prediction, for example
940 * by computing an average over multiple GC:s.)
941 */
942 if (freelist->min_yield_fraction)
943 {
944 /* Pick largest of last two yields. */
945 long delta = ((SCM_HEAP_SIZE * freelist->min_yield_fraction / 100)
946 - (long) SCM_MAX (scm_gc_yield_1, scm_gc_yield));
947 #ifdef DEBUGINFO
948 fprintf (stderr, " after GC = %lu, delta = %ld\n",
949 (long) scm_cells_allocated,
950 (long) delta);
951 #endif
952 if (delta > 0)
953 freelist->min_yield += delta;
954 }
955 }
956
957
958 /* When we get POSIX threads support, the master will be global and
959 * common while the freelist will be individual for each thread.
960 */
961
962 SCM
963 scm_gc_for_newcell (scm_t_freelist *master, SCM *freelist)
964 {
965 SCM cell;
966 ++scm_ints_disabled;
967 do
968 {
969 if (SCM_NULLP (master->clusters))
970 {
971 if (master->grow_heap_p || scm_block_gc)
972 {
973 /* In order to reduce gc frequency, try to allocate a new heap
974 * segment first, even if gc might find some free cells. If we
975 * can't obtain a new heap segment, we will try gc later.
976 */
977 master->grow_heap_p = 0;
978 alloc_some_heap (master, return_on_error);
979 }
980 if (SCM_NULLP (master->clusters))
981 {
982 /* The heap was not grown, either because it wasn't scheduled to
983 * grow, or because there was not enough memory available. In
984 * both cases we have to try gc to get some free cells.
985 */
986 #ifdef DEBUGINFO
987 fprintf (stderr, "allocated = %lu, ",
988 (long) (scm_cells_allocated
989 + master_cells_allocated (&scm_master_freelist)
990 + master_cells_allocated (&scm_master_freelist2)));
991 #endif
992 scm_igc ("cells");
993 adjust_min_yield (master);
994 if (SCM_NULLP (master->clusters))
995 {
996 /* gc could not free any cells. Now, we _must_ allocate a
997 * new heap segment, because there is no other possibility
998 * to provide a new cell for the caller.
999 */
1000 alloc_some_heap (master, abort_on_error);
1001 }
1002 }
1003 }
1004 cell = SCM_CAR (master->clusters);
1005 master->clusters = SCM_CDR (master->clusters);
1006 ++master->clusters_allocated;
1007 }
1008 while (SCM_NULLP (cell));
1009
1010 #ifdef GUILE_DEBUG_FREELIST
1011 scm_check_freelist (cell);
1012 #endif
1013
1014 --scm_ints_disabled;
1015 *freelist = SCM_FREE_CELL_CDR (cell);
1016 return cell;
1017 }
1018
1019
1020 #if 0
1021 /* This is a support routine which can be used to reserve a cluster
1022 * for some special use, such as debugging. It won't be useful until
1023 * free cells are preserved between garbage collections.
1024 */
1025
1026 void
1027 scm_alloc_cluster (scm_t_freelist *master)
1028 {
1029 SCM freelist, cell;
1030 cell = scm_gc_for_newcell (master, &freelist);
1031 SCM_SETCDR (cell, freelist);
1032 return cell;
1033 }
1034 #endif
1035
1036
1037 scm_t_c_hook scm_before_gc_c_hook;
1038 scm_t_c_hook scm_before_mark_c_hook;
1039 scm_t_c_hook scm_before_sweep_c_hook;
1040 scm_t_c_hook scm_after_sweep_c_hook;
1041 scm_t_c_hook scm_after_gc_c_hook;
1042
1043
1044 void
1045 scm_igc (const char *what)
1046 {
1047 long j;
1048
1049 ++scm_gc_running_p;
1050 scm_c_hook_run (&scm_before_gc_c_hook, 0);
1051 #ifdef DEBUGINFO
1052 fprintf (stderr,
1053 SCM_NULLP (scm_freelist)
1054 ? "*"
1055 : (SCM_NULLP (scm_freelist2) ? "o" : "m"));
1056 #endif
1057 /* During the critical section, only the current thread may run. */
1058 SCM_CRITICAL_SECTION_START;
1059
1060 /* fprintf (stderr, "gc: %s\n", what); */
1061
1062 if (!scm_stack_base || scm_block_gc)
1063 {
1064 --scm_gc_running_p;
1065 return;
1066 }
1067
1068 gc_start_stats (what);
1069
1070 if (scm_gc_heap_lock)
1071 /* We've invoked the collector while a GC is already in progress.
1072 That should never happen. */
1073 abort ();
1074
1075 ++scm_gc_heap_lock;
1076
1077 /* flush dead entries from the continuation stack */
1078 {
1079 long x;
1080 long bound;
1081 SCM * elts;
1082 elts = SCM_VELTS (scm_continuation_stack);
1083 bound = SCM_VECTOR_LENGTH (scm_continuation_stack);
1084 x = SCM_INUM (scm_continuation_stack_ptr);
1085 while (x < bound)
1086 {
1087 elts[x] = SCM_BOOL_F;
1088 ++x;
1089 }
1090 }
1091
1092 scm_c_hook_run (&scm_before_mark_c_hook, 0);
1093
1094 clear_mark_space ();
1095
1096 #ifndef USE_THREADS
1097
1098 /* Mark objects on the C stack. */
1099 SCM_FLUSH_REGISTER_WINDOWS;
1100 /* This assumes that all registers are saved into the jmp_buf */
1101 setjmp (scm_save_regs_gc_mark);
1102 scm_mark_locations ((SCM_STACKITEM *) scm_save_regs_gc_mark,
1103 ( (size_t) (sizeof (SCM_STACKITEM) - 1 +
1104 sizeof scm_save_regs_gc_mark)
1105 / sizeof (SCM_STACKITEM)));
1106
1107 {
1108 unsigned long stack_len = scm_stack_size (scm_stack_base);
1109 #ifdef SCM_STACK_GROWS_UP
1110 scm_mark_locations (scm_stack_base, stack_len);
1111 #else
1112 scm_mark_locations (scm_stack_base - stack_len, stack_len);
1113 #endif
1114 }
1115
1116 #else /* USE_THREADS */
1117
1118 /* Mark every thread's stack and registers */
1119 scm_threads_mark_stacks ();
1120
1121 #endif /* USE_THREADS */
1122
1123 j = SCM_NUM_PROTECTS;
1124 while (j--)
1125 scm_gc_mark (scm_sys_protects[j]);
1126
1127 /* mark the registered roots */
1128 {
1129 size_t i;
1130 for (i = 0; i < SCM_VECTOR_LENGTH (scm_gc_registered_roots); ++i) {
1131 SCM l = SCM_VELTS (scm_gc_registered_roots)[i];
1132 for (; !SCM_NULLP (l); l = SCM_CDR (l)) {
1133 SCM *p = (SCM *) (scm_num2long (SCM_CAAR (l), 0, NULL));
1134 scm_gc_mark (*p);
1135 }
1136 }
1137 }
1138
1139 /* FIXME: we should have a means to register C functions to be run
1140 * in different phases of GC
1141 */
1142 scm_mark_subr_table ();
1143
1144 #ifndef USE_THREADS
1145 scm_gc_mark (scm_root->handle);
1146 #endif
1147
1148 t_before_sweep = scm_c_get_internal_run_time ();
1149 scm_gc_mark_time_taken += (t_before_sweep - t_before_gc);
1150
1151 scm_c_hook_run (&scm_before_sweep_c_hook, 0);
1152
1153 scm_gc_sweep ();
1154
1155 scm_c_hook_run (&scm_after_sweep_c_hook, 0);
1156
1157 --scm_gc_heap_lock;
1158 gc_end_stats ();
1159
1160 SCM_CRITICAL_SECTION_END;
1161 scm_c_hook_run (&scm_after_gc_c_hook, 0);
1162 --scm_gc_running_p;
1163 }
1164
1165 \f
1166
1167 /* {Mark/Sweep}
1168 */
1169
1170 #define MARK scm_gc_mark
1171 #define FNAME "scm_gc_mark"
1172
1173 #endif /*!MARK_DEPENDENCIES*/
1174
1175 /* Mark an object precisely.
1176 */
1177 void
1178 MARK (SCM p)
1179 #define FUNC_NAME FNAME
1180 {
1181 register long i;
1182 register SCM ptr;
1183 scm_t_bits cell_type;
1184
1185 #ifndef MARK_DEPENDENCIES
1186 # define RECURSE scm_gc_mark
1187 #else
1188 /* go through the usual marking, but not for self-cycles. */
1189 # define RECURSE(x) do { if ((x) != p) scm_gc_mark (x); } while (0)
1190 #endif
1191 ptr = p;
1192
1193 #ifdef MARK_DEPENDENCIES
1194 goto gc_mark_loop_first_time;
1195 #endif
1196
1197 /* A simple hack for debugging. Chose the second branch to get a
1198 meaningful backtrace for crashes inside the GC.
1199 */
1200 #if 1
1201 #define goto_gc_mark_loop goto gc_mark_loop
1202 #define goto_gc_mark_nimp goto gc_mark_nimp
1203 #else
1204 #define goto_gc_mark_loop RECURSE(ptr); return
1205 #define goto_gc_mark_nimp RECURSE(ptr); return
1206 #endif
1207
1208 gc_mark_loop:
1209 if (SCM_IMP (ptr))
1210 return;
1211
1212 gc_mark_nimp:
1213
1214 #ifdef MARK_DEPENDENCIES
1215 if (SCM_EQ_P (ptr, p))
1216 return;
1217
1218 scm_gc_mark (ptr);
1219 return;
1220
1221 gc_mark_loop_first_time:
1222 #endif
1223
1224 #if (SCM_DEBUG_CELL_ACCESSES == 1) || (defined (GUILE_DEBUG_FREELIST))
1225 /* We are in debug mode. Check the ptr exhaustively. */
1226 if (!scm_cellp (ptr))
1227 SCM_MISC_ERROR ("rogue pointer in heap", SCM_EOL);
1228 #else
1229 /* In non-debug mode, do at least some cheap testing. */
1230 if (!SCM_CELLP (ptr))
1231 SCM_MISC_ERROR ("rogue pointer in heap", SCM_EOL);
1232 #endif
1233
1234 #ifndef MARK_DEPENDENCIES
1235
1236 if (SCM_GCMARKP (ptr))
1237 return;
1238
1239 SCM_SETGCMARK (ptr);
1240
1241 #endif
1242
1243 cell_type = SCM_GC_CELL_TYPE (ptr);
1244 switch (SCM_ITAG7 (cell_type))
1245 {
1246 case scm_tcs_cons_nimcar:
1247 if (SCM_IMP (SCM_CDR (ptr)))
1248 {
1249 ptr = SCM_CAR (ptr);
1250 goto_gc_mark_nimp;
1251 }
1252 RECURSE (SCM_CAR (ptr));
1253 ptr = SCM_CDR (ptr);
1254 goto_gc_mark_nimp;
1255 case scm_tcs_cons_imcar:
1256 ptr = SCM_CDR (ptr);
1257 goto_gc_mark_loop;
1258 case scm_tc7_pws:
1259 RECURSE (SCM_SETTER (ptr));
1260 ptr = SCM_PROCEDURE (ptr);
1261 goto_gc_mark_loop;
1262 case scm_tcs_struct:
1263 {
1264 /* XXX - use less explicit code. */
1265 scm_t_bits word0 = SCM_CELL_WORD_0 (ptr) - scm_tc3_struct;
1266 scm_t_bits * vtable_data = (scm_t_bits *) word0;
1267 SCM layout = SCM_PACK (vtable_data [scm_vtable_index_layout]);
1268 long len = SCM_SYMBOL_LENGTH (layout);
1269 char * fields_desc = SCM_SYMBOL_CHARS (layout);
1270 scm_t_bits * struct_data = (scm_t_bits *) SCM_STRUCT_DATA (ptr);
1271
1272 if (vtable_data[scm_struct_i_flags] & SCM_STRUCTF_ENTITY)
1273 {
1274 RECURSE (SCM_PACK (struct_data[scm_struct_i_procedure]));
1275 RECURSE (SCM_PACK (struct_data[scm_struct_i_setter]));
1276 }
1277 if (len)
1278 {
1279 long x;
1280
1281 for (x = 0; x < len - 2; x += 2, ++struct_data)
1282 if (fields_desc[x] == 'p')
1283 RECURSE (SCM_PACK (*struct_data));
1284 if (fields_desc[x] == 'p')
1285 {
1286 if (SCM_LAYOUT_TAILP (fields_desc[x + 1]))
1287 for (x = *struct_data++; x; --x, ++struct_data)
1288 RECURSE (SCM_PACK (*struct_data));
1289 else
1290 RECURSE (SCM_PACK (*struct_data));
1291 }
1292 }
1293 /* mark vtable */
1294 ptr = SCM_PACK (vtable_data [scm_vtable_index_vtable]);
1295 goto_gc_mark_loop;
1296 }
1297 break;
1298 case scm_tcs_closures:
1299 if (SCM_IMP (SCM_ENV (ptr)))
1300 {
1301 ptr = SCM_CLOSCAR (ptr);
1302 goto_gc_mark_nimp;
1303 }
1304 RECURSE (SCM_CLOSCAR (ptr));
1305 ptr = SCM_ENV (ptr);
1306 goto_gc_mark_nimp;
1307 case scm_tc7_vector:
1308 i = SCM_VECTOR_LENGTH (ptr);
1309 if (i == 0)
1310 break;
1311 while (--i > 0)
1312 if (SCM_NIMP (SCM_VELTS (ptr)[i]))
1313 RECURSE (SCM_VELTS (ptr)[i]);
1314 ptr = SCM_VELTS (ptr)[0];
1315 goto_gc_mark_loop;
1316 #ifdef CCLO
1317 case scm_tc7_cclo:
1318 {
1319 size_t i = SCM_CCLO_LENGTH (ptr);
1320 size_t j;
1321 for (j = 1; j != i; ++j)
1322 {
1323 SCM obj = SCM_CCLO_REF (ptr, j);
1324 if (!SCM_IMP (obj))
1325 RECURSE (obj);
1326 }
1327 ptr = SCM_CCLO_REF (ptr, 0);
1328 goto_gc_mark_loop;
1329 }
1330 #endif
1331 #ifdef HAVE_ARRAYS
1332 case scm_tc7_bvect:
1333 case scm_tc7_byvect:
1334 case scm_tc7_ivect:
1335 case scm_tc7_uvect:
1336 case scm_tc7_fvect:
1337 case scm_tc7_dvect:
1338 case scm_tc7_cvect:
1339 case scm_tc7_svect:
1340 #ifdef HAVE_LONG_LONGS
1341 case scm_tc7_llvect:
1342 #endif
1343 #endif
1344 case scm_tc7_string:
1345 break;
1346
1347 case scm_tc7_substring:
1348 ptr = SCM_CDR (ptr);
1349 goto_gc_mark_loop;
1350
1351 case scm_tc7_wvect:
1352 SCM_SET_WVECT_GC_CHAIN (ptr, scm_weak_vectors);
1353 scm_weak_vectors = ptr;
1354 if (SCM_IS_WHVEC_ANY (ptr))
1355 {
1356 long x;
1357 long len;
1358 int weak_keys;
1359 int weak_values;
1360
1361 len = SCM_VECTOR_LENGTH (ptr);
1362 weak_keys = SCM_IS_WHVEC (ptr) || SCM_IS_WHVEC_B (ptr);
1363 weak_values = SCM_IS_WHVEC_V (ptr) || SCM_IS_WHVEC_B (ptr);
1364
1365 for (x = 0; x < len; ++x)
1366 {
1367 SCM alist;
1368 alist = SCM_VELTS (ptr)[x];
1369
1370 /* mark everything on the alist except the keys or
1371 * values, according to weak_values and weak_keys. */
1372 while ( SCM_CONSP (alist)
1373 && !SCM_GCMARKP (alist)
1374 && SCM_CONSP (SCM_CAR (alist)))
1375 {
1376 SCM kvpair;
1377 SCM next_alist;
1378
1379 kvpair = SCM_CAR (alist);
1380 next_alist = SCM_CDR (alist);
1381 /*
1382 * Do not do this:
1383 * SCM_SETGCMARK (alist);
1384 * SCM_SETGCMARK (kvpair);
1385 *
1386 * It may be that either the key or value is protected by
1387 * an escaped reference to part of the spine of this alist.
1388 * If we mark the spine here, and only mark one or neither of the
1389 * key and value, they may never be properly marked.
1390 * This leads to a horrible situation in which an alist containing
1391 * freelist cells is exported.
1392 *
1393 * So only mark the spines of these arrays last of all marking.
1394 * If somebody confuses us by constructing a weak vector
1395 * with a circular alist then we are hosed, but at least we
1396 * won't prematurely drop table entries.
1397 */
1398 if (!weak_keys)
1399 RECURSE (SCM_CAR (kvpair));
1400 if (!weak_values)
1401 RECURSE (SCM_CDR (kvpair));
1402 alist = next_alist;
1403 }
1404 if (SCM_NIMP (alist))
1405 RECURSE (alist);
1406 }
1407 }
1408 break;
1409
1410 case scm_tc7_symbol:
1411 ptr = SCM_PROP_SLOTS (ptr);
1412 goto_gc_mark_loop;
1413 case scm_tc7_variable:
1414 ptr = SCM_CELL_OBJECT_1 (ptr);
1415 goto_gc_mark_loop;
1416 case scm_tcs_subrs:
1417 break;
1418 case scm_tc7_port:
1419 i = SCM_PTOBNUM (ptr);
1420 #if (SCM_DEBUG_CELL_ACCESSES == 1) || (defined (GUILE_DEBUG_FREELIST))
1421 if (!(i < scm_numptob))
1422 SCM_MISC_ERROR ("undefined port type", SCM_EOL);
1423 #endif
1424 if (SCM_PTAB_ENTRY(ptr))
1425 RECURSE (SCM_FILENAME (ptr));
1426 if (scm_ptobs[i].mark)
1427 {
1428 ptr = (scm_ptobs[i].mark) (ptr);
1429 goto_gc_mark_loop;
1430 }
1431 else
1432 return;
1433 break;
1434 case scm_tc7_smob:
1435 switch (SCM_TYP16 (ptr))
1436 { /* should be faster than going through scm_smobs */
1437 case scm_tc_free_cell:
1438 /* We have detected a free cell. This can happen if non-object data
1439 * on the C stack points into guile's heap and is scanned during
1440 * conservative marking. */
1441 #if (SCM_DEBUG_CELL_ACCESSES == 0)
1442 /* If cell debugging is disabled, there is a second situation in
1443 * which a free cell can be encountered, namely if with preemptive
1444 * threading one thread has just obtained a fresh cell and was
1445 * preempted before the cell initialization was completed. In this
1446 * case, some entries of the cell may already contain objects.
1447 * Thus, if cell debugging is disabled, free cells are scanned
1448 * conservatively. */
1449 scm_gc_mark_cell_conservatively (ptr);
1450 #else /* SCM_DEBUG_CELL_ACCESSES == 1 */
1451 /* With cell debugging enabled, a freshly obtained but not fully
1452 * initialized cell is guaranteed to be of type scm_tc16_allocated.
1453 * Thus, no conservative scanning for free cells is necessary, but
1454 * instead cells of type scm_tc16_allocated have to be scanned
1455 * conservatively. This is done in the mark function of the
1456 * scm_tc16_allocated smob type. */
1457 #endif
1458 break;
1459 case scm_tc16_big:
1460 case scm_tc16_real:
1461 case scm_tc16_complex:
1462 break;
1463 default:
1464 i = SCM_SMOBNUM (ptr);
1465 #if (SCM_DEBUG_CELL_ACCESSES == 1) || (defined (GUILE_DEBUG_FREELIST))
1466 if (!(i < scm_numsmob))
1467 SCM_MISC_ERROR ("undefined smob type", SCM_EOL);
1468 #endif
1469 if (scm_smobs[i].mark)
1470 {
1471 ptr = (scm_smobs[i].mark) (ptr);
1472 goto_gc_mark_loop;
1473 }
1474 else
1475 return;
1476 }
1477 break;
1478 default:
1479 SCM_MISC_ERROR ("unknown type", SCM_EOL);
1480 }
1481 #undef RECURSE
1482 }
1483 #undef FUNC_NAME
1484
1485 #ifndef MARK_DEPENDENCIES
1486
1487 #undef MARK
1488 #undef FNAME
1489
1490 /* And here we define `scm_gc_mark_dependencies', by including this
1491 * same file in itself.
1492 */
1493 #define MARK scm_gc_mark_dependencies
1494 #define FNAME "scm_gc_mark_dependencies"
1495 #define MARK_DEPENDENCIES
1496 #include "gc.c"
1497 #undef MARK_DEPENDENCIES
1498 #undef MARK
1499 #undef FNAME
1500
1501
1502 /* Determine whether the given value does actually represent a cell in some
1503 * heap segment. If this is the case, the number of the heap segment is
1504 * returned. Otherwise, -1 is returned. Binary search is used in order to
1505 * determine the heap segment that contains the cell.*/
1506 /* FIXME: To be used within scm_gc_mark_cell_conservatively,
1507 * scm_mark_locations and scm_cellp this function should be an inline
1508 * function. */
1509 static long int
1510 heap_segment (SCM obj)
1511 {
1512 if (!SCM_CELLP (obj))
1513 return -1;
1514 else
1515 {
1516 SCM_CELLPTR ptr = SCM2PTR (obj);
1517 unsigned long int i = 0;
1518 unsigned long int j = scm_n_heap_segs - 1;
1519
1520 if (SCM_PTR_LT (ptr, scm_heap_table[i].bounds[0]))
1521 return -1;
1522 else if (SCM_PTR_LE (scm_heap_table[j].bounds[1], ptr))
1523 return -1;
1524 else
1525 {
1526 while (i < j)
1527 {
1528 if (SCM_PTR_LT (ptr, scm_heap_table[i].bounds[1]))
1529 {
1530 break;
1531 }
1532 else if (SCM_PTR_LE (scm_heap_table[j].bounds[0], ptr))
1533 {
1534 i = j;
1535 break;
1536 }
1537 else
1538 {
1539 unsigned long int k = (i + j) / 2;
1540
1541 if (k == i)
1542 return -1;
1543 else if (SCM_PTR_LT (ptr, scm_heap_table[k].bounds[1]))
1544 {
1545 j = k;
1546 ++i;
1547 if (SCM_PTR_LT (ptr, scm_heap_table[i].bounds[0]))
1548 return -1;
1549 }
1550 else if (SCM_PTR_LE (scm_heap_table[k].bounds[0], ptr))
1551 {
1552 i = k;
1553 --j;
1554 if (SCM_PTR_LE (scm_heap_table[j].bounds[1], ptr))
1555 return -1;
1556 }
1557 }
1558 }
1559
1560 if (!DOUBLECELL_ALIGNED_P (obj) && scm_heap_table[i].span == 2)
1561 return -1;
1562 else if (SCM_GC_IN_CARD_HEADERP (ptr))
1563 return -1;
1564 else
1565 return i;
1566 }
1567 }
1568 }
1569
1570
1571 /* Mark the entries of a cell conservatively. The given cell is known to be
1572 * on the heap. Still we have to determine its heap segment in order to
1573 * figure out whether it is a single or a double cell. Then, each of the cell
1574 * elements itself is checked and potentially marked. */
1575 void
1576 scm_gc_mark_cell_conservatively (SCM cell)
1577 {
1578 unsigned long int cell_segment = heap_segment (cell);
1579 unsigned int span = scm_heap_table[cell_segment].span;
1580 unsigned int i;
1581
1582 for (i = 1; i != span * 2; ++i)
1583 {
1584 SCM obj = SCM_CELL_OBJECT (cell, i);
1585 long int obj_segment = heap_segment (obj);
1586 if (obj_segment >= 0)
1587 scm_gc_mark (obj);
1588 }
1589 }
1590
1591
1592 /* Mark a region conservatively */
1593 void
1594 scm_mark_locations (SCM_STACKITEM x[], unsigned long n)
1595 {
1596 unsigned long m;
1597
1598 for (m = 0; m < n; ++m)
1599 {
1600 SCM obj = * (SCM *) &x[m];
1601 long int segment = heap_segment (obj);
1602 if (segment >= 0)
1603 scm_gc_mark (obj);
1604 }
1605 }
1606
1607
1608 /* The function scm_cellp determines whether an SCM value can be regarded as a
1609 * pointer to a cell on the heap.
1610 */
1611 int
1612 scm_cellp (SCM value)
1613 {
1614 long int segment = heap_segment (value);
1615 return (segment >= 0);
1616 }
1617
1618
1619 static void
1620 gc_sweep_freelist_start (scm_t_freelist *freelist)
1621 {
1622 freelist->cells = SCM_EOL;
1623 freelist->left_to_collect = freelist->cluster_size;
1624 freelist->clusters_allocated = 0;
1625 freelist->clusters = SCM_EOL;
1626 freelist->clustertail = &freelist->clusters;
1627 freelist->collected_1 = freelist->collected;
1628 freelist->collected = 0;
1629 }
1630
1631 static void
1632 gc_sweep_freelist_finish (scm_t_freelist *freelist)
1633 {
1634 long collected;
1635 *freelist->clustertail = freelist->cells;
1636 if (!SCM_NULLP (freelist->cells))
1637 {
1638 SCM c = freelist->cells;
1639 SCM_SET_CELL_WORD_0 (c, SCM_FREE_CELL_CDR (c));
1640 SCM_SET_CELL_WORD_1 (c, SCM_EOL);
1641 freelist->collected +=
1642 freelist->span * (freelist->cluster_size - freelist->left_to_collect);
1643 }
1644 scm_gc_cells_collected += freelist->collected;
1645
1646 /* Although freelist->min_yield is used to test freelist->collected
1647 * (which is the local GC yield for freelist), it is adjusted so
1648 * that *total* yield is freelist->min_yield_fraction of total heap
1649 * size. This means that a too low yield is compensated by more
1650 * heap on the list which is currently doing most work, which is
1651 * just what we want.
1652 */
1653 collected = SCM_MAX (freelist->collected_1, freelist->collected);
1654 freelist->grow_heap_p = (collected < freelist->min_yield);
1655 }
1656
1657 #define NEXT_DATA_CELL(ptr, span) \
1658 do { \
1659 scm_cell *nxt__ = CELL_UP ((char *) (ptr) + 1, (span)); \
1660 (ptr) = (SCM_GC_IN_CARD_HEADERP (nxt__) ? \
1661 CELL_UP (SCM_GC_CELL_CARD (nxt__) + SCM_GC_CARD_N_HEADER_CELLS, span) \
1662 : nxt__); \
1663 } while (0)
1664
1665 void
1666 scm_gc_sweep ()
1667 #define FUNC_NAME "scm_gc_sweep"
1668 {
1669 register SCM_CELLPTR ptr;
1670 register SCM nfreelist;
1671 register scm_t_freelist *freelist;
1672 register unsigned long m;
1673 register int span;
1674 size_t i;
1675 size_t seg_size;
1676
1677 m = 0;
1678
1679 gc_sweep_freelist_start (&scm_master_freelist);
1680 gc_sweep_freelist_start (&scm_master_freelist2);
1681
1682 for (i = 0; i < scm_n_heap_segs; i++)
1683 {
1684 register long left_to_collect;
1685 register size_t j;
1686
1687 /* Unmarked cells go onto the front of the freelist this heap
1688 segment points to. Rather than updating the real freelist
1689 pointer as we go along, we accumulate the new head in
1690 nfreelist. Then, if it turns out that the entire segment is
1691 free, we free (i.e., malloc's free) the whole segment, and
1692 simply don't assign nfreelist back into the real freelist. */
1693 freelist = scm_heap_table[i].freelist;
1694 nfreelist = freelist->cells;
1695 left_to_collect = freelist->left_to_collect;
1696 span = scm_heap_table[i].span;
1697
1698 ptr = CELL_UP (scm_heap_table[i].bounds[0], span);
1699 seg_size = CELL_DN (scm_heap_table[i].bounds[1], span) - ptr;
1700
1701 /* use only data cells in seg_size */
1702 seg_size = (seg_size / SCM_GC_CARD_N_CELLS) * (SCM_GC_CARD_N_DATA_CELLS / span) * span;
1703
1704 scm_gc_cells_swept += seg_size;
1705
1706 for (j = seg_size + span; j -= span; ptr += span)
1707 {
1708 SCM scmptr;
1709
1710 if (SCM_GC_IN_CARD_HEADERP (ptr))
1711 {
1712 SCM_CELLPTR nxt;
1713
1714 /* cheat here */
1715 nxt = ptr;
1716 NEXT_DATA_CELL (nxt, span);
1717 j += span;
1718
1719 ptr = nxt - span;
1720 continue;
1721 }
1722
1723 scmptr = PTR2SCM (ptr);
1724
1725 if (SCM_GCMARKP (scmptr))
1726 continue;
1727
1728 switch SCM_TYP7 (scmptr)
1729 {
1730 case scm_tcs_struct:
1731 {
1732 /* Structs need to be freed in a special order.
1733 * This is handled by GC C hooks in struct.c.
1734 */
1735 SCM_SET_STRUCT_GC_CHAIN (scmptr, scm_structs_to_free);
1736 scm_structs_to_free = scmptr;
1737 }
1738 continue;
1739 case scm_tcs_cons_imcar:
1740 case scm_tcs_cons_nimcar:
1741 case scm_tcs_closures:
1742 case scm_tc7_pws:
1743 break;
1744 case scm_tc7_wvect:
1745 case scm_tc7_vector:
1746 {
1747 unsigned long int length = SCM_VECTOR_LENGTH (scmptr);
1748 if (length > 0)
1749 {
1750 m += length * sizeof (scm_t_bits);
1751 scm_must_free (SCM_VECTOR_BASE (scmptr));
1752 }
1753 break;
1754 }
1755 #ifdef CCLO
1756 case scm_tc7_cclo:
1757 m += (SCM_CCLO_LENGTH (scmptr) * sizeof (SCM));
1758 scm_must_free (SCM_CCLO_BASE (scmptr));
1759 break;
1760 #endif
1761 #ifdef HAVE_ARRAYS
1762 case scm_tc7_bvect:
1763 {
1764 unsigned long int length = SCM_BITVECTOR_LENGTH (scmptr);
1765 if (length > 0)
1766 {
1767 m += sizeof (long) * ((length + SCM_LONG_BIT - 1) / SCM_LONG_BIT);
1768 scm_must_free (SCM_BITVECTOR_BASE (scmptr));
1769 }
1770 }
1771 break;
1772 case scm_tc7_byvect:
1773 case scm_tc7_ivect:
1774 case scm_tc7_uvect:
1775 case scm_tc7_svect:
1776 #ifdef HAVE_LONG_LONGS
1777 case scm_tc7_llvect:
1778 #endif
1779 case scm_tc7_fvect:
1780 case scm_tc7_dvect:
1781 case scm_tc7_cvect:
1782 m += SCM_UVECTOR_LENGTH (scmptr) * scm_uniform_element_size (scmptr);
1783 scm_must_free (SCM_UVECTOR_BASE (scmptr));
1784 break;
1785 #endif
1786 case scm_tc7_substring:
1787 break;
1788 case scm_tc7_string:
1789 m += SCM_STRING_LENGTH (scmptr) + 1;
1790 scm_must_free (SCM_STRING_CHARS (scmptr));
1791 break;
1792 case scm_tc7_symbol:
1793 m += SCM_SYMBOL_LENGTH (scmptr) + 1;
1794 scm_must_free (SCM_SYMBOL_CHARS (scmptr));
1795 break;
1796 case scm_tcs_subrs:
1797 /* the various "subrs" (primitives) are never freed */
1798 continue;
1799 case scm_tc7_port:
1800 if SCM_OPENP (scmptr)
1801 {
1802 int k = SCM_PTOBNUM (scmptr);
1803 #if (SCM_DEBUG_CELL_ACCESSES == 1) || (defined (GUILE_DEBUG_FREELIST))
1804 if (!(k < scm_numptob))
1805 SCM_MISC_ERROR ("undefined port type", SCM_EOL);
1806 #endif
1807 /* Keep "revealed" ports alive. */
1808 if (scm_revealed_count (scmptr) > 0)
1809 continue;
1810 /* Yes, I really do mean scm_ptobs[k].free */
1811 /* rather than ftobs[k].close. .close */
1812 /* is for explicit CLOSE-PORT by user */
1813 m += (scm_ptobs[k].free) (scmptr);
1814 SCM_SETSTREAM (scmptr, 0);
1815 scm_remove_from_port_table (scmptr);
1816 scm_gc_ports_collected++;
1817 SCM_CLR_PORT_OPEN_FLAG (scmptr);
1818 }
1819 break;
1820 case scm_tc7_smob:
1821 switch SCM_TYP16 (scmptr)
1822 {
1823 case scm_tc_free_cell:
1824 case scm_tc16_real:
1825 break;
1826 #ifdef SCM_BIGDIG
1827 case scm_tc16_big:
1828 m += (SCM_NUMDIGS (scmptr) * SCM_BITSPERDIG / SCM_CHAR_BIT);
1829 scm_must_free (SCM_BDIGITS (scmptr));
1830 break;
1831 #endif /* def SCM_BIGDIG */
1832 case scm_tc16_complex:
1833 m += sizeof (scm_t_complex);
1834 scm_must_free (SCM_COMPLEX_MEM (scmptr));
1835 break;
1836 default:
1837 {
1838 int k;
1839 k = SCM_SMOBNUM (scmptr);
1840 #if (SCM_DEBUG_CELL_ACCESSES == 1) || (defined (GUILE_DEBUG_FREELIST))
1841 if (!(k < scm_numsmob))
1842 SCM_MISC_ERROR ("undefined smob type", SCM_EOL);
1843 #endif
1844 if (scm_smobs[k].free)
1845 m += (scm_smobs[k].free) (scmptr);
1846 break;
1847 }
1848 }
1849 break;
1850 default:
1851 SCM_MISC_ERROR ("unknown type", SCM_EOL);
1852 }
1853
1854 if (!--left_to_collect)
1855 {
1856 SCM_SET_CELL_WORD_0 (scmptr, nfreelist);
1857 *freelist->clustertail = scmptr;
1858 freelist->clustertail = SCM_CDRLOC (scmptr);
1859
1860 nfreelist = SCM_EOL;
1861 freelist->collected += span * freelist->cluster_size;
1862 left_to_collect = freelist->cluster_size;
1863 }
1864 else
1865 {
1866 /* Stick the new cell on the front of nfreelist. It's
1867 critical that we mark this cell as freed; otherwise, the
1868 conservative collector might trace it as some other type
1869 of object. */
1870 SCM_SET_CELL_TYPE (scmptr, scm_tc_free_cell);
1871 SCM_SET_FREE_CELL_CDR (scmptr, nfreelist);
1872 nfreelist = scmptr;
1873 }
1874 }
1875
1876 #ifdef GC_FREE_SEGMENTS
1877 if (n == seg_size)
1878 {
1879 register long j;
1880
1881 freelist->heap_size -= seg_size;
1882 free ((char *) scm_heap_table[i].bounds[0]);
1883 scm_heap_table[i].bounds[0] = 0;
1884 for (j = i + 1; j < scm_n_heap_segs; j++)
1885 scm_heap_table[j - 1] = scm_heap_table[j];
1886 scm_n_heap_segs -= 1;
1887 i--; /* We need to scan the segment just moved. */
1888 }
1889 else
1890 #endif /* ifdef GC_FREE_SEGMENTS */
1891 {
1892 /* Update the real freelist pointer to point to the head of
1893 the list of free cells we've built for this segment. */
1894 freelist->cells = nfreelist;
1895 freelist->left_to_collect = left_to_collect;
1896 }
1897
1898 #ifdef GUILE_DEBUG_FREELIST
1899 scm_map_free_list ();
1900 #endif
1901 }
1902
1903 gc_sweep_freelist_finish (&scm_master_freelist);
1904 gc_sweep_freelist_finish (&scm_master_freelist2);
1905
1906 /* When we move to POSIX threads private freelists should probably
1907 be GC-protected instead. */
1908 scm_freelist = SCM_EOL;
1909 scm_freelist2 = SCM_EOL;
1910
1911 scm_cells_allocated = (SCM_HEAP_SIZE - scm_gc_cells_collected);
1912 scm_gc_yield -= scm_cells_allocated;
1913
1914 if (scm_mallocated < m)
1915 /* The byte count of allocated objects has underflowed. This is
1916 probably because you forgot to report the sizes of objects you
1917 have allocated, by calling scm_done_malloc or some such. When
1918 the GC freed them, it subtracted their size from
1919 scm_mallocated, which underflowed. */
1920 abort ();
1921
1922 scm_mallocated -= m;
1923 scm_gc_malloc_collected = m;
1924 }
1925 #undef FUNC_NAME
1926
1927
1928 \f
1929 /* {Front end to malloc}
1930 *
1931 * scm_must_malloc, scm_must_realloc, scm_must_free, scm_done_malloc,
1932 * scm_done_free
1933 *
1934 * These functions provide services comparable to malloc, realloc, and
1935 * free. They should be used when allocating memory that will be under
1936 * control of the garbage collector, i.e., if the memory may be freed
1937 * during garbage collection.
1938 */
1939
1940 /* scm_must_malloc
1941 * Return newly malloced storage or throw an error.
1942 *
1943 * The parameter WHAT is a string for error reporting.
1944 * If the threshold scm_mtrigger will be passed by this
1945 * allocation, or if the first call to malloc fails,
1946 * garbage collect -- on the presumption that some objects
1947 * using malloced storage may be collected.
1948 *
1949 * The limit scm_mtrigger may be raised by this allocation.
1950 */
1951 void *
1952 scm_must_malloc (size_t size, const char *what)
1953 {
1954 void *ptr;
1955 unsigned long nm = scm_mallocated + size;
1956
1957 if (nm < size)
1958 /* The byte count of allocated objects has overflowed. This is
1959 probably because you forgot to report the correct size of freed
1960 memory in some of your smob free methods. */
1961 abort ();
1962
1963 if (nm <= scm_mtrigger)
1964 {
1965 SCM_SYSCALL (ptr = malloc (size));
1966 if (NULL != ptr)
1967 {
1968 scm_mallocated = nm;
1969 #ifdef GUILE_DEBUG_MALLOC
1970 scm_malloc_register (ptr, what);
1971 #endif
1972 return ptr;
1973 }
1974 }
1975
1976 scm_igc (what);
1977
1978 nm = scm_mallocated + size;
1979
1980 if (nm < size)
1981 /* The byte count of allocated objects has overflowed. This is
1982 probably because you forgot to report the correct size of freed
1983 memory in some of your smob free methods. */
1984 abort ();
1985
1986 SCM_SYSCALL (ptr = malloc (size));
1987 if (NULL != ptr)
1988 {
1989 scm_mallocated = nm;
1990 if (nm > scm_mtrigger - SCM_MTRIGGER_HYSTERESIS) {
1991 if (nm > scm_mtrigger)
1992 scm_mtrigger = nm + nm / 2;
1993 else
1994 scm_mtrigger += scm_mtrigger / 2;
1995 }
1996 #ifdef GUILE_DEBUG_MALLOC
1997 scm_malloc_register (ptr, what);
1998 #endif
1999
2000 return ptr;
2001 }
2002
2003 scm_memory_error (what);
2004 }
2005
2006
2007 /* scm_must_realloc
2008 * is similar to scm_must_malloc.
2009 */
2010 void *
2011 scm_must_realloc (void *where,
2012 size_t old_size,
2013 size_t size,
2014 const char *what)
2015 {
2016 void *ptr;
2017 unsigned long nm;
2018
2019 if (size <= old_size)
2020 return where;
2021
2022 nm = scm_mallocated + size - old_size;
2023
2024 if (nm < (size - old_size))
2025 /* The byte count of allocated objects has overflowed. This is
2026 probably because you forgot to report the correct size of freed
2027 memory in some of your smob free methods. */
2028 abort ();
2029
2030 if (nm <= scm_mtrigger)
2031 {
2032 SCM_SYSCALL (ptr = realloc (where, size));
2033 if (NULL != ptr)
2034 {
2035 scm_mallocated = nm;
2036 #ifdef GUILE_DEBUG_MALLOC
2037 scm_malloc_reregister (where, ptr, what);
2038 #endif
2039 return ptr;
2040 }
2041 }
2042
2043 scm_igc (what);
2044
2045 nm = scm_mallocated + size - old_size;
2046
2047 if (nm < (size - old_size))
2048 /* The byte count of allocated objects has overflowed. This is
2049 probably because you forgot to report the correct size of freed
2050 memory in some of your smob free methods. */
2051 abort ();
2052
2053 SCM_SYSCALL (ptr = realloc (where, size));
2054 if (NULL != ptr)
2055 {
2056 scm_mallocated = nm;
2057 if (nm > scm_mtrigger - SCM_MTRIGGER_HYSTERESIS) {
2058 if (nm > scm_mtrigger)
2059 scm_mtrigger = nm + nm / 2;
2060 else
2061 scm_mtrigger += scm_mtrigger / 2;
2062 }
2063 #ifdef GUILE_DEBUG_MALLOC
2064 scm_malloc_reregister (where, ptr, what);
2065 #endif
2066 return ptr;
2067 }
2068
2069 scm_memory_error (what);
2070 }
2071
2072 char *
2073 scm_must_strndup (const char *str, size_t length)
2074 {
2075 char * dst = scm_must_malloc (length + 1, "scm_must_strndup");
2076 memcpy (dst, str, length);
2077 dst[length] = 0;
2078 return dst;
2079 }
2080
2081 char *
2082 scm_must_strdup (const char *str)
2083 {
2084 return scm_must_strndup (str, strlen (str));
2085 }
2086
2087 void
2088 scm_must_free (void *obj)
2089 #define FUNC_NAME "scm_must_free"
2090 {
2091 #ifdef GUILE_DEBUG_MALLOC
2092 scm_malloc_unregister (obj);
2093 #endif
2094 if (obj)
2095 free (obj);
2096 else
2097 SCM_MISC_ERROR ("freeing NULL pointer", SCM_EOL);
2098 }
2099 #undef FUNC_NAME
2100
2101
2102 /* Announce that there has been some malloc done that will be freed
2103 * during gc. A typical use is for a smob that uses some malloced
2104 * memory but can not get it from scm_must_malloc (for whatever
2105 * reason). When a new object of this smob is created you call
2106 * scm_done_malloc with the size of the object. When your smob free
2107 * function is called, be sure to include this size in the return
2108 * value.
2109 *
2110 * If you can't actually free the memory in the smob free function,
2111 * for whatever reason (like reference counting), you still can (and
2112 * should) report the amount of memory freed when you actually free it.
2113 * Do it by calling scm_done_malloc with the _negated_ size. Clever,
2114 * eh? Or even better, call scm_done_free. */
2115
2116 void
2117 scm_done_malloc (long size)
2118 {
2119 if (size < 0) {
2120 if (scm_mallocated < size)
2121 /* The byte count of allocated objects has underflowed. This is
2122 probably because you forgot to report the sizes of objects you
2123 have allocated, by calling scm_done_malloc or some such. When
2124 the GC freed them, it subtracted their size from
2125 scm_mallocated, which underflowed. */
2126 abort ();
2127 } else {
2128 unsigned long nm = scm_mallocated + size;
2129 if (nm < size)
2130 /* The byte count of allocated objects has overflowed. This is
2131 probably because you forgot to report the correct size of freed
2132 memory in some of your smob free methods. */
2133 abort ();
2134 }
2135
2136 scm_mallocated += size;
2137
2138 if (scm_mallocated > scm_mtrigger)
2139 {
2140 scm_igc ("foreign mallocs");
2141 if (scm_mallocated > scm_mtrigger - SCM_MTRIGGER_HYSTERESIS)
2142 {
2143 if (scm_mallocated > scm_mtrigger)
2144 scm_mtrigger = scm_mallocated + scm_mallocated / 2;
2145 else
2146 scm_mtrigger += scm_mtrigger / 2;
2147 }
2148 }
2149 }
2150
2151 void
2152 scm_done_free (long size)
2153 {
2154 if (size >= 0) {
2155 if (scm_mallocated < size)
2156 /* The byte count of allocated objects has underflowed. This is
2157 probably because you forgot to report the sizes of objects you
2158 have allocated, by calling scm_done_malloc or some such. When
2159 the GC freed them, it subtracted their size from
2160 scm_mallocated, which underflowed. */
2161 abort ();
2162 } else {
2163 unsigned long nm = scm_mallocated + size;
2164 if (nm < size)
2165 /* The byte count of allocated objects has overflowed. This is
2166 probably because you forgot to report the correct size of freed
2167 memory in some of your smob free methods. */
2168 abort ();
2169 }
2170
2171 scm_mallocated -= size;
2172 }
2173
2174
2175 \f
2176 /* {Heap Segments}
2177 *
2178 * Each heap segment is an array of objects of a particular size.
2179 * Every segment has an associated (possibly shared) freelist.
2180 * A table of segment records is kept that records the upper and
2181 * lower extents of the segment; this is used during the conservative
2182 * phase of gc to identify probably gc roots (because they point
2183 * into valid segments at reasonable offsets). */
2184
2185 /* scm_expmem
2186 * is true if the first segment was smaller than INIT_HEAP_SEG.
2187 * If scm_expmem is set to one, subsequent segment allocations will
2188 * allocate segments of size SCM_EXPHEAP(scm_heap_size).
2189 */
2190 int scm_expmem = 0;
2191
2192 size_t scm_max_segment_size;
2193
2194 /* scm_heap_org
2195 * is the lowest base address of any heap segment.
2196 */
2197 SCM_CELLPTR scm_heap_org;
2198
2199 scm_t_heap_seg_data * scm_heap_table = 0;
2200 static size_t heap_segment_table_size = 0;
2201 size_t scm_n_heap_segs = 0;
2202
2203 /* init_heap_seg
2204 * initializes a new heap segment and returns the number of objects it contains.
2205 *
2206 * The segment origin and segment size in bytes are input parameters.
2207 * The freelist is both input and output.
2208 *
2209 * This function presumes that the scm_heap_table has already been expanded
2210 * to accomodate a new segment record and that the markbit space was reserved
2211 * for all the cards in this segment.
2212 */
2213
2214 #define INIT_CARD(card, span) \
2215 do { \
2216 SCM_GC_SET_CARD_BVEC (card, get_bvec ()); \
2217 if ((span) == 2) \
2218 SCM_GC_SET_CARD_DOUBLECELL (card); \
2219 } while (0)
2220
2221 static size_t
2222 init_heap_seg (SCM_CELLPTR seg_org, size_t size, scm_t_freelist *freelist)
2223 {
2224 register SCM_CELLPTR ptr;
2225 SCM_CELLPTR seg_end;
2226 size_t new_seg_index;
2227 ptrdiff_t n_new_cells;
2228 int span = freelist->span;
2229
2230 if (seg_org == NULL)
2231 return 0;
2232
2233 /* Align the begin ptr up.
2234 */
2235 ptr = SCM_GC_CARD_UP (seg_org);
2236
2237 /* Compute the ceiling on valid object pointers w/in this segment.
2238 */
2239 seg_end = SCM_GC_CARD_DOWN ((char *)seg_org + size);
2240
2241 /* Find the right place and insert the segment record.
2242 */
2243 new_seg_index = 0;
2244 while (new_seg_index < scm_n_heap_segs
2245 && SCM_PTR_LE (scm_heap_table[new_seg_index].bounds[0], seg_org))
2246 new_seg_index++;
2247
2248 {
2249 int i;
2250 for (i = scm_n_heap_segs; i > new_seg_index; --i)
2251 scm_heap_table[i] = scm_heap_table[i - 1];
2252 }
2253
2254 ++scm_n_heap_segs;
2255
2256 scm_heap_table[new_seg_index].span = span;
2257 scm_heap_table[new_seg_index].freelist = freelist;
2258 scm_heap_table[new_seg_index].bounds[0] = ptr;
2259 scm_heap_table[new_seg_index].bounds[1] = seg_end;
2260
2261 /*n_new_cells*/
2262 n_new_cells = seg_end - ptr;
2263
2264 freelist->heap_size += n_new_cells;
2265
2266 /* Partition objects in this segment into clusters */
2267 {
2268 SCM clusters;
2269 SCM *clusterp = &clusters;
2270
2271 NEXT_DATA_CELL (ptr, span);
2272 while (ptr < seg_end)
2273 {
2274 scm_cell *nxt = ptr;
2275 scm_cell *prv = NULL;
2276 scm_cell *last_card = NULL;
2277 int n_data_cells = (SCM_GC_CARD_N_DATA_CELLS / span) * SCM_CARDS_PER_CLUSTER - 1;
2278 NEXT_DATA_CELL(nxt, span);
2279
2280 /* Allocate cluster spine
2281 */
2282 *clusterp = PTR2SCM (ptr);
2283 SCM_SETCAR (*clusterp, PTR2SCM (nxt));
2284 clusterp = SCM_CDRLOC (*clusterp);
2285 ptr = nxt;
2286
2287 while (n_data_cells--)
2288 {
2289 scm_cell *card = SCM_GC_CELL_CARD (ptr);
2290 SCM scmptr = PTR2SCM (ptr);
2291 nxt = ptr;
2292 NEXT_DATA_CELL (nxt, span);
2293 prv = ptr;
2294
2295 if (card != last_card)
2296 {
2297 INIT_CARD (card, span);
2298 last_card = card;
2299 }
2300
2301 SCM_SET_CELL_TYPE (scmptr, scm_tc_free_cell);
2302 SCM_SET_FREE_CELL_CDR (scmptr, PTR2SCM (nxt));
2303
2304 ptr = nxt;
2305 }
2306
2307 SCM_SET_FREE_CELL_CDR (PTR2SCM (prv), SCM_EOL);
2308 }
2309
2310 /* sanity check */
2311 {
2312 scm_cell *ref = seg_end;
2313 NEXT_DATA_CELL (ref, span);
2314 if (ref != ptr)
2315 /* [cmm] looks like the segment size doesn't divide cleanly by
2316 cluster size. bad cmm! */
2317 abort();
2318 }
2319
2320 /* Patch up the last cluster pointer in the segment
2321 * to join it to the input freelist.
2322 */
2323 *clusterp = freelist->clusters;
2324 freelist->clusters = clusters;
2325 }
2326
2327 #ifdef DEBUGINFO
2328 fprintf (stderr, "H");
2329 #endif
2330 return size;
2331 }
2332
2333 static size_t
2334 round_to_cluster_size (scm_t_freelist *freelist, size_t len)
2335 {
2336 size_t cluster_size_in_bytes = CLUSTER_SIZE_IN_BYTES (freelist);
2337
2338 return
2339 (len + cluster_size_in_bytes - 1) / cluster_size_in_bytes * cluster_size_in_bytes
2340 + ALIGNMENT_SLACK (freelist);
2341 }
2342
2343 static void
2344 alloc_some_heap (scm_t_freelist *freelist, policy_on_error error_policy)
2345 #define FUNC_NAME "alloc_some_heap"
2346 {
2347 SCM_CELLPTR ptr;
2348 size_t len;
2349
2350 if (scm_gc_heap_lock)
2351 {
2352 /* Critical code sections (such as the garbage collector) aren't
2353 * supposed to add heap segments.
2354 */
2355 fprintf (stderr, "alloc_some_heap: Can not extend locked heap.\n");
2356 abort ();
2357 }
2358
2359 if (scm_n_heap_segs == heap_segment_table_size)
2360 {
2361 /* We have to expand the heap segment table to have room for the new
2362 * segment. Do not yet increment scm_n_heap_segs -- that is done by
2363 * init_heap_seg only if the allocation of the segment itself succeeds.
2364 */
2365 size_t new_table_size = scm_n_heap_segs + 1;
2366 size_t size = new_table_size * sizeof (scm_t_heap_seg_data);
2367 scm_t_heap_seg_data *new_heap_table;
2368
2369 SCM_SYSCALL (new_heap_table = ((scm_t_heap_seg_data *)
2370 realloc ((char *)scm_heap_table, size)));
2371 if (!new_heap_table)
2372 {
2373 if (error_policy == abort_on_error)
2374 {
2375 fprintf (stderr, "alloc_some_heap: Could not grow heap segment table.\n");
2376 abort ();
2377 }
2378 else
2379 {
2380 return;
2381 }
2382 }
2383 else
2384 {
2385 scm_heap_table = new_heap_table;
2386 heap_segment_table_size = new_table_size;
2387 }
2388 }
2389
2390 /* Pick a size for the new heap segment.
2391 * The rule for picking the size of a segment is explained in
2392 * gc.h
2393 */
2394 {
2395 /* Assure that the new segment is predicted to be large enough.
2396 *
2397 * New yield should at least equal GC fraction of new heap size, i.e.
2398 *
2399 * y + dh > f * (h + dh)
2400 *
2401 * y : yield
2402 * f : min yield fraction
2403 * h : heap size
2404 * dh : size of new heap segment
2405 *
2406 * This gives dh > (f * h - y) / (1 - f)
2407 */
2408 int f = freelist->min_yield_fraction;
2409 unsigned long h = SCM_HEAP_SIZE;
2410 size_t min_cells = (f * h - 100 * (long) scm_gc_yield) / (99 - f);
2411 len = SCM_EXPHEAP (freelist->heap_size);
2412 #ifdef DEBUGINFO
2413 fprintf (stderr, "(%ld < %ld)", (long) len, (long) min_cells);
2414 #endif
2415 if (len < min_cells)
2416 len = min_cells + freelist->cluster_size;
2417 len *= sizeof (scm_cell);
2418 /* force new sampling */
2419 freelist->collected = LONG_MAX;
2420 }
2421
2422 if (len > scm_max_segment_size)
2423 len = scm_max_segment_size;
2424
2425 {
2426 size_t smallest;
2427
2428 smallest = CLUSTER_SIZE_IN_BYTES (freelist);
2429
2430 if (len < smallest)
2431 len = smallest;
2432
2433 /* Allocate with decaying ambition. */
2434 while ((len >= SCM_MIN_HEAP_SEG_SIZE)
2435 && (len >= smallest))
2436 {
2437 size_t rounded_len = round_to_cluster_size (freelist, len);
2438 SCM_SYSCALL (ptr = (SCM_CELLPTR) malloc (rounded_len));
2439 if (ptr)
2440 {
2441 init_heap_seg (ptr, rounded_len, freelist);
2442 return;
2443 }
2444 len /= 2;
2445 }
2446 }
2447
2448 if (error_policy == abort_on_error)
2449 {
2450 fprintf (stderr, "alloc_some_heap: Could not grow heap.\n");
2451 abort ();
2452 }
2453 }
2454 #undef FUNC_NAME
2455
2456 \f
2457 /* {GC Protection Helper Functions}
2458 */
2459
2460
2461 /*
2462 * If within a function you need to protect one or more scheme objects from
2463 * garbage collection, pass them as parameters to one of the
2464 * scm_remember_upto_here* functions below. These functions don't do
2465 * anything, but since the compiler does not know that they are actually
2466 * no-ops, it will generate code that calls these functions with the given
2467 * parameters. Therefore, you can be sure that the compiler will keep those
2468 * scheme values alive (on the stack or in a register) up to the point where
2469 * scm_remember_upto_here* is called. In other words, place the call to
2470 * scm_remember_upto_here* _behind_ the last code in your function, that
2471 * depends on the scheme object to exist.
2472 *
2473 * Example: We want to make sure, that the string object str does not get
2474 * garbage collected during the execution of 'some_function', because
2475 * otherwise the characters belonging to str would be freed and
2476 * 'some_function' might access freed memory. To make sure that the compiler
2477 * keeps str alive on the stack or in a register such that it is visible to
2478 * the conservative gc we add the call to scm_remember_upto_here_1 _after_ the
2479 * call to 'some_function'. Note that this would not be necessary if str was
2480 * used anyway after the call to 'some_function'.
2481 * char *chars = SCM_STRING_CHARS (str);
2482 * some_function (chars);
2483 * scm_remember_upto_here_1 (str); // str will be alive up to this point.
2484 */
2485
2486 void
2487 scm_remember_upto_here_1 (SCM obj SCM_UNUSED)
2488 {
2489 /* Empty. Protects a single object from garbage collection. */
2490 }
2491
2492 void
2493 scm_remember_upto_here_2 (SCM obj1 SCM_UNUSED, SCM obj2 SCM_UNUSED)
2494 {
2495 /* Empty. Protects two objects from garbage collection. */
2496 }
2497
2498 void
2499 scm_remember_upto_here (SCM obj SCM_UNUSED, ...)
2500 {
2501 /* Empty. Protects any number of objects from garbage collection. */
2502 }
2503
2504
2505 #if (SCM_DEBUG_DEPRECATED == 0)
2506
2507 void
2508 scm_remember (SCM *ptr)
2509 {
2510 scm_c_issue_deprecation_warning ("`scm_remember' is deprecated. "
2511 "Use the `scm_remember_upto_here*' family of functions instead.");
2512 }
2513
2514 SCM
2515 scm_protect_object (SCM obj)
2516 {
2517 scm_c_issue_deprecation_warning ("`scm_protect_object' is deprecated. "
2518 "Use `scm_gc_protect_object' instead.");
2519 return scm_gc_protect_object (obj);
2520 }
2521
2522 SCM
2523 scm_unprotect_object (SCM obj)
2524 {
2525 scm_c_issue_deprecation_warning ("`scm_unprotect_object' is deprecated. "
2526 "Use `scm_gc_unprotect_object' instead.");
2527 return scm_gc_unprotect_object (obj);
2528 }
2529
2530 #endif /* SCM_DEBUG_DEPRECATED == 0 */
2531
2532 /*
2533 These crazy functions prevent garbage collection
2534 of arguments after the first argument by
2535 ensuring they remain live throughout the
2536 function because they are used in the last
2537 line of the code block.
2538 It'd be better to have a nice compiler hint to
2539 aid the conservative stack-scanning GC. --03/09/00 gjb */
2540 SCM
2541 scm_return_first (SCM elt, ...)
2542 {
2543 return elt;
2544 }
2545
2546 int
2547 scm_return_first_int (int i, ...)
2548 {
2549 return i;
2550 }
2551
2552
2553 SCM
2554 scm_permanent_object (SCM obj)
2555 {
2556 SCM_REDEFER_INTS;
2557 scm_permobjs = scm_cons (obj, scm_permobjs);
2558 SCM_REALLOW_INTS;
2559 return obj;
2560 }
2561
2562
2563 /* Protect OBJ from the garbage collector. OBJ will not be freed, even if all
2564 other references are dropped, until the object is unprotected by calling
2565 scm_gc_unprotect_object (OBJ). Calls to scm_gc_protect/unprotect_object nest,
2566 i. e. it is possible to protect the same object several times, but it is
2567 necessary to unprotect the object the same number of times to actually get
2568 the object unprotected. It is an error to unprotect an object more often
2569 than it has been protected before. The function scm_protect_object returns
2570 OBJ.
2571 */
2572
2573 /* Implementation note: For every object X, there is a counter which
2574 scm_gc_protect_object(X) increments and scm_gc_unprotect_object(X) decrements.
2575 */
2576
2577 SCM
2578 scm_gc_protect_object (SCM obj)
2579 {
2580 SCM handle;
2581
2582 /* This critical section barrier will be replaced by a mutex. */
2583 SCM_REDEFER_INTS;
2584
2585 handle = scm_hashq_create_handle_x (scm_protects, obj, SCM_MAKINUM (0));
2586 SCM_SETCDR (handle, scm_sum (SCM_CDR (handle), SCM_MAKINUM (1)));
2587
2588 SCM_REALLOW_INTS;
2589
2590 return obj;
2591 }
2592
2593
2594 /* Remove any protection for OBJ established by a prior call to
2595 scm_protect_object. This function returns OBJ.
2596
2597 See scm_protect_object for more information. */
2598 SCM
2599 scm_gc_unprotect_object (SCM obj)
2600 {
2601 SCM handle;
2602
2603 /* This critical section barrier will be replaced by a mutex. */
2604 SCM_REDEFER_INTS;
2605
2606 handle = scm_hashq_get_handle (scm_protects, obj);
2607
2608 if (SCM_FALSEP (handle))
2609 {
2610 fprintf (stderr, "scm_unprotect_object called on unprotected object\n");
2611 abort ();
2612 }
2613 else
2614 {
2615 SCM count = scm_difference (SCM_CDR (handle), SCM_MAKINUM (1));
2616 if (SCM_EQ_P (count, SCM_MAKINUM (0)))
2617 scm_hashq_remove_x (scm_protects, obj);
2618 else
2619 SCM_SETCDR (handle, count);
2620 }
2621
2622 SCM_REALLOW_INTS;
2623
2624 return obj;
2625 }
2626
2627 void
2628 scm_gc_register_root (SCM *p)
2629 {
2630 SCM handle;
2631 SCM key = scm_long2num ((long) p);
2632
2633 /* This critical section barrier will be replaced by a mutex. */
2634 SCM_REDEFER_INTS;
2635
2636 handle = scm_hashv_create_handle_x (scm_gc_registered_roots, key, SCM_MAKINUM (0));
2637 SCM_SETCDR (handle, scm_sum (SCM_CDR (handle), SCM_MAKINUM (1)));
2638
2639 SCM_REALLOW_INTS;
2640 }
2641
2642 void
2643 scm_gc_unregister_root (SCM *p)
2644 {
2645 SCM handle;
2646 SCM key = scm_long2num ((long) p);
2647
2648 /* This critical section barrier will be replaced by a mutex. */
2649 SCM_REDEFER_INTS;
2650
2651 handle = scm_hashv_get_handle (scm_gc_registered_roots, key);
2652
2653 if (SCM_FALSEP (handle))
2654 {
2655 fprintf (stderr, "scm_gc_unregister_root called on unregistered root\n");
2656 abort ();
2657 }
2658 else
2659 {
2660 SCM count = scm_difference (SCM_CDR (handle), SCM_MAKINUM (1));
2661 if (SCM_EQ_P (count, SCM_MAKINUM (0)))
2662 scm_hashv_remove_x (scm_gc_registered_roots, key);
2663 else
2664 SCM_SETCDR (handle, count);
2665 }
2666
2667 SCM_REALLOW_INTS;
2668 }
2669
2670 void
2671 scm_gc_register_roots (SCM *b, unsigned long n)
2672 {
2673 SCM *p = b;
2674 for (; p < b + n; ++p)
2675 scm_gc_register_root (p);
2676 }
2677
2678 void
2679 scm_gc_unregister_roots (SCM *b, unsigned long n)
2680 {
2681 SCM *p = b;
2682 for (; p < b + n; ++p)
2683 scm_gc_unregister_root (p);
2684 }
2685
2686 int terminating;
2687
2688 /* called on process termination. */
2689 #ifdef HAVE_ATEXIT
2690 static void
2691 cleanup (void)
2692 #else
2693 #ifdef HAVE_ON_EXIT
2694 extern int on_exit (void (*procp) (), int arg);
2695
2696 static void
2697 cleanup (int status, void *arg)
2698 #else
2699 #error Dont know how to setup a cleanup handler on your system.
2700 #endif
2701 #endif
2702 {
2703 terminating = 1;
2704 scm_flush_all_ports ();
2705 }
2706
2707 \f
2708 static int
2709 make_initial_segment (size_t init_heap_size, scm_t_freelist *freelist)
2710 {
2711 size_t rounded_size = round_to_cluster_size (freelist, init_heap_size);
2712
2713 if (!init_heap_seg ((SCM_CELLPTR) malloc (rounded_size),
2714 rounded_size,
2715 freelist))
2716 {
2717 rounded_size = round_to_cluster_size (freelist, SCM_HEAP_SEG_SIZE);
2718 if (!init_heap_seg ((SCM_CELLPTR) malloc (rounded_size),
2719 rounded_size,
2720 freelist))
2721 return 1;
2722 }
2723 else
2724 scm_expmem = 1;
2725
2726 if (freelist->min_yield_fraction)
2727 freelist->min_yield = (freelist->heap_size * freelist->min_yield_fraction
2728 / 100);
2729 freelist->grow_heap_p = (freelist->heap_size < freelist->min_yield);
2730
2731 return 0;
2732 }
2733
2734 \f
2735 static void
2736 init_freelist (scm_t_freelist *freelist,
2737 int span,
2738 long cluster_size,
2739 int min_yield)
2740 {
2741 freelist->clusters = SCM_EOL;
2742 freelist->cluster_size = cluster_size + 1;
2743 freelist->left_to_collect = 0;
2744 freelist->clusters_allocated = 0;
2745 freelist->min_yield = 0;
2746 freelist->min_yield_fraction = min_yield;
2747 freelist->span = span;
2748 freelist->collected = 0;
2749 freelist->collected_1 = 0;
2750 freelist->heap_size = 0;
2751 }
2752
2753
2754 /* Get an integer from an environment variable. */
2755 static int
2756 scm_i_getenv_int (const char *var, int def)
2757 {
2758 char *end, *val = getenv (var);
2759 long res;
2760 if (!val)
2761 return def;
2762 res = strtol (val, &end, 10);
2763 if (end == val)
2764 return def;
2765 return res;
2766 }
2767
2768
2769 int
2770 scm_init_storage ()
2771 {
2772 unsigned long gc_trigger_1;
2773 unsigned long gc_trigger_2;
2774 size_t init_heap_size_1;
2775 size_t init_heap_size_2;
2776 size_t j;
2777
2778 #if (SCM_DEBUG_CELL_ACCESSES == 1)
2779 scm_tc16_allocated = scm_make_smob_type ("allocated cell", 0);
2780 scm_set_smob_mark (scm_tc16_allocated, allocated_mark);
2781 #endif /* SCM_DEBUG_CELL_ACCESSES == 1 */
2782
2783 j = SCM_NUM_PROTECTS;
2784 while (j)
2785 scm_sys_protects[--j] = SCM_BOOL_F;
2786 scm_block_gc = 1;
2787
2788 scm_freelist = SCM_EOL;
2789 scm_freelist2 = SCM_EOL;
2790 gc_trigger_1 = scm_i_getenv_int ("GUILE_MIN_YIELD_1", scm_default_min_yield_1);
2791 init_freelist (&scm_master_freelist, 1, SCM_CLUSTER_SIZE_1, gc_trigger_1);
2792 gc_trigger_2 = scm_i_getenv_int ("GUILE_MIN_YIELD_2", scm_default_min_yield_2);
2793 init_freelist (&scm_master_freelist2, 2, SCM_CLUSTER_SIZE_2, gc_trigger_2);
2794 scm_max_segment_size = scm_i_getenv_int ("GUILE_MAX_SEGMENT_SIZE", scm_default_max_segment_size);
2795
2796 scm_expmem = 0;
2797
2798 j = SCM_HEAP_SEG_SIZE;
2799 scm_mtrigger = SCM_INIT_MALLOC_LIMIT;
2800 scm_heap_table = ((scm_t_heap_seg_data *)
2801 scm_must_malloc (sizeof (scm_t_heap_seg_data) * 2, "hplims"));
2802 heap_segment_table_size = 2;
2803
2804 mark_space_ptr = &mark_space_head;
2805
2806 init_heap_size_1 = scm_i_getenv_int ("GUILE_INIT_SEGMENT_SIZE_1", scm_default_init_heap_size_1);
2807 init_heap_size_2 = scm_i_getenv_int ("GUILE_INIT_SEGMENT_SIZE_2", scm_default_init_heap_size_2);
2808 if (make_initial_segment (init_heap_size_1, &scm_master_freelist) ||
2809 make_initial_segment (init_heap_size_2, &scm_master_freelist2))
2810 return 1;
2811
2812 /* scm_hplims[0] can change. do not remove scm_heap_org */
2813 scm_heap_org = CELL_UP (scm_heap_table[0].bounds[0], 1);
2814
2815 scm_c_hook_init (&scm_before_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
2816 scm_c_hook_init (&scm_before_mark_c_hook, 0, SCM_C_HOOK_NORMAL);
2817 scm_c_hook_init (&scm_before_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
2818 scm_c_hook_init (&scm_after_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
2819 scm_c_hook_init (&scm_after_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
2820
2821 /* Initialise the list of ports. */
2822 scm_t_portable = (scm_t_port **)
2823 malloc (sizeof (scm_t_port *) * scm_t_portable_room);
2824 if (!scm_t_portable)
2825 return 1;
2826
2827 #ifdef HAVE_ATEXIT
2828 atexit (cleanup);
2829 #else
2830 #ifdef HAVE_ON_EXIT
2831 on_exit (cleanup, 0);
2832 #endif
2833 #endif
2834
2835 scm_stand_in_procs = SCM_EOL;
2836 scm_permobjs = SCM_EOL;
2837 scm_protects = scm_c_make_hash_table (31);
2838 scm_gc_registered_roots = scm_c_make_hash_table (31);
2839
2840 return 0;
2841 }
2842
2843 \f
2844
2845 SCM scm_after_gc_hook;
2846
2847 static SCM gc_async;
2848
2849 /* The function gc_async_thunk causes the execution of the after-gc-hook. It
2850 * is run after the gc, as soon as the asynchronous events are handled by the
2851 * evaluator.
2852 */
2853 static SCM
2854 gc_async_thunk (void)
2855 {
2856 scm_c_run_hook (scm_after_gc_hook, SCM_EOL);
2857 return SCM_UNSPECIFIED;
2858 }
2859
2860
2861 /* The function mark_gc_async is run by the scm_after_gc_c_hook at the end of
2862 * the garbage collection. The only purpose of this function is to mark the
2863 * gc_async (which will eventually lead to the execution of the
2864 * gc_async_thunk).
2865 */
2866 static void *
2867 mark_gc_async (void * hook_data SCM_UNUSED,
2868 void *func_data SCM_UNUSED,
2869 void *data SCM_UNUSED)
2870 {
2871 /* If cell access debugging is enabled, the user may choose to perform
2872 * additional garbage collections after an arbitrary number of cell
2873 * accesses. We don't want the scheme level after-gc-hook to be performed
2874 * for each of these garbage collections for the following reason: The
2875 * execution of the after-gc-hook causes cell accesses itself. Thus, if the
2876 * after-gc-hook was performed with every gc, and if the gc was performed
2877 * after a very small number of cell accesses, then the number of cell
2878 * accesses during the execution of the after-gc-hook will suffice to cause
2879 * the execution of the next gc. Then, guile would keep executing the
2880 * after-gc-hook over and over again, and would never come to do other
2881 * things.
2882 *
2883 * To overcome this problem, if cell access debugging with additional
2884 * garbage collections is enabled, the after-gc-hook is never run by the
2885 * garbage collecter. When running guile with cell access debugging and the
2886 * execution of the after-gc-hook is desired, then it is necessary to run
2887 * the hook explicitly from the user code. This has the effect, that from
2888 * the scheme level point of view it seems that garbage collection is
2889 * performed with a much lower frequency than it actually is. Obviously,
2890 * this will not work for code that depends on a fixed one to one
2891 * relationship between the execution counts of the C level garbage
2892 * collection hooks and the execution count of the scheme level
2893 * after-gc-hook.
2894 */
2895 #if (SCM_DEBUG_CELL_ACCESSES == 1)
2896 if (debug_cells_gc_interval == 0)
2897 scm_system_async_mark (gc_async);
2898 #else
2899 scm_system_async_mark (gc_async);
2900 #endif
2901
2902 return NULL;
2903 }
2904
2905
2906 void
2907 scm_init_gc ()
2908 {
2909 SCM after_gc_thunk;
2910
2911 scm_after_gc_hook = scm_permanent_object (scm_make_hook (SCM_INUM0));
2912 scm_c_define ("after-gc-hook", scm_after_gc_hook);
2913
2914 after_gc_thunk = scm_c_make_subr ("%gc-thunk", scm_tc7_subr_0,
2915 gc_async_thunk);
2916 gc_async = scm_system_async (after_gc_thunk); /* protected via scm_asyncs */
2917
2918 scm_c_hook_add (&scm_after_gc_c_hook, mark_gc_async, NULL, 0);
2919
2920 #ifndef SCM_MAGIC_SNARFER
2921 #include "libguile/gc.x"
2922 #endif
2923 }
2924
2925 #endif /*MARK_DEPENDENCIES*/
2926
2927 /*
2928 Local Variables:
2929 c-file-style: "gnu"
2930 End:
2931 */