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