gc.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  1. /* Copyright (C) 1995,1996,1997,1998,1999,2000,2001, 2002, 2003, 2006,
  2. * 2008, 2009, 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
  3. *
  4. * This library is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU Lesser General Public License
  6. * as published by the Free Software Foundation; either version 3 of
  7. * the License, or (at your option) any later version.
  8. *
  9. * This library is distributed in the hope that it will be useful, but
  10. * WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. * Lesser General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU Lesser General Public
  15. * License along with this library; if not, write to the Free Software
  16. * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  17. * 02110-1301 USA
  18. */
  19. /* #define DEBUGINFO */
  20. #ifdef HAVE_CONFIG_H
  21. # include <config.h>
  22. #endif
  23. #include "libguile/gen-scmconfig.h"
  24. #include <stdio.h>
  25. #include <errno.h>
  26. #include <string.h>
  27. #include <stdlib.h>
  28. #include <math.h>
  29. #ifdef __ia64__
  30. #include <ucontext.h>
  31. extern unsigned long * __libc_ia64_register_backing_store_base;
  32. #endif
  33. #include "libguile/_scm.h"
  34. #include "libguile/eval.h"
  35. #include "libguile/stime.h"
  36. #include "libguile/stackchk.h"
  37. #include "libguile/struct.h"
  38. #include "libguile/smob.h"
  39. #include "libguile/arrays.h"
  40. #include "libguile/async.h"
  41. #include "libguile/ports.h"
  42. #include "libguile/root.h"
  43. #include "libguile/simpos.h"
  44. #include "libguile/strings.h"
  45. #include "libguile/vectors.h"
  46. #include "libguile/hashtab.h"
  47. #include "libguile/tags.h"
  48. #include "libguile/validate.h"
  49. #include "libguile/deprecation.h"
  50. #include "libguile/gc.h"
  51. #include "libguile/dynwind.h"
  52. #include "libguile/bdw-gc.h"
  53. /* For GC_set_start_callback. */
  54. #include <gc/gc_mark.h>
  55. #ifdef GUILE_DEBUG_MALLOC
  56. #include "libguile/debug-malloc.h"
  57. #endif
  58. #ifdef HAVE_UNISTD_H
  59. #include <unistd.h>
  60. #endif
  61. /* Size in bytes of the initial heap. This should be about the size of
  62. result of 'guile -c "(display (assq-ref (gc-stats)
  63. 'heap-total-allocated))"'. */
  64. #define DEFAULT_INITIAL_HEAP_SIZE (128 * 1024 * SIZEOF_SCM_T_BITS)
  65. /* Set this to != 0 if every cell that is accessed shall be checked:
  66. */
  67. int scm_debug_cell_accesses_p = 0;
  68. int scm_expensive_debug_cell_accesses_p = 0;
  69. /* Set this to 0 if no additional gc's shall be performed, otherwise set it to
  70. * the number of cell accesses after which a gc shall be called.
  71. */
  72. int scm_debug_cells_gc_interval = 0;
  73. /* Hash table that keeps a reference to objects the user wants to protect from
  74. garbage collection. */
  75. static SCM scm_protects;
  76. #if (SCM_DEBUG_CELL_ACCESSES == 1)
  77. /*
  78. Assert that the given object is a valid reference to a valid cell. This
  79. test involves to determine whether the object is a cell pointer, whether
  80. this pointer actually points into a heap segment and whether the cell
  81. pointed to is not a free cell. Further, additional garbage collections may
  82. get executed after a user defined number of cell accesses. This helps to
  83. find places in the C code where references are dropped for extremely short
  84. periods.
  85. */
  86. void
  87. scm_i_expensive_validation_check (SCM cell)
  88. {
  89. /* If desired, perform additional garbage collections after a user
  90. * defined number of cell accesses.
  91. */
  92. if (scm_debug_cells_gc_interval)
  93. {
  94. static unsigned int counter = 0;
  95. if (counter != 0)
  96. {
  97. --counter;
  98. }
  99. else
  100. {
  101. counter = scm_debug_cells_gc_interval;
  102. scm_gc ();
  103. }
  104. }
  105. }
  106. /* Whether cell validation is already running. */
  107. static int scm_i_cell_validation_already_running = 0;
  108. void
  109. scm_assert_cell_valid (SCM cell)
  110. {
  111. if (!scm_i_cell_validation_already_running && scm_debug_cell_accesses_p)
  112. {
  113. scm_i_cell_validation_already_running = 1; /* set to avoid recursion */
  114. /*
  115. During GC, no user-code should be run, and the guile core
  116. should use non-protected accessors.
  117. */
  118. if (scm_gc_running_p)
  119. return;
  120. /*
  121. Only scm_in_heap_p and rescanning the heap is wildly
  122. expensive.
  123. */
  124. if (scm_expensive_debug_cell_accesses_p)
  125. scm_i_expensive_validation_check (cell);
  126. scm_i_cell_validation_already_running = 0; /* re-enable */
  127. }
  128. }
  129. SCM_DEFINE (scm_set_debug_cell_accesses_x, "set-debug-cell-accesses!", 1, 0, 0,
  130. (SCM flag),
  131. "If @var{flag} is @code{#f}, cell access checking is disabled.\n"
  132. "If @var{flag} is @code{#t}, cheap cell access checking is enabled,\n"
  133. "but no additional calls to garbage collection are issued.\n"
  134. "If @var{flag} is a number, strict cell access checking is enabled,\n"
  135. "with an additional garbage collection after the given\n"
  136. "number of cell accesses.\n"
  137. "This procedure only exists when the compile-time flag\n"
  138. "@code{SCM_DEBUG_CELL_ACCESSES} was set to 1.")
  139. #define FUNC_NAME s_scm_set_debug_cell_accesses_x
  140. {
  141. if (scm_is_false (flag))
  142. {
  143. scm_debug_cell_accesses_p = 0;
  144. }
  145. else if (scm_is_eq (flag, SCM_BOOL_T))
  146. {
  147. scm_debug_cells_gc_interval = 0;
  148. scm_debug_cell_accesses_p = 1;
  149. scm_expensive_debug_cell_accesses_p = 0;
  150. }
  151. else
  152. {
  153. scm_debug_cells_gc_interval = scm_to_signed_integer (flag, 0, INT_MAX);
  154. scm_debug_cell_accesses_p = 1;
  155. scm_expensive_debug_cell_accesses_p = 1;
  156. }
  157. return SCM_UNSPECIFIED;
  158. }
  159. #undef FUNC_NAME
  160. #endif /* SCM_DEBUG_CELL_ACCESSES == 1 */
  161. /* Hooks. */
  162. scm_t_c_hook scm_before_gc_c_hook;
  163. scm_t_c_hook scm_before_mark_c_hook;
  164. scm_t_c_hook scm_before_sweep_c_hook;
  165. scm_t_c_hook scm_after_sweep_c_hook;
  166. scm_t_c_hook scm_after_gc_c_hook;
  167. static void
  168. run_before_gc_c_hook (void)
  169. {
  170. if (!SCM_I_CURRENT_THREAD)
  171. /* GC while a thread is spinning up; punt. */
  172. return;
  173. scm_c_hook_run (&scm_before_gc_c_hook, NULL);
  174. }
  175. /* GC Statistics Keeping
  176. */
  177. unsigned long scm_gc_ports_collected = 0;
  178. static long gc_time_taken = 0;
  179. static long gc_start_time = 0;
  180. static unsigned long free_space_divisor;
  181. static unsigned long minimum_free_space_divisor;
  182. static double target_free_space_divisor;
  183. static unsigned long protected_obj_count = 0;
  184. SCM_SYMBOL (sym_gc_time_taken, "gc-time-taken");
  185. SCM_SYMBOL (sym_heap_size, "heap-size");
  186. SCM_SYMBOL (sym_heap_free_size, "heap-free-size");
  187. SCM_SYMBOL (sym_heap_total_allocated, "heap-total-allocated");
  188. SCM_SYMBOL (sym_heap_allocated_since_gc, "heap-allocated-since-gc");
  189. SCM_SYMBOL (sym_protected_objects, "protected-objects");
  190. SCM_SYMBOL (sym_times, "gc-times");
  191. /* {Scheme Interface to GC}
  192. */
  193. extern int scm_gc_malloc_yield_percentage;
  194. SCM_DEFINE (scm_gc_stats, "gc-stats", 0, 0, 0,
  195. (),
  196. "Return an association list of statistics about Guile's current\n"
  197. "use of storage.\n")
  198. #define FUNC_NAME s_scm_gc_stats
  199. {
  200. SCM answer;
  201. GC_word heap_size, free_bytes, unmapped_bytes, bytes_since_gc, total_bytes;
  202. size_t gc_times;
  203. GC_get_heap_usage_safe (&heap_size, &free_bytes, &unmapped_bytes,
  204. &bytes_since_gc, &total_bytes);
  205. gc_times = GC_get_gc_no ();
  206. answer =
  207. scm_list_n (scm_cons (sym_gc_time_taken, scm_from_long (gc_time_taken)),
  208. scm_cons (sym_heap_size, scm_from_size_t (heap_size)),
  209. scm_cons (sym_heap_free_size, scm_from_size_t (free_bytes)),
  210. scm_cons (sym_heap_total_allocated,
  211. scm_from_size_t (total_bytes)),
  212. scm_cons (sym_heap_allocated_since_gc,
  213. scm_from_size_t (bytes_since_gc)),
  214. scm_cons (sym_protected_objects,
  215. scm_from_ulong (protected_obj_count)),
  216. scm_cons (sym_times, scm_from_size_t (gc_times)),
  217. SCM_UNDEFINED);
  218. return answer;
  219. }
  220. #undef FUNC_NAME
  221. SCM_DEFINE (scm_gc_dump, "gc-dump", 0, 0, 0,
  222. (void),
  223. "Dump information about the garbage collector's internal data "
  224. "structures and memory usage to the standard output.")
  225. #define FUNC_NAME s_scm_gc_dump
  226. {
  227. GC_dump ();
  228. return SCM_UNSPECIFIED;
  229. }
  230. #undef FUNC_NAME
  231. SCM_DEFINE (scm_object_address, "object-address", 1, 0, 0,
  232. (SCM obj),
  233. "Return an integer that for the lifetime of @var{obj} is uniquely\n"
  234. "returned by this function for @var{obj}")
  235. #define FUNC_NAME s_scm_object_address
  236. {
  237. return scm_from_ulong (SCM_UNPACK (obj));
  238. }
  239. #undef FUNC_NAME
  240. SCM_DEFINE (scm_gc_disable, "gc-disable", 0, 0, 0,
  241. (),
  242. "Disables the garbage collector. Nested calls are permitted. "
  243. "GC is re-enabled once @code{gc-enable} has been called the "
  244. "same number of times @code{gc-disable} was called.")
  245. #define FUNC_NAME s_scm_gc_disable
  246. {
  247. GC_disable ();
  248. return SCM_UNSPECIFIED;
  249. }
  250. #undef FUNC_NAME
  251. SCM_DEFINE (scm_gc_enable, "gc-enable", 0, 0, 0,
  252. (),
  253. "Enables the garbage collector.")
  254. #define FUNC_NAME s_scm_gc_enable
  255. {
  256. GC_enable ();
  257. return SCM_UNSPECIFIED;
  258. }
  259. #undef FUNC_NAME
  260. SCM_DEFINE (scm_gc, "gc", 0, 0, 0,
  261. (),
  262. "Scans all of SCM objects and reclaims for further use those that are\n"
  263. "no longer accessible.")
  264. #define FUNC_NAME s_scm_gc
  265. {
  266. scm_i_gc ("call");
  267. /* If you're calling scm_gc(), you probably want synchronous
  268. finalization. */
  269. GC_invoke_finalizers ();
  270. return SCM_UNSPECIFIED;
  271. }
  272. #undef FUNC_NAME
  273. void
  274. scm_i_gc (const char *what)
  275. {
  276. GC_gcollect ();
  277. }
  278. /* {GC Protection Helper Functions}
  279. */
  280. /*
  281. * If within a function you need to protect one or more scheme objects from
  282. * garbage collection, pass them as parameters to one of the
  283. * scm_remember_upto_here* functions below. These functions don't do
  284. * anything, but since the compiler does not know that they are actually
  285. * no-ops, it will generate code that calls these functions with the given
  286. * parameters. Therefore, you can be sure that the compiler will keep those
  287. * scheme values alive (on the stack or in a register) up to the point where
  288. * scm_remember_upto_here* is called. In other words, place the call to
  289. * scm_remember_upto_here* _behind_ the last code in your function, that
  290. * depends on the scheme object to exist.
  291. *
  292. * Example: We want to make sure that the string object str does not get
  293. * garbage collected during the execution of 'some_function' in the code
  294. * below, because otherwise the characters belonging to str would be freed and
  295. * 'some_function' might access freed memory. To make sure that the compiler
  296. * keeps str alive on the stack or in a register such that it is visible to
  297. * the conservative gc we add the call to scm_remember_upto_here_1 _after_ the
  298. * call to 'some_function'. Note that this would not be necessary if str was
  299. * used anyway after the call to 'some_function'.
  300. * char *chars = scm_i_string_chars (str);
  301. * some_function (chars);
  302. * scm_remember_upto_here_1 (str); // str will be alive up to this point.
  303. */
  304. /* Remove any macro versions of these while defining the functions.
  305. Functions are always included in the library, for upward binary
  306. compatibility and in case combinations of GCC and non-GCC are used. */
  307. #undef scm_remember_upto_here_1
  308. #undef scm_remember_upto_here_2
  309. void
  310. scm_remember_upto_here_1 (SCM obj SCM_UNUSED)
  311. {
  312. /* Empty. Protects a single object from garbage collection. */
  313. }
  314. void
  315. scm_remember_upto_here_2 (SCM obj1 SCM_UNUSED, SCM obj2 SCM_UNUSED)
  316. {
  317. /* Empty. Protects two objects from garbage collection. */
  318. }
  319. void
  320. scm_remember_upto_here (SCM obj SCM_UNUSED, ...)
  321. {
  322. /* Empty. Protects any number of objects from garbage collection. */
  323. }
  324. /*
  325. These crazy functions prevent garbage collection
  326. of arguments after the first argument by
  327. ensuring they remain live throughout the
  328. function because they are used in the last
  329. line of the code block.
  330. It'd be better to have a nice compiler hint to
  331. aid the conservative stack-scanning GC. --03/09/00 gjb */
  332. SCM
  333. scm_return_first (SCM elt, ...)
  334. {
  335. return elt;
  336. }
  337. int
  338. scm_return_first_int (int i, ...)
  339. {
  340. return i;
  341. }
  342. SCM
  343. scm_permanent_object (SCM obj)
  344. {
  345. return (scm_gc_protect_object (obj));
  346. }
  347. /* Protect OBJ from the garbage collector. OBJ will not be freed, even if all
  348. other references are dropped, until the object is unprotected by calling
  349. scm_gc_unprotect_object (OBJ). Calls to scm_gc_protect/unprotect_object nest,
  350. i. e. it is possible to protect the same object several times, but it is
  351. necessary to unprotect the object the same number of times to actually get
  352. the object unprotected. It is an error to unprotect an object more often
  353. than it has been protected before. The function scm_protect_object returns
  354. OBJ.
  355. */
  356. /* Implementation note: For every object X, there is a counter which
  357. scm_gc_protect_object (X) increments and scm_gc_unprotect_object (X) decrements.
  358. */
  359. SCM
  360. scm_gc_protect_object (SCM obj)
  361. {
  362. SCM handle;
  363. /* This critical section barrier will be replaced by a mutex. */
  364. /* njrev: Indeed; if my comment above is correct, there is the same
  365. critsec/mutex inconsistency here. */
  366. SCM_CRITICAL_SECTION_START;
  367. handle = scm_hashq_create_handle_x (scm_protects, obj, scm_from_int (0));
  368. SCM_SETCDR (handle, scm_sum (SCM_CDR (handle), scm_from_int (1)));
  369. protected_obj_count ++;
  370. SCM_CRITICAL_SECTION_END;
  371. return obj;
  372. }
  373. /* Remove any protection for OBJ established by a prior call to
  374. scm_protect_object. This function returns OBJ.
  375. See scm_protect_object for more information. */
  376. SCM
  377. scm_gc_unprotect_object (SCM obj)
  378. {
  379. SCM handle;
  380. /* This critical section barrier will be replaced by a mutex. */
  381. /* njrev: and again. */
  382. SCM_CRITICAL_SECTION_START;
  383. if (scm_gc_running_p)
  384. {
  385. fprintf (stderr, "scm_unprotect_object called during GC.\n");
  386. abort ();
  387. }
  388. handle = scm_hashq_get_handle (scm_protects, obj);
  389. if (scm_is_false (handle))
  390. {
  391. fprintf (stderr, "scm_unprotect_object called on unprotected object\n");
  392. abort ();
  393. }
  394. else
  395. {
  396. SCM count = scm_difference (SCM_CDR (handle), scm_from_int (1));
  397. if (scm_is_eq (count, scm_from_int (0)))
  398. scm_hashq_remove_x (scm_protects, obj);
  399. else
  400. SCM_SETCDR (handle, count);
  401. }
  402. protected_obj_count --;
  403. SCM_CRITICAL_SECTION_END;
  404. return obj;
  405. }
  406. void
  407. scm_gc_register_root (SCM *p)
  408. {
  409. /* Nothing. */
  410. }
  411. void
  412. scm_gc_unregister_root (SCM *p)
  413. {
  414. /* Nothing. */
  415. }
  416. void
  417. scm_gc_register_roots (SCM *b, unsigned long n)
  418. {
  419. SCM *p = b;
  420. for (; p < b + n; ++p)
  421. scm_gc_register_root (p);
  422. }
  423. void
  424. scm_gc_unregister_roots (SCM *b, unsigned long n)
  425. {
  426. SCM *p = b;
  427. for (; p < b + n; ++p)
  428. scm_gc_unregister_root (p);
  429. }
  430. void
  431. scm_storage_prehistory ()
  432. {
  433. GC_set_all_interior_pointers (0);
  434. free_space_divisor = scm_getenv_int ("GC_FREE_SPACE_DIVISOR", 3);
  435. minimum_free_space_divisor = free_space_divisor;
  436. target_free_space_divisor = free_space_divisor;
  437. GC_set_free_space_divisor (free_space_divisor);
  438. GC_set_finalize_on_demand (1);
  439. GC_INIT ();
  440. GC_expand_hp (DEFAULT_INITIAL_HEAP_SIZE);
  441. /* We only need to register a displacement for those types for which the
  442. higher bits of the type tag are used to store a pointer (that is, a
  443. pointer to an 8-octet aligned region). For `scm_tc3_struct', this is
  444. handled in `scm_alloc_struct ()'. */
  445. GC_REGISTER_DISPLACEMENT (scm_tc3_cons);
  446. /* GC_REGISTER_DISPLACEMENT (scm_tc3_unused); */
  447. /* Sanity check. */
  448. if (!GC_is_visible (&scm_protects))
  449. abort ();
  450. scm_c_hook_init (&scm_before_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
  451. scm_c_hook_init (&scm_before_mark_c_hook, 0, SCM_C_HOOK_NORMAL);
  452. scm_c_hook_init (&scm_before_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
  453. scm_c_hook_init (&scm_after_sweep_c_hook, 0, SCM_C_HOOK_NORMAL);
  454. scm_c_hook_init (&scm_after_gc_c_hook, 0, SCM_C_HOOK_NORMAL);
  455. }
  456. scm_i_pthread_mutex_t scm_i_gc_admin_mutex = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  457. void
  458. scm_init_gc_protect_object ()
  459. {
  460. scm_protects = scm_c_make_hash_table (31);
  461. #if 0
  462. /* We can't have a cleanup handler since we have no thread to run it
  463. in. */
  464. #ifdef HAVE_ATEXIT
  465. atexit (cleanup);
  466. #else
  467. #ifdef HAVE_ON_EXIT
  468. on_exit (cleanup, 0);
  469. #endif
  470. #endif
  471. #endif
  472. }
  473. SCM scm_after_gc_hook;
  474. static SCM after_gc_async_cell;
  475. /* The function after_gc_async_thunk causes the execution of the
  476. * after-gc-hook. It is run after the gc, as soon as the asynchronous
  477. * events are handled by the evaluator.
  478. */
  479. static SCM
  480. after_gc_async_thunk (void)
  481. {
  482. /* Fun, no? Hook-run *and* run-hook? */
  483. scm_c_hook_run (&scm_after_gc_c_hook, NULL);
  484. scm_c_run_hook (scm_after_gc_hook, SCM_EOL);
  485. return SCM_UNSPECIFIED;
  486. }
  487. /* The function queue_after_gc_hook is run by the scm_before_gc_c_hook
  488. * at the end of the garbage collection. The only purpose of this
  489. * function is to mark the after_gc_async (which will eventually lead to
  490. * the execution of the after_gc_async_thunk).
  491. */
  492. static void *
  493. queue_after_gc_hook (void * hook_data SCM_UNUSED,
  494. void *fn_data SCM_UNUSED,
  495. void *data SCM_UNUSED)
  496. {
  497. /* If cell access debugging is enabled, the user may choose to perform
  498. * additional garbage collections after an arbitrary number of cell
  499. * accesses. We don't want the scheme level after-gc-hook to be performed
  500. * for each of these garbage collections for the following reason: The
  501. * execution of the after-gc-hook causes cell accesses itself. Thus, if the
  502. * after-gc-hook was performed with every gc, and if the gc was performed
  503. * after a very small number of cell accesses, then the number of cell
  504. * accesses during the execution of the after-gc-hook will suffice to cause
  505. * the execution of the next gc. Then, guile would keep executing the
  506. * after-gc-hook over and over again, and would never come to do other
  507. * things.
  508. *
  509. * To overcome this problem, if cell access debugging with additional
  510. * garbage collections is enabled, the after-gc-hook is never run by the
  511. * garbage collecter. When running guile with cell access debugging and the
  512. * execution of the after-gc-hook is desired, then it is necessary to run
  513. * the hook explicitly from the user code. This has the effect, that from
  514. * the scheme level point of view it seems that garbage collection is
  515. * performed with a much lower frequency than it actually is. Obviously,
  516. * this will not work for code that depends on a fixed one to one
  517. * relationship between the execution counts of the C level garbage
  518. * collection hooks and the execution count of the scheme level
  519. * after-gc-hook.
  520. */
  521. #if (SCM_DEBUG_CELL_ACCESSES == 1)
  522. if (scm_debug_cells_gc_interval == 0)
  523. #endif
  524. {
  525. scm_i_thread *t = SCM_I_CURRENT_THREAD;
  526. if (scm_is_false (SCM_CDR (after_gc_async_cell)))
  527. {
  528. SCM_SETCDR (after_gc_async_cell, t->active_asyncs);
  529. t->active_asyncs = after_gc_async_cell;
  530. t->pending_asyncs = 1;
  531. }
  532. }
  533. return NULL;
  534. }
  535. static void *
  536. start_gc_timer (void * hook_data SCM_UNUSED,
  537. void *fn_data SCM_UNUSED,
  538. void *data SCM_UNUSED)
  539. {
  540. if (!gc_start_time)
  541. gc_start_time = scm_c_get_internal_run_time ();
  542. return NULL;
  543. }
  544. static void *
  545. accumulate_gc_timer (void * hook_data SCM_UNUSED,
  546. void *fn_data SCM_UNUSED,
  547. void *data SCM_UNUSED)
  548. {
  549. if (gc_start_time)
  550. {
  551. long now = scm_c_get_internal_run_time ();
  552. gc_time_taken += now - gc_start_time;
  553. gc_start_time = 0;
  554. }
  555. return NULL;
  556. }
  557. /* Return some idea of the memory footprint of a process, in bytes.
  558. Currently only works on Linux systems. */
  559. static size_t
  560. get_image_size (void)
  561. {
  562. unsigned long size, resident, share;
  563. size_t ret = 0;
  564. FILE *fp = fopen ("/proc/self/statm", "r");
  565. if (fp && fscanf (fp, "%lu %lu %lu", &size, &resident, &share) == 3)
  566. ret = resident * 4096;
  567. if (fp)
  568. fclose (fp);
  569. return ret;
  570. }
  571. /* These are discussed later. */
  572. static size_t bytes_until_gc = DEFAULT_INITIAL_HEAP_SIZE;
  573. static scm_i_pthread_mutex_t bytes_until_gc_lock = SCM_I_PTHREAD_MUTEX_INITIALIZER;
  574. /* Make GC run more frequently when the process image size is growing,
  575. measured against the number of bytes allocated through the GC.
  576. If Guile is allocating at a GC-managed heap size H, libgc will tend
  577. to limit the process image size to H*N. But if at the same time the
  578. user program is mallocating at a rate M bytes per GC-allocated byte,
  579. then the process stabilizes at H*N*M -- assuming that collecting data
  580. will result in malloc'd data being freed. It doesn't take a very
  581. large M for this to be a bad situation. To limit the image size,
  582. Guile should GC more often -- the bigger the M, the more often.
  583. Numeric functions that produce bigger and bigger integers are
  584. pessimal, because M is an increasing function of time. Here is an
  585. example of such a function:
  586. (define (factorial n)
  587. (define (fac n acc)
  588. (if (<= n 1)
  589. acc
  590. (fac (1- n) (* n acc))))
  591. (fac n 1))
  592. It is possible for a process to grow for reasons that will not be
  593. solved by faster GC. In that case M will be estimated as
  594. artificially high for a while, and so GC will happen more often on
  595. the Guile side. But when it stabilizes, Guile can ease back the GC
  596. frequency.
  597. The key is to measure process image growth, not mallocation rate.
  598. For maximum effectiveness, Guile reacts quickly to process growth,
  599. and exponentially backs down when the process stops growing.
  600. See http://thread.gmane.org/gmane.lisp.guile.devel/12552/focus=12936
  601. for further discussion.
  602. */
  603. static void *
  604. adjust_gc_frequency (void * hook_data SCM_UNUSED,
  605. void *fn_data SCM_UNUSED,
  606. void *data SCM_UNUSED)
  607. {
  608. static size_t prev_image_size = 0;
  609. static size_t prev_bytes_alloced = 0;
  610. size_t image_size;
  611. size_t bytes_alloced;
  612. scm_i_pthread_mutex_lock (&bytes_until_gc_lock);
  613. bytes_until_gc = GC_get_heap_size ();
  614. scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
  615. image_size = get_image_size ();
  616. bytes_alloced = GC_get_total_bytes ();
  617. #define HEURISTICS_DEBUG 0
  618. #if HEURISTICS_DEBUG
  619. fprintf (stderr, "prev image / alloced: %lu / %lu\n", prev_image_size, prev_bytes_alloced);
  620. fprintf (stderr, " image / alloced: %lu / %lu\n", image_size, bytes_alloced);
  621. fprintf (stderr, "divisor %lu / %f\n", free_space_divisor, target_free_space_divisor);
  622. #endif
  623. if (prev_image_size && bytes_alloced != prev_bytes_alloced)
  624. {
  625. double growth_rate, new_target_free_space_divisor;
  626. double decay_factor = 0.5;
  627. double hysteresis = 0.1;
  628. growth_rate = ((double) image_size - prev_image_size)
  629. / ((double)bytes_alloced - prev_bytes_alloced);
  630. #if HEURISTICS_DEBUG
  631. fprintf (stderr, "growth rate %f\n", growth_rate);
  632. #endif
  633. new_target_free_space_divisor = minimum_free_space_divisor;
  634. if (growth_rate > 0)
  635. new_target_free_space_divisor *= 1.0 + growth_rate;
  636. #if HEURISTICS_DEBUG
  637. fprintf (stderr, "new divisor %f\n", new_target_free_space_divisor);
  638. #endif
  639. if (new_target_free_space_divisor < target_free_space_divisor)
  640. /* Decay down. */
  641. target_free_space_divisor =
  642. (decay_factor * target_free_space_divisor
  643. + (1.0 - decay_factor) * new_target_free_space_divisor);
  644. else
  645. /* Jump up. */
  646. target_free_space_divisor = new_target_free_space_divisor;
  647. #if HEURISTICS_DEBUG
  648. fprintf (stderr, "new target divisor %f\n", target_free_space_divisor);
  649. #endif
  650. if (free_space_divisor + 0.5 + hysteresis < target_free_space_divisor
  651. || free_space_divisor - 0.5 - hysteresis > target_free_space_divisor)
  652. {
  653. free_space_divisor = lround (target_free_space_divisor);
  654. #if HEURISTICS_DEBUG
  655. fprintf (stderr, "new divisor %lu\n", free_space_divisor);
  656. #endif
  657. GC_set_free_space_divisor (free_space_divisor);
  658. }
  659. }
  660. prev_image_size = image_size;
  661. prev_bytes_alloced = bytes_alloced;
  662. return NULL;
  663. }
  664. /* The adjust_gc_frequency routine handles transients in the process
  665. image size. It can't handle instense non-GC-managed steady-state
  666. allocation though, as it decays the FSD at steady-state down to its
  667. minimum value.
  668. The only real way to handle continuous, high non-GC allocation is to
  669. let the GC know about it. This routine can handle non-GC allocation
  670. rates that are similar in size to the GC-managed heap size.
  671. */
  672. void
  673. scm_gc_register_allocation (size_t size)
  674. {
  675. scm_i_pthread_mutex_lock (&bytes_until_gc_lock);
  676. if (bytes_until_gc - size > bytes_until_gc)
  677. {
  678. bytes_until_gc = GC_get_heap_size ();
  679. scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
  680. GC_gcollect ();
  681. }
  682. else
  683. {
  684. bytes_until_gc -= size;
  685. scm_i_pthread_mutex_unlock (&bytes_until_gc_lock);
  686. }
  687. }
  688. void
  689. scm_init_gc ()
  690. {
  691. /* `GC_INIT ()' was invoked in `scm_storage_prehistory ()'. */
  692. scm_after_gc_hook = scm_make_hook (SCM_INUM0);
  693. scm_c_define ("after-gc-hook", scm_after_gc_hook);
  694. /* When the async is to run, the cdr of the gc_async pair gets set to
  695. the asyncs queue of the current thread. */
  696. after_gc_async_cell = scm_cons (scm_c_make_gsubr ("%after-gc-thunk", 0, 0, 0,
  697. after_gc_async_thunk),
  698. SCM_BOOL_F);
  699. scm_c_hook_add (&scm_before_gc_c_hook, queue_after_gc_hook, NULL, 0);
  700. scm_c_hook_add (&scm_before_gc_c_hook, start_gc_timer, NULL, 0);
  701. scm_c_hook_add (&scm_after_gc_c_hook, accumulate_gc_timer, NULL, 0);
  702. /* GC_get_heap_usage does not take a lock, and so can run in the GC
  703. start hook. */
  704. scm_c_hook_add (&scm_before_gc_c_hook, adjust_gc_frequency, NULL, 0);
  705. GC_set_start_callback (run_before_gc_c_hook);
  706. #include "libguile/gc.x"
  707. }
  708. void
  709. scm_gc_sweep (void)
  710. #define FUNC_NAME "scm_gc_sweep"
  711. {
  712. /* FIXME */
  713. fprintf (stderr, "%s: doing nothing\n", FUNC_NAME);
  714. }
  715. #undef FUNC_NAME
  716. /*
  717. Local Variables:
  718. c-file-style: "gnu"
  719. End:
  720. */