gc.c 29 KB

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