use the new finalizer helpers
[bpt/guile.git] / libguile / gc.c
CommitLineData
ec7f624d 1/* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002, 2003, 2006, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
a00c95d9 2 *
73be1d9e 3 * This library is free software; you can redistribute it and/or
53befeb7
NJ
4 * modify it under the terms of the GNU Lesser General Public License
5 * as published by the Free Software Foundation; either version 3 of
6 * the License, or (at your option) any later version.
a00c95d9 7 *
53befeb7
NJ
8 * This library is distributed in the hope that it will be useful, but
9 * WITHOUT ANY WARRANTY; without even the implied warranty of
73be1d9e
MV
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
a00c95d9 12 *
73be1d9e
MV
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
53befeb7
NJ
15 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
16 * 02110-1301 USA
73be1d9e 17 */
1bbd0b84 18
37ddcaf6
MD
19/* #define DEBUGINFO */
20
dbb605f5 21#ifdef HAVE_CONFIG_H
aa54a9b0
RB
22# include <config.h>
23#endif
56495472 24
52b680f8
AW
25#define SCM_BUILDING_DEPRECATED_CODE
26
e7bca227
LC
27#include "libguile/gen-scmconfig.h"
28
0f2d19dd 29#include <stdio.h>
e6e2e95a 30#include <errno.h>
783e7774 31#include <string.h>
34cf38c3 32#include <stdlib.h>
6360beb2 33#include <math.h>
e6e2e95a 34
3ec17f28
LC
35#ifdef __ia64__
36#include <ucontext.h>
37extern unsigned long * __libc_ia64_register_backing_store_base;
38#endif
39
a0599745 40#include "libguile/_scm.h"
0a7a7445 41#include "libguile/eval.h"
a0599745
MD
42#include "libguile/stime.h"
43#include "libguile/stackchk.h"
44#include "libguile/struct.h"
a0599745 45#include "libguile/smob.h"
2fa901a5 46#include "libguile/arrays.h"
a0599745
MD
47#include "libguile/async.h"
48#include "libguile/ports.h"
49#include "libguile/root.h"
50#include "libguile/strings.h"
51#include "libguile/vectors.h"
801cb5e7 52#include "libguile/weaks.h"
686765af 53#include "libguile/hashtab.h"
ecf470a2 54#include "libguile/tags.h"
a0599745 55
c8a1bdc4 56#include "libguile/private-gc.h"
a0599745 57#include "libguile/validate.h"
1be6b49c 58#include "libguile/deprecation.h"
a0599745 59#include "libguile/gc.h"
9de87eea 60#include "libguile/dynwind.h"
fce59c93 61
1c44468d 62#include "libguile/bdw-gc.h"
a82e7953 63
cc3546b0
AW
64/* For GC_set_start_callback. */
65#include <gc/gc_mark.h>
66
bc9d9bb2 67#ifdef GUILE_DEBUG_MALLOC
a0599745 68#include "libguile/debug-malloc.h"
bc9d9bb2
MD
69#endif
70
0f2d19dd 71#ifdef HAVE_UNISTD_H
95b88819 72#include <unistd.h>
0f2d19dd
JB
73#endif
74
eae33935 75/* Set this to != 0 if every cell that is accessed shall be checked:
61045190 76 */
eab1b259
HWN
77int scm_debug_cell_accesses_p = 0;
78int scm_expensive_debug_cell_accesses_p = 0;
406c7d90 79
e81d98ec
DH
80/* Set this to 0 if no additional gc's shall be performed, otherwise set it to
81 * the number of cell accesses after which a gc shall be called.
82 */
eab1b259 83int scm_debug_cells_gc_interval = 0;
e81d98ec 84
f0d1bacd 85#if SCM_ENABLE_DEPRECATED == 1
acbccb0c
LC
86/* Hash table that keeps a reference to objects the user wants to protect from
87 garbage collection. It could arguably be private but applications have come
88 to rely on it (e.g., Lilypond 2.13.9). */
89SCM scm_protects;
f0d1bacd
AW
90#else
91static SCM scm_protects;
92#endif
e7efe8e7 93
eab1b259
HWN
94#if (SCM_DEBUG_CELL_ACCESSES == 1)
95
96
97/*
98
99 Assert that the given object is a valid reference to a valid cell. This
100 test involves to determine whether the object is a cell pointer, whether
101 this pointer actually points into a heap segment and whether the cell
102 pointed to is not a free cell. Further, additional garbage collections may
103 get executed after a user defined number of cell accesses. This helps to
104 find places in the C code where references are dropped for extremely short
105 periods.
106
107*/
406c7d90 108void
eab1b259 109scm_i_expensive_validation_check (SCM cell)
406c7d90 110{
eab1b259
HWN
111 /* If desired, perform additional garbage collections after a user
112 * defined number of cell accesses.
113 */
114 if (scm_debug_cells_gc_interval)
115 {
116 static unsigned int counter = 0;
61045190 117
eab1b259
HWN
118 if (counter != 0)
119 {
120 --counter;
121 }
122 else
123 {
124 counter = scm_debug_cells_gc_interval;
b17e0ac3 125 scm_gc ();
eab1b259
HWN
126 }
127 }
128}
129
8c93b597
LC
130/* Whether cell validation is already running. */
131static int scm_i_cell_validation_already_running = 0;
132
eab1b259
HWN
133void
134scm_assert_cell_valid (SCM cell)
135{
136 if (!scm_i_cell_validation_already_running && scm_debug_cell_accesses_p)
406c7d90 137 {
eab1b259 138 scm_i_cell_validation_already_running = 1; /* set to avoid recursion */
406c7d90 139
c8a1bdc4 140 /*
eab1b259
HWN
141 During GC, no user-code should be run, and the guile core
142 should use non-protected accessors.
143 */
c8a1bdc4 144 if (scm_gc_running_p)
eab1b259 145 return;
c8a1bdc4
HWN
146
147 /*
eab1b259
HWN
148 Only scm_in_heap_p and rescanning the heap is wildly
149 expensive.
150 */
151 if (scm_expensive_debug_cell_accesses_p)
152 scm_i_expensive_validation_check (cell);
b4246e5b 153
eab1b259 154 scm_i_cell_validation_already_running = 0; /* re-enable */
406c7d90
DH
155 }
156}
157
158
eab1b259 159
406c7d90
DH
160SCM_DEFINE (scm_set_debug_cell_accesses_x, "set-debug-cell-accesses!", 1, 0, 0,
161 (SCM flag),
1e6808ea 162 "If @var{flag} is @code{#f}, cell access checking is disabled.\n"
eab1b259 163 "If @var{flag} is @code{#t}, cheap cell access checking is enabled,\n"
e81d98ec 164 "but no additional calls to garbage collection are issued.\n"
eab1b259 165 "If @var{flag} is a number, strict cell access checking is enabled,\n"
e81d98ec
DH
166 "with an additional garbage collection after the given\n"
167 "number of cell accesses.\n"
1e6808ea
MG
168 "This procedure only exists when the compile-time flag\n"
169 "@code{SCM_DEBUG_CELL_ACCESSES} was set to 1.")
406c7d90
DH
170#define FUNC_NAME s_scm_set_debug_cell_accesses_x
171{
7888309b 172 if (scm_is_false (flag))
eab1b259
HWN
173 {
174 scm_debug_cell_accesses_p = 0;
175 }
bc36d050 176 else if (scm_is_eq (flag, SCM_BOOL_T))
eab1b259
HWN
177 {
178 scm_debug_cells_gc_interval = 0;
179 scm_debug_cell_accesses_p = 1;
180 scm_expensive_debug_cell_accesses_p = 0;
181 }
e11e83f3 182 else
eab1b259 183 {
e11e83f3 184 scm_debug_cells_gc_interval = scm_to_signed_integer (flag, 0, INT_MAX);
eab1b259
HWN
185 scm_debug_cell_accesses_p = 1;
186 scm_expensive_debug_cell_accesses_p = 1;
187 }
406c7d90
DH
188 return SCM_UNSPECIFIED;
189}
190#undef FUNC_NAME
0f2d19dd 191
ecf470a2 192
c8a1bdc4 193#endif /* SCM_DEBUG_CELL_ACCESSES == 1 */
0f2d19dd
JB
194
195\f
14294ce0 196
6360beb2
AW
197/* Compatibility. */
198
14294ce0
AW
199#ifndef HAVE_GC_GET_HEAP_USAGE_SAFE
200static void
201GC_get_heap_usage_safe (GC_word *pheap_size, GC_word *pfree_bytes,
202 GC_word *punmapped_bytes, GC_word *pbytes_since_gc,
203 GC_word *ptotal_bytes)
204{
205 *pheap_size = GC_get_heap_size ();
206 *pfree_bytes = GC_get_free_bytes ();
4eb28612 207#ifdef HAVE_GC_GET_UNMAPPED_BYTES
14294ce0 208 *punmapped_bytes = GC_get_unmapped_bytes ();
4eb28612
CJY
209#else
210 *punmapped_bytes = 0;
211#endif
14294ce0
AW
212 *pbytes_since_gc = GC_get_bytes_since_gc ();
213 *ptotal_bytes = GC_get_total_bytes ();
214}
215#endif
216
6360beb2
AW
217#ifndef HAVE_GC_GET_FREE_SPACE_DIVISOR
218static GC_word
219GC_get_free_space_divisor (void)
220{
221 return GC_free_space_divisor;
222}
223#endif
224
14294ce0 225\f
26224b3f
LC
226/* Hooks. */
227scm_t_c_hook scm_before_gc_c_hook;
228scm_t_c_hook scm_before_mark_c_hook;
229scm_t_c_hook scm_before_sweep_c_hook;
230scm_t_c_hook scm_after_sweep_c_hook;
231scm_t_c_hook scm_after_gc_c_hook;
945fec60 232
0f2d19dd 233
0fbdbe6c
AW
234static void
235run_before_gc_c_hook (void)
236{
e1fbe716
AW
237 if (!SCM_I_CURRENT_THREAD)
238 /* GC while a thread is spinning up; punt. */
239 return;
240
0fbdbe6c
AW
241 scm_c_hook_run (&scm_before_gc_c_hook, NULL);
242}
243
244
0f2d19dd
JB
245/* GC Statistics Keeping
246 */
b74e86cf 247unsigned long scm_gc_ports_collected = 0;
00b6ef23
AW
248static long gc_time_taken = 0;
249static long gc_start_time = 0;
250
6360beb2
AW
251static unsigned long free_space_divisor;
252static unsigned long minimum_free_space_divisor;
253static double target_free_space_divisor;
b74e86cf 254
915b3f9f 255static unsigned long protected_obj_count = 0;
c2cbcc57 256
0f2d19dd 257
17ab1dc3 258SCM_SYMBOL (sym_gc_time_taken, "gc-time-taken");
915b3f9f
LC
259SCM_SYMBOL (sym_heap_size, "heap-size");
260SCM_SYMBOL (sym_heap_free_size, "heap-free-size");
261SCM_SYMBOL (sym_heap_total_allocated, "heap-total-allocated");
17ab1dc3 262SCM_SYMBOL (sym_heap_allocated_since_gc, "heap-allocated-since-gc");
7eec4c37 263SCM_SYMBOL (sym_protected_objects, "protected-objects");
17ab1dc3 264SCM_SYMBOL (sym_times, "gc-times");
cf2d30f6 265
d3dd80ab 266
0f2d19dd
JB
267/* {Scheme Interface to GC}
268 */
1367aa5e
HWN
269static SCM
270tag_table_to_type_alist (void *closure, SCM key, SCM val, SCM acc)
271{
8fecbb19 272 if (scm_is_integer (key))
8a00ba71 273 {
3e2073bd 274 int c_tag = scm_to_int (key);
8fecbb19
HWN
275
276 char const * name = scm_i_tag_name (c_tag);
277 if (name != NULL)
278 {
279 key = scm_from_locale_string (name);
280 }
281 else
282 {
283 char s[100];
284 sprintf (s, "tag %d", c_tag);
285 key = scm_from_locale_string (s);
286 }
8a00ba71 287 }
8fecbb19 288
1367aa5e
HWN
289 return scm_cons (scm_cons (key, val), acc);
290}
291
292SCM_DEFINE (scm_gc_live_object_stats, "gc-live-object-stats", 0, 0, 0,
293 (),
294 "Return an alist of statistics of the current live objects. ")
295#define FUNC_NAME s_scm_gc_live_object_stats
296{
297 SCM tab = scm_make_hash_table (scm_from_int (57));
b01532af
NJ
298 SCM alist;
299
b01532af 300 alist
1367aa5e
HWN
301 = scm_internal_hash_fold (&tag_table_to_type_alist, NULL, SCM_EOL, tab);
302
303 return alist;
304}
305#undef FUNC_NAME
306
c2cbcc57 307extern int scm_gc_malloc_yield_percentage;
a00c95d9 308SCM_DEFINE (scm_gc_stats, "gc-stats", 0, 0, 0,
1bbd0b84 309 (),
1e6808ea 310 "Return an association list of statistics about Guile's current\n"
c8a1bdc4 311 "use of storage.\n")
1bbd0b84 312#define FUNC_NAME s_scm_gc_stats
0f2d19dd 313{
0f2d19dd 314 SCM answer;
14294ce0 315 GC_word heap_size, free_bytes, unmapped_bytes, bytes_since_gc, total_bytes;
915b3f9f 316 size_t gc_times;
4c9419ac 317
14294ce0
AW
318 GC_get_heap_usage_safe (&heap_size, &free_bytes, &unmapped_bytes,
319 &bytes_since_gc, &total_bytes);
320 gc_times = GC_gc_no;
fca43887 321
b9bd8526 322 answer =
00b6ef23 323 scm_list_n (scm_cons (sym_gc_time_taken, scm_from_long (gc_time_taken)),
915b3f9f
LC
324 scm_cons (sym_heap_size, scm_from_size_t (heap_size)),
325 scm_cons (sym_heap_free_size, scm_from_size_t (free_bytes)),
326 scm_cons (sym_heap_total_allocated,
327 scm_from_size_t (total_bytes)),
17ab1dc3
AW
328 scm_cons (sym_heap_allocated_since_gc,
329 scm_from_size_t (bytes_since_gc)),
915b3f9f
LC
330 scm_cons (sym_protected_objects,
331 scm_from_ulong (protected_obj_count)),
332 scm_cons (sym_times, scm_from_size_t (gc_times)),
b9bd8526 333 SCM_UNDEFINED);
fca43887 334
c8a1bdc4 335 return answer;
0f2d19dd 336}
c8a1bdc4 337#undef FUNC_NAME
0f2d19dd 338
539b08a4 339
7f9ec18a
LC
340SCM_DEFINE (scm_gc_dump, "gc-dump", 0, 0, 0,
341 (void),
342 "Dump information about the garbage collector's internal data "
343 "structures and memory usage to the standard output.")
344#define FUNC_NAME s_scm_gc_dump
345{
346 GC_dump ();
347
348 return SCM_UNSPECIFIED;
349}
350#undef FUNC_NAME
351
acf4331f 352
c8a1bdc4
HWN
353SCM_DEFINE (scm_object_address, "object-address", 1, 0, 0,
354 (SCM obj),
355 "Return an integer that for the lifetime of @var{obj} is uniquely\n"
356 "returned by this function for @var{obj}")
357#define FUNC_NAME s_scm_object_address
c68296f8 358{
b9bd8526 359 return scm_from_ulong (SCM_UNPACK (obj));
c68296f8 360}
c8a1bdc4 361#undef FUNC_NAME
c68296f8 362
1be6b49c 363
915b3f9f
LC
364SCM_DEFINE (scm_gc_disable, "gc-disable", 0, 0, 0,
365 (),
366 "Disables the garbage collector. Nested calls are permitted. "
367 "GC is re-enabled once @code{gc-enable} has been called the "
368 "same number of times @code{gc-disable} was called.")
369#define FUNC_NAME s_scm_gc_disable
370{
371 GC_disable ();
372 return SCM_UNSPECIFIED;
373}
374#undef FUNC_NAME
375
376SCM_DEFINE (scm_gc_enable, "gc-enable", 0, 0, 0,
377 (),
378 "Enables the garbage collector.")
379#define FUNC_NAME s_scm_gc_enable
380{
381 GC_enable ();
382 return SCM_UNSPECIFIED;
383}
384#undef FUNC_NAME
385
386
c8a1bdc4
HWN
387SCM_DEFINE (scm_gc, "gc", 0, 0, 0,
388 (),
389 "Scans all of SCM objects and reclaims for further use those that are\n"
390 "no longer accessible.")
391#define FUNC_NAME s_scm_gc
392{
b17e0ac3 393 scm_i_gc ("call");
c8a1bdc4 394 return SCM_UNSPECIFIED;
9d47a1e6 395}
c8a1bdc4 396#undef FUNC_NAME
9d47a1e6 397
c8a1bdc4 398void
b17e0ac3 399scm_i_gc (const char *what)
c8a1bdc4 400{
66b229d5
AW
401#ifndef HAVE_GC_SET_START_CALLBACK
402 run_before_gc_c_hook ();
403#endif
26224b3f 404 GC_gcollect ();
eab1b259 405}
0f2d19dd 406
4c7016dc 407
0f2d19dd
JB
408\f
409/* {GC Protection Helper Functions}
410 */
411
412
5d2b97cd
DH
413/*
414 * If within a function you need to protect one or more scheme objects from
415 * garbage collection, pass them as parameters to one of the
416 * scm_remember_upto_here* functions below. These functions don't do
417 * anything, but since the compiler does not know that they are actually
418 * no-ops, it will generate code that calls these functions with the given
419 * parameters. Therefore, you can be sure that the compiler will keep those
420 * scheme values alive (on the stack or in a register) up to the point where
421 * scm_remember_upto_here* is called. In other words, place the call to
592996c9 422 * scm_remember_upto_here* _behind_ the last code in your function, that
5d2b97cd
DH
423 * depends on the scheme object to exist.
424 *
8c494e99
DH
425 * Example: We want to make sure that the string object str does not get
426 * garbage collected during the execution of 'some_function' in the code
427 * below, because otherwise the characters belonging to str would be freed and
5d2b97cd
DH
428 * 'some_function' might access freed memory. To make sure that the compiler
429 * keeps str alive on the stack or in a register such that it is visible to
430 * the conservative gc we add the call to scm_remember_upto_here_1 _after_ the
431 * call to 'some_function'. Note that this would not be necessary if str was
432 * used anyway after the call to 'some_function'.
eb01cb64 433 * char *chars = scm_i_string_chars (str);
5d2b97cd
DH
434 * some_function (chars);
435 * scm_remember_upto_here_1 (str); // str will be alive up to this point.
436 */
437
9e1569bd
KR
438/* Remove any macro versions of these while defining the functions.
439 Functions are always included in the library, for upward binary
440 compatibility and in case combinations of GCC and non-GCC are used. */
441#undef scm_remember_upto_here_1
442#undef scm_remember_upto_here_2
443
5d2b97cd 444void
e81d98ec 445scm_remember_upto_here_1 (SCM obj SCM_UNUSED)
5d2b97cd
DH
446{
447 /* Empty. Protects a single object from garbage collection. */
448}
449
450void
e81d98ec 451scm_remember_upto_here_2 (SCM obj1 SCM_UNUSED, SCM obj2 SCM_UNUSED)
5d2b97cd
DH
452{
453 /* Empty. Protects two objects from garbage collection. */
454}
455
456void
e81d98ec 457scm_remember_upto_here (SCM obj SCM_UNUSED, ...)
5d2b97cd
DH
458{
459 /* Empty. Protects any number of objects from garbage collection. */
460}
461
c209c88e 462/*
41b0806d
GB
463 These crazy functions prevent garbage collection
464 of arguments after the first argument by
465 ensuring they remain live throughout the
466 function because they are used in the last
467 line of the code block.
468 It'd be better to have a nice compiler hint to
469 aid the conservative stack-scanning GC. --03/09/00 gjb */
0f2d19dd
JB
470SCM
471scm_return_first (SCM elt, ...)
0f2d19dd
JB
472{
473 return elt;
474}
475
41b0806d
GB
476int
477scm_return_first_int (int i, ...)
478{
479 return i;
480}
481
0f2d19dd 482
0f2d19dd 483SCM
6e8d25a6 484scm_permanent_object (SCM obj)
0f2d19dd 485{
8e7b3e98 486 return (scm_gc_protect_object (obj));
0f2d19dd
JB
487}
488
489
7bd4fbe2
MD
490/* Protect OBJ from the garbage collector. OBJ will not be freed, even if all
491 other references are dropped, until the object is unprotected by calling
6b1b030e 492 scm_gc_unprotect_object (OBJ). Calls to scm_gc_protect/unprotect_object nest,
7bd4fbe2
MD
493 i. e. it is possible to protect the same object several times, but it is
494 necessary to unprotect the object the same number of times to actually get
495 the object unprotected. It is an error to unprotect an object more often
496 than it has been protected before. The function scm_protect_object returns
497 OBJ.
498*/
499
500/* Implementation note: For every object X, there is a counter which
1f584400 501 scm_gc_protect_object (X) increments and scm_gc_unprotect_object (X) decrements.
7bd4fbe2 502*/
686765af 503
7eec4c37
HWN
504
505
ef290276 506SCM
6b1b030e 507scm_gc_protect_object (SCM obj)
ef290276 508{
686765af 509 SCM handle;
9d47a1e6 510
686765af 511 /* This critical section barrier will be replaced by a mutex. */
33b320ae
NJ
512 /* njrev: Indeed; if my comment above is correct, there is the same
513 critsec/mutex inconsistency here. */
9de87eea 514 SCM_CRITICAL_SECTION_START;
9d47a1e6 515
acbccb0c 516 handle = scm_hashq_create_handle_x (scm_protects, obj, scm_from_int (0));
e11e83f3 517 SCM_SETCDR (handle, scm_sum (SCM_CDR (handle), scm_from_int (1)));
9d47a1e6 518
7eec4c37
HWN
519 protected_obj_count ++;
520
9de87eea 521 SCM_CRITICAL_SECTION_END;
9d47a1e6 522
ef290276
JB
523 return obj;
524}
525
526
527/* Remove any protection for OBJ established by a prior call to
dab7f566 528 scm_protect_object. This function returns OBJ.
ef290276 529
dab7f566 530 See scm_protect_object for more information. */
ef290276 531SCM
6b1b030e 532scm_gc_unprotect_object (SCM obj)
ef290276 533{
686765af 534 SCM handle;
9d47a1e6 535
686765af 536 /* This critical section barrier will be replaced by a mutex. */
33b320ae 537 /* njrev: and again. */
9de87eea 538 SCM_CRITICAL_SECTION_START;
9d47a1e6 539
0ff7e3ff
HWN
540 if (scm_gc_running_p)
541 {
542 fprintf (stderr, "scm_unprotect_object called during GC.\n");
543 abort ();
544 }
b17e0ac3 545
acbccb0c 546 handle = scm_hashq_get_handle (scm_protects, obj);
9d47a1e6 547
7888309b 548 if (scm_is_false (handle))
686765af 549 {
0f0f0899
MD
550 fprintf (stderr, "scm_unprotect_object called on unprotected object\n");
551 abort ();
686765af 552 }
6a199940
DH
553 else
554 {
e11e83f3 555 SCM count = scm_difference (SCM_CDR (handle), scm_from_int (1));
bc36d050 556 if (scm_is_eq (count, scm_from_int (0)))
acbccb0c 557 scm_hashq_remove_x (scm_protects, obj);
6a199940 558 else
1be6b49c 559 SCM_SETCDR (handle, count);
6a199940 560 }
7eec4c37 561 protected_obj_count --;
686765af 562
9de87eea 563 SCM_CRITICAL_SECTION_END;
ef290276
JB
564
565 return obj;
566}
567
6b1b030e
ML
568void
569scm_gc_register_root (SCM *p)
570{
8e7b3e98 571 /* Nothing. */
6b1b030e
ML
572}
573
574void
575scm_gc_unregister_root (SCM *p)
576{
8e7b3e98 577 /* Nothing. */
6b1b030e
ML
578}
579
580void
581scm_gc_register_roots (SCM *b, unsigned long n)
582{
583 SCM *p = b;
584 for (; p < b + n; ++p)
585 scm_gc_register_root (p);
586}
587
588void
589scm_gc_unregister_roots (SCM *b, unsigned long n)
590{
591 SCM *p = b;
592 for (; p < b + n; ++p)
593 scm_gc_unregister_root (p);
594}
595
0f2d19dd 596\f
a00c95d9 597
4c48ba06 598
c8a1bdc4
HWN
599/*
600 MOVE THIS FUNCTION. IT DOES NOT HAVE ANYTHING TODO WITH GC.
601 */
85db4a2c
DH
602
603/* Get an integer from an environment variable. */
c8a1bdc4
HWN
604int
605scm_getenv_int (const char *var, int def)
85db4a2c 606{
c8a1bdc4
HWN
607 char *end = 0;
608 char *val = getenv (var);
609 long res = def;
85db4a2c
DH
610 if (!val)
611 return def;
612 res = strtol (val, &end, 10);
613 if (end == val)
614 return def;
615 return res;
616}
617
c35738c1
MD
618void
619scm_storage_prehistory ()
620{
184327a6 621 GC_all_interior_pointers = 0;
6360beb2
AW
622 free_space_divisor = scm_getenv_int ("GC_FREE_SPACE_DIVISOR", 3);
623 minimum_free_space_divisor = free_space_divisor;
624 target_free_space_divisor = free_space_divisor;
625 GC_set_free_space_divisor (free_space_divisor);
184327a6 626
a82e7953 627 GC_INIT ();
e7bca227 628
11d2fc06
LC
629#if (! ((defined GC_VERSION_MAJOR) && (GC_VERSION_MAJOR >= 7))) \
630 && (defined SCM_I_GSC_USE_PTHREAD_THREADS)
e7bca227
LC
631 /* When using GC 6.8, this call is required to initialize thread-local
632 freelists (shouldn't be necessary with GC 7.0). */
633 GC_init ();
634#endif
635
fdab75a1 636 GC_expand_hp (SCM_DEFAULT_INIT_HEAP_SIZE_2);
915b3f9f 637
184327a6
LC
638 /* We only need to register a displacement for those types for which the
639 higher bits of the type tag are used to store a pointer (that is, a
640 pointer to an 8-octet aligned region). For `scm_tc3_struct', this is
641 handled in `scm_alloc_struct ()'. */
642 GC_REGISTER_DISPLACEMENT (scm_tc3_cons);
314b8716 643 /* GC_REGISTER_DISPLACEMENT (scm_tc3_unused); */
184327a6 644
915b3f9f 645 /* Sanity check. */
acbccb0c 646 if (!GC_is_visible (&scm_protects))
915b3f9f 647 abort ();
a82e7953 648
c35738c1
MD
649 scm_c_hook_init (&scm_before_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
650 scm_c_hook_init (&scm_before_mark_c_hook, 0, SCM_C_HOOK_NORMAL);
651 scm_c_hook_init (&scm_before_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
652 scm_c_hook_init (&scm_after_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
653 scm_c_hook_init (&scm_after_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
654}
85db4a2c 655
9de87eea 656scm_i_pthread_mutex_t scm_i_gc_admin_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
eb01cb64 657
562cd1b8
AW
658void
659scm_init_gc_protect_object ()
0f2d19dd 660{
acbccb0c 661 scm_protects = scm_c_make_hash_table (31);
4a4c9785 662
9de87eea
MV
663#if 0
664 /* We can't have a cleanup handler since we have no thread to run it
665 in. */
666
a18bcd0e 667#ifdef HAVE_ATEXIT
c45acc34 668 atexit (cleanup);
e52ceaac
MD
669#else
670#ifdef HAVE_ON_EXIT
671 on_exit (cleanup, 0);
672#endif
9de87eea
MV
673#endif
674
a18bcd0e 675#endif
0f2d19dd 676}
939794ce 677
0f2d19dd
JB
678\f
679
939794ce
DH
680SCM scm_after_gc_hook;
681
cc3546b0 682static SCM after_gc_async_cell;
939794ce 683
cc3546b0
AW
684/* The function after_gc_async_thunk causes the execution of the
685 * after-gc-hook. It is run after the gc, as soon as the asynchronous
686 * events are handled by the evaluator.
939794ce
DH
687 */
688static SCM
cc3546b0 689after_gc_async_thunk (void)
939794ce 690{
cc3546b0
AW
691 /* Fun, no? Hook-run *and* run-hook? */
692 scm_c_hook_run (&scm_after_gc_c_hook, NULL);
939794ce 693 scm_c_run_hook (scm_after_gc_hook, SCM_EOL);
939794ce
DH
694 return SCM_UNSPECIFIED;
695}
696
697
cc3546b0
AW
698/* The function queue_after_gc_hook is run by the scm_before_gc_c_hook
699 * at the end of the garbage collection. The only purpose of this
700 * function is to mark the after_gc_async (which will eventually lead to
701 * the execution of the after_gc_async_thunk).
939794ce
DH
702 */
703static void *
cc3546b0
AW
704queue_after_gc_hook (void * hook_data SCM_UNUSED,
705 void *fn_data SCM_UNUSED,
706 void *data SCM_UNUSED)
e81d98ec
DH
707{
708 /* If cell access debugging is enabled, the user may choose to perform
709 * additional garbage collections after an arbitrary number of cell
710 * accesses. We don't want the scheme level after-gc-hook to be performed
711 * for each of these garbage collections for the following reason: The
712 * execution of the after-gc-hook causes cell accesses itself. Thus, if the
713 * after-gc-hook was performed with every gc, and if the gc was performed
714 * after a very small number of cell accesses, then the number of cell
715 * accesses during the execution of the after-gc-hook will suffice to cause
716 * the execution of the next gc. Then, guile would keep executing the
717 * after-gc-hook over and over again, and would never come to do other
718 * things.
eae33935 719 *
e81d98ec
DH
720 * To overcome this problem, if cell access debugging with additional
721 * garbage collections is enabled, the after-gc-hook is never run by the
722 * garbage collecter. When running guile with cell access debugging and the
723 * execution of the after-gc-hook is desired, then it is necessary to run
724 * the hook explicitly from the user code. This has the effect, that from
725 * the scheme level point of view it seems that garbage collection is
726 * performed with a much lower frequency than it actually is. Obviously,
727 * this will not work for code that depends on a fixed one to one
728 * relationship between the execution counts of the C level garbage
729 * collection hooks and the execution count of the scheme level
730 * after-gc-hook.
731 */
9de87eea 732
e81d98ec 733#if (SCM_DEBUG_CELL_ACCESSES == 1)
eab1b259 734 if (scm_debug_cells_gc_interval == 0)
e81d98ec 735#endif
cc3546b0
AW
736 {
737 scm_i_thread *t = SCM_I_CURRENT_THREAD;
738
739 if (scm_is_false (SCM_CDR (after_gc_async_cell)))
740 {
741 SCM_SETCDR (after_gc_async_cell, t->active_asyncs);
742 t->active_asyncs = after_gc_async_cell;
743 t->pending_asyncs = 1;
744 }
745 }
e81d98ec 746
939794ce
DH
747 return NULL;
748}
749
00b6ef23
AW
750\f
751
752static void *
753start_gc_timer (void * hook_data SCM_UNUSED,
754 void *fn_data SCM_UNUSED,
755 void *data SCM_UNUSED)
756{
757 if (!gc_start_time)
758 gc_start_time = scm_c_get_internal_run_time ();
759
760 return NULL;
761}
762
763static void *
764accumulate_gc_timer (void * hook_data SCM_UNUSED,
765 void *fn_data SCM_UNUSED,
766 void *data SCM_UNUSED)
767{
768 if (gc_start_time)
6360beb2
AW
769 {
770 long now = scm_c_get_internal_run_time ();
00b6ef23
AW
771 gc_time_taken += now - gc_start_time;
772 gc_start_time = 0;
773 }
774
775 return NULL;
776}
777
6360beb2
AW
778/* Return some idea of the memory footprint of a process, in bytes.
779 Currently only works on Linux systems. */
780static size_t
781get_image_size (void)
782{
783 unsigned long size, resident, share;
8ac70433 784 size_t ret = 0;
6360beb2
AW
785
786 FILE *fp = fopen ("/proc/self/statm", "r");
787
788 if (fp && fscanf (fp, "%lu %lu %lu", &size, &resident, &share) == 3)
789 ret = resident * 4096;
790
791 if (fp)
792 fclose (fp);
793
794 return ret;
795}
796
fd51e661
AW
797/* These are discussed later. */
798static size_t bytes_until_gc;
799static scm_i_pthread_mutex_t bytes_until_gc_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
800
6360beb2
AW
801/* Make GC run more frequently when the process image size is growing,
802 measured against the number of bytes allocated through the GC.
803
804 If Guile is allocating at a GC-managed heap size H, libgc will tend
805 to limit the process image size to H*N. But if at the same time the
806 user program is mallocating at a rate M bytes per GC-allocated byte,
807 then the process stabilizes at H*N*M -- assuming that collecting data
808 will result in malloc'd data being freed. It doesn't take a very
809 large M for this to be a bad situation. To limit the image size,
810 Guile should GC more often -- the bigger the M, the more often.
811
812 Numeric functions that produce bigger and bigger integers are
813 pessimal, because M is an increasing function of time. Here is an
814 example of such a function:
815
816 (define (factorial n)
817 (define (fac n acc)
818 (if (<= n 1)
819 acc
820 (fac (1- n) (* n acc))))
821 (fac n 1))
822
823 It is possible for a process to grow for reasons that will not be
824 solved by faster GC. In that case M will be estimated as
825 artificially high for a while, and so GC will happen more often on
826 the Guile side. But when it stabilizes, Guile can ease back the GC
827 frequency.
828
829 The key is to measure process image growth, not mallocation rate.
830 For maximum effectiveness, Guile reacts quickly to process growth,
831 and exponentially backs down when the process stops growing.
832
833 See http://thread.gmane.org/gmane.lisp.guile.devel/12552/focus=12936
834 for further discussion.
835 */
836static void *
837adjust_gc_frequency (void * hook_data SCM_UNUSED,
838 void *fn_data SCM_UNUSED,
839 void *data SCM_UNUSED)
840{
841 static size_t prev_image_size = 0;
842 static size_t prev_bytes_alloced = 0;
843 size_t image_size;
844 size_t bytes_alloced;
845
fd51e661
AW
846 scm_i_pthread_mutex_lock (&bytes_until_gc_lock);
847 bytes_until_gc = GC_get_heap_size ();
848 scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
849
6360beb2
AW
850 image_size = get_image_size ();
851 bytes_alloced = GC_get_total_bytes ();
852
d1c03624 853#define HEURISTICS_DEBUG 0
6360beb2
AW
854
855#if HEURISTICS_DEBUG
856 fprintf (stderr, "prev image / alloced: %lu / %lu\n", prev_image_size, prev_bytes_alloced);
857 fprintf (stderr, " image / alloced: %lu / %lu\n", image_size, bytes_alloced);
858 fprintf (stderr, "divisor %lu / %f\n", free_space_divisor, target_free_space_divisor);
859#endif
860
861 if (prev_image_size && bytes_alloced != prev_bytes_alloced)
862 {
863 double growth_rate, new_target_free_space_divisor;
864 double decay_factor = 0.5;
865 double hysteresis = 0.1;
866
867 growth_rate = ((double) image_size - prev_image_size)
868 / ((double)bytes_alloced - prev_bytes_alloced);
869
870#if HEURISTICS_DEBUG
871 fprintf (stderr, "growth rate %f\n", growth_rate);
872#endif
873
874 new_target_free_space_divisor = minimum_free_space_divisor;
875
876 if (growth_rate > 0)
877 new_target_free_space_divisor *= 1.0 + growth_rate;
878
879#if HEURISTICS_DEBUG
880 fprintf (stderr, "new divisor %f\n", new_target_free_space_divisor);
881#endif
882
883 if (new_target_free_space_divisor < target_free_space_divisor)
884 /* Decay down. */
885 target_free_space_divisor =
886 (decay_factor * target_free_space_divisor
887 + (1.0 - decay_factor) * new_target_free_space_divisor);
888 else
889 /* Jump up. */
890 target_free_space_divisor = new_target_free_space_divisor;
891
892#if HEURISTICS_DEBUG
893 fprintf (stderr, "new target divisor %f\n", target_free_space_divisor);
894#endif
895
896 if (free_space_divisor + 0.5 + hysteresis < target_free_space_divisor
897 || free_space_divisor - 0.5 - hysteresis > target_free_space_divisor)
898 {
899 free_space_divisor = lround (target_free_space_divisor);
900#if HEURISTICS_DEBUG
901 fprintf (stderr, "new divisor %lu\n", free_space_divisor);
902#endif
903 GC_set_free_space_divisor (free_space_divisor);
904 }
905 }
906
907 prev_image_size = image_size;
908 prev_bytes_alloced = bytes_alloced;
909
910 return NULL;
911}
912
fd51e661
AW
913/* The adjust_gc_frequency routine handles transients in the process
914 image size. It can't handle instense non-GC-managed steady-state
915 allocation though, as it decays the FSD at steady-state down to its
916 minimum value.
917
918 The only real way to handle continuous, high non-GC allocation is to
919 let the GC know about it. This routine can handle non-GC allocation
920 rates that are similar in size to the GC-managed heap size.
921 */
922
923void
924scm_gc_register_allocation (size_t size)
925{
926 scm_i_pthread_mutex_lock (&bytes_until_gc_lock);
927 if (bytes_until_gc - size > bytes_until_gc)
928 {
929 bytes_until_gc = GC_get_heap_size ();
930 scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
931 GC_gcollect ();
932 }
933 else
934 {
935 bytes_until_gc -= size;
936 scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
937 }
938}
939
00b6ef23
AW
940
941\f
942
26224b3f
LC
943char const *
944scm_i_tag_name (scm_t_bits tag)
945{
74ec8d78 946 switch (tag & 0x7f) /* 7 bits */
26224b3f
LC
947 {
948 case scm_tcs_struct:
949 return "struct";
950 case scm_tcs_cons_imcar:
951 return "cons (immediate car)";
952 case scm_tcs_cons_nimcar:
953 return "cons (non-immediate car)";
5b46a8c2 954 case scm_tc7_pointer:
e2c2a699 955 return "foreign";
c99de5aa
AW
956 case scm_tc7_hashtable:
957 return "hashtable";
9ea31741
AW
958 case scm_tc7_fluid:
959 return "fluid";
960 case scm_tc7_dynamic_state:
961 return "dynamic state";
6f3b0cc2
AW
962 case scm_tc7_frame:
963 return "frame";
964 case scm_tc7_objcode:
965 return "objcode";
966 case scm_tc7_vm:
967 return "vm";
968 case scm_tc7_vm_cont:
969 return "vm continuation";
26224b3f
LC
970 case scm_tc7_wvect:
971 return "weak vector";
972 case scm_tc7_vector:
973 return "vector";
26224b3f
LC
974 case scm_tc7_number:
975 switch (tag)
976 {
977 case scm_tc16_real:
978 return "real";
979 break;
980 case scm_tc16_big:
981 return "bignum";
982 break;
983 case scm_tc16_complex:
984 return "complex number";
985 break;
986 case scm_tc16_fraction:
987 return "fraction";
988 break;
989 }
990 break;
991 case scm_tc7_string:
992 return "string";
993 break;
994 case scm_tc7_stringbuf:
995 return "string buffer";
996 break;
997 case scm_tc7_symbol:
998 return "symbol";
999 break;
1000 case scm_tc7_variable:
1001 return "variable";
1002 break;
26224b3f
LC
1003 case scm_tc7_port:
1004 return "port";
1005 break;
1006 case scm_tc7_smob:
74ec8d78
AW
1007 {
1008 int k = 0xff & (tag >> 8);
1009 return (scm_smobs[k].name);
1010 }
26224b3f
LC
1011 break;
1012 }
1013
1014 return NULL;
1015}
1016
1017
26224b3f
LC
1018
1019\f
0f2d19dd
JB
1020void
1021scm_init_gc ()
0f2d19dd 1022{
a82e7953 1023 /* `GC_INIT ()' was invoked in `scm_storage_prehistory ()'. */
d678e25c 1024
f39448c5 1025 scm_after_gc_hook = scm_make_hook (SCM_INUM0);
fde50407 1026 scm_c_define ("after-gc-hook", scm_after_gc_hook);
939794ce 1027
cc3546b0
AW
1028 /* When the async is to run, the cdr of the gc_async pair gets set to
1029 the asyncs queue of the current thread. */
1030 after_gc_async_cell = scm_cons (scm_c_make_gsubr ("%after-gc-thunk", 0, 0, 0,
1031 after_gc_async_thunk),
1032 SCM_BOOL_F);
939794ce 1033
cc3546b0 1034 scm_c_hook_add (&scm_before_gc_c_hook, queue_after_gc_hook, NULL, 0);
00b6ef23
AW
1035 scm_c_hook_add (&scm_before_gc_c_hook, start_gc_timer, NULL, 0);
1036 scm_c_hook_add (&scm_after_gc_c_hook, accumulate_gc_timer, NULL, 0);
66b229d5 1037
738c899e
AW
1038#if HAVE_GC_GET_HEAP_USAGE_SAFE
1039 /* GC_get_heap_usage does not take a lock, and so can run in the GC
1040 start hook. */
1041 scm_c_hook_add (&scm_before_gc_c_hook, adjust_gc_frequency, NULL, 0);
1042#else
1043 /* GC_get_heap_usage might take a lock (and did from 7.2alpha1 to
1044 7.2alpha7), so call it in the after_gc_hook. */
1045 scm_c_hook_add (&scm_after_gc_c_hook, adjust_gc_frequency, NULL, 0);
1046#endif
1047
66b229d5 1048#ifdef HAVE_GC_SET_START_CALLBACK
cc3546b0 1049 GC_set_start_callback (run_before_gc_c_hook);
66b229d5 1050#endif
939794ce 1051
a0599745 1052#include "libguile/gc.x"
0f2d19dd 1053}
89e00824 1054
c8a1bdc4
HWN
1055
1056void
1057scm_gc_sweep (void)
1058#define FUNC_NAME "scm_gc_sweep"
1059{
26224b3f 1060 /* FIXME */
cd169c5a 1061 fprintf (stderr, "%s: doing nothing\n", FUNC_NAME);
c8a1bdc4 1062}
c8a1bdc4
HWN
1063#undef FUNC_NAME
1064
89e00824
ML
1065/*
1066 Local Variables:
1067 c-file-style: "gnu"
1068 End:
1069*/