Release notes and some test programs.
[ocaml-ancient.git] / ancient_c.c
1 /* Mark objects as 'ancient' so they are taken out of the OCaml heap.
2  * $Id: ancient_c.c,v 1.7 2006-10-06 12:25:20 rich Exp $
3  */
4
5 #include <string.h>
6 #include <assert.h>
7
8 #include <caml/config.h>
9 #include <caml/memory.h>
10 #include <caml/alloc.h>
11 #include <caml/mlvalues.h>
12 #include <caml/fail.h>
13
14 #include "mmalloc/mmalloc.h"
15
16 // From byterun/misc.h:
17 typedef char * addr;
18
19 // From byterun/minor_gc.c:
20 CAMLextern char *caml_young_start;
21 CAMLextern char *caml_young_end;
22 #define Is_young(val) \
23   (assert (Is_block (val)),                                             \
24    (addr)(val) < (addr)caml_young_end && (addr)(val) > (addr)caml_young_start)
25
26 // From byterun/major_gc.h:
27 #ifdef __alpha
28 typedef int page_table_entry;
29 #else
30 typedef char page_table_entry;
31 #endif
32 CAMLextern char *caml_heap_start;
33 CAMLextern char *caml_heap_end;
34 CAMLextern page_table_entry *caml_page_table;
35
36 #define In_heap 1
37 #define Not_in_heap 0
38 #define Page(p) ((uintnat) (p) >> Page_log)
39 #define Is_in_heap(p) \
40   (assert (Is_block ((value) (p))),                                     \
41    (addr)(p) >= (addr)caml_heap_start && (addr)(p) < (addr)caml_heap_end \
42    && caml_page_table [Page (p)])
43
44 // Area is an expandable buffer, allocated on the C heap.
45 typedef struct area {
46   void *ptr;                    // Start of area.
47   size_t n;                     // Current position.
48   size_t size;                  // Allocated size.
49
50   // If this area requires custom realloc function, these will be non-null.
51   void *(*realloc)(void *data, void *ptr, size_t size);
52   void (*free)(void *data, void *ptr);
53   void *data;
54 } area;
55
56 static inline void
57 area_init (area *a)
58 {
59   a->ptr = 0;
60   a->n =
61   a->size = 0;
62   a->realloc = 0;
63   a->free = 0;
64   a->data = 0;
65 }
66
67 static inline void
68 area_init_custom (area *a,
69                   void *(*realloc)(void *data, void *ptr, size_t size),
70                   void (*free)(void *data, void *ptr),
71                   void *data)
72 {
73   area_init (a);
74   a->realloc = realloc;
75   a->free = free;
76   a->data = data;
77 }
78
79 static inline int
80 area_append (area *a, const void *obj, size_t size)
81 {
82   while (a->n + size > a->size) {
83     if (a->size == 0) a->size = 256; else a->size <<= 1;
84     a->ptr =
85       a->realloc
86       ? a->realloc (a->data, a->ptr, a->size)
87       : realloc (a->ptr, a->size);
88     if (a->ptr == 0) return -1; // Out of memory.
89   }
90   memcpy (a->ptr + a->n, obj, size);
91   a->n += size;
92   return 0;
93 }
94
95 static inline void
96 area_shrink (area *a)
97 {
98   if (a->n != a->size) {
99     a->size = a->n;
100     a->ptr =
101       a->realloc
102       ? a->realloc (a->data, a->ptr, a->size)
103       : realloc (a->ptr, a->size);
104     assert (a->ptr); // Getting smaller, so shouldn't really fail.
105   }
106 }
107
108 static inline void
109 area_free (area *a)
110 {
111   if (a->free) a->free (a->data, a->ptr);
112   else free (a->ptr);
113   a->n =
114   a->size = 0;
115 }
116
117 struct restore_item {
118   char *header;
119   value field_zero;
120 };
121
122 // When a block is visited, we overwrite the header with all 1's.
123 // This is not quite an impossible value - one could imagine an
124 // enormous custom block where the header could take on this
125 // value. (XXX)
126 static header_t visited = (unsigned long) -1;
127
128 // The general plan here:
129 //
130 // 1. Starting at [obj], copy it to our out-of-heap memory area
131 // defined by [ptr].
132 // 2. Recursively visit subnodes of [obj] and do the same.
133 // 3. As we copy each object, we avoid circularity by setting that
134 // object's header to a special 'visited' value.  However since these
135 // are objects in the Caml heap we have to restore the original
136 // headers at the end, which is the purpose of the [restore] area.
137 // 4. We use realloc to allocate the memory for the copy, but because
138 // the memory can move around, we cannot store absolute pointers.
139 // Instead we store offsets and fix them up later.  This is the
140 // purpose of the [fixups] area.
141 //
142 // XXX Large, deeply recursive structures cause a stack overflow.
143 // Temporary solution: 'ulimit -s unlimited'.  This function should
144 // be replaced with something iterative.
145 static size_t
146 _mark (value obj, area *ptr, area *restore, area *fixups)
147 {
148   char *header = Hp_val (obj);
149   assert (Wosize_hp (header) > 0); // Always true? (XXX)
150
151   // XXX This assertion might fail if someone tries to mark an object
152   // which is already ancient.
153   assert (Is_young (obj) || Is_in_heap (obj));
154
155   // If we've already visited this object, just return its offset
156   // in the out-of-heap memory.
157   if (memcmp (header, &visited, sizeof visited) == 0)
158     return (Long_val (Field (obj, 0)));
159
160   // Offset where we will store this object in the out-of-heap memory.
161   size_t offset = ptr->n;
162
163   // Copy the object out of the OCaml heap.
164   size_t bytes = Bhsize_hp (header);
165   if (area_append (ptr, header, bytes) == -1)
166     return -1;                  // Error out of memory.
167
168   // Scan the fields looking for pointers to blocks.
169   int can_scan = Tag_val (obj) < No_scan_tag;
170   if (can_scan) {
171     mlsize_t nr_words = Wosize_hp (header);
172     mlsize_t i;
173
174     for (i = 0; i < nr_words; ++i) {
175       value field = Field (obj, i);
176
177       if (Is_block (field) &&
178           (Is_young (field) || Is_in_heap (field))) {
179         size_t field_offset = _mark (field, ptr, restore, fixups);
180         if (field_offset == -1) return -1; // Propagate out of memory errors.
181
182         // Since the recursive call to mark above can reallocate the
183         // area, we need to recompute these each time round the loop.
184         char *obj_copy_header = ptr->ptr + offset;
185         value obj_copy = Val_hp (obj_copy_header);
186
187         // Don't store absolute pointers yet because realloc will
188         // move the memory around.  Store a fake pointer instead.
189         // We'll fix up these fake pointers afterwards in do_fixups.
190         Field (obj_copy, i) = field_offset + sizeof (header_t);
191
192         size_t fixup = (void *)&Field(obj_copy, i) - ptr->ptr;
193         area_append (fixups, &fixup, sizeof fixup);
194       }
195     }
196   }
197
198   // Mark this object as having been "visited", but keep track of
199   // what was there before so it can be restored.  We also need to
200   // record the offset.
201   // Observations:
202   // (1) What was in the header before is kept in the out-of-heap
203   // copy, so we don't explicitly need to remember that.
204   // (2) We can keep the offset in the zeroth field, but since
205   // the code above might have modified the copy, we need to remember
206   // what was in that field before.
207   // (3) We can overwrite the header with all 1's to indicate that
208   // we've visited (but see notes on 'static header_t visited' above).
209   // (4) All objects in OCaml are at least one word long (we hope!).
210   struct restore_item restore_item;
211   restore_item.header = header;
212   restore_item.field_zero = Field (obj, 0);
213   area_append (restore, &restore_item, sizeof restore_item);
214
215   memcpy (header, (void *)&visited, sizeof visited);
216   Field (obj, 0) = Val_long (offset);
217
218   return offset;
219 }
220
221 // See comments immediately above.
222 static void
223 do_restore (area *ptr, area *restore)
224 {
225   mlsize_t i;
226   for (i = 0; i < restore->n; i += sizeof (struct restore_item))
227     {
228       struct restore_item *restore_item =
229         (struct restore_item *)(restore->ptr + i);
230       assert (memcmp (restore_item->header, &visited, sizeof visited) == 0);
231
232       value obj = Val_hp (restore_item->header);
233       size_t offset = Long_val (Field (obj, 0));
234
235       char *obj_copy_header = ptr->ptr + offset;
236       //value obj_copy = Val_hp (obj_copy_header);
237
238       // Restore the original header.
239       memcpy (restore_item->header, obj_copy_header, sizeof visited);
240
241       // Restore the original zeroth field.
242       Field (obj, 0) = restore_item->field_zero;
243     }
244 }
245
246 // Fixup fake pointers.
247 static void
248 do_fixups (area *ptr, area *fixups)
249 {
250   long i;
251
252   for (i = 0; i < fixups->n; i += sizeof (size_t))
253     {
254       size_t fixup = *(size_t *)(fixups->ptr + i);
255       size_t offset = *(size_t *)(ptr->ptr + fixup);
256       void *real_ptr = ptr->ptr + offset;
257       *(value *)(ptr->ptr + fixup) = (value) real_ptr;
258     }
259 }
260
261 static void *
262 mark (value obj,
263          void *(*realloc)(void *data, void *ptr, size_t size),
264          void (*free)(void *data, void *ptr),
265          void *data)
266 {
267   area ptr; // This will be the out of heap area.
268   area_init_custom (&ptr, realloc, free, data);
269   area restore; // Headers to be fixed up after.
270   area_init (&restore);
271   area fixups; // List of fake pointers to be fixed up.
272   area_init (&fixups);
273
274   if (_mark (obj, &ptr, &restore, &fixups) == -1) {
275     // Ran out of memory.  Recover and throw an exception.
276     area_free (&fixups);
277     do_restore (&ptr, &restore);
278     area_free (&restore);
279     area_free (&ptr);
280     caml_failwith ("out of memory");
281   }
282   area_shrink (&ptr);
283
284   // Restore Caml heap structures.
285   do_restore (&ptr, &restore);
286   area_free (&restore);
287
288   // Update all fake pointers in the out of heap area to make them real
289   // pointers.
290   do_fixups (&ptr, &fixups);
291   area_free (&fixups);
292
293   return ptr.ptr;
294 }
295
296 static void *
297 my_realloc (void *data __attribute__((unused)), void *ptr, size_t size)
298 {
299   return realloc (ptr, size);
300 }
301
302 static void
303 my_free (void *data __attribute__((unused)), void *ptr)
304 {
305   return free (ptr);
306 }
307
308 CAMLprim value
309 ancient_mark (value obj)
310 {
311   CAMLparam1 (obj);
312   CAMLlocal1 (proxy);
313
314   void *ptr = mark (obj, my_realloc, my_free, 0);
315
316   // Return the proxy.
317   proxy = caml_alloc (1, Abstract_tag);
318   Field (proxy, 0) = (value) ptr;
319
320   CAMLreturn (proxy);
321 }
322
323 CAMLprim value
324 ancient_follow (value obj)
325 {
326   CAMLparam1 (obj);
327   CAMLlocal1 (v);
328
329   v = Field (obj, 0);
330   if (Is_long (v)) caml_invalid_argument ("deleted");
331   v = Val_hp (v); // v points to the header; make it point to the object.
332
333   CAMLreturn (v);
334 }
335
336 CAMLprim value
337 ancient_delete (value obj)
338 {
339   CAMLparam1 (obj);
340   CAMLlocal1 (v);
341
342   v = Field (obj, 0);
343   if (Is_long (v)) caml_invalid_argument ("deleted");
344
345   // Otherwise v is a pointer to the out of heap malloc'd object.
346   assert (!Is_young (v) && !Is_in_heap (v));
347   free ((void *) v);
348
349   // Replace the proxy (a pointer) with an int 0 so we know it's
350   // been deleted in future.
351   Field (obj, 0) = Val_long (0);
352
353   CAMLreturn (Val_unit);
354 }
355
356 CAMLprim value
357 ancient_attach (value fdv, value baseaddrv)
358 {
359   CAMLparam2 (fdv, baseaddrv);
360   CAMLlocal1 (mdv);
361
362   int fd = Int_val (fdv);
363   void *baseaddr = (void *) Nativeint_val (baseaddrv);
364   void *md = mmalloc_attach (fd, baseaddr);
365   if (md == 0) {
366     perror ("mmalloc_attach");
367     caml_failwith ("mmalloc_attach");
368   }
369
370   mdv = caml_alloc (1, Abstract_tag);
371   Field (mdv, 0) = (value) md;
372
373   CAMLreturn (mdv);
374 }
375
376 CAMLprim value
377 ancient_detach (value mdv)
378 {
379   CAMLparam1 (mdv);
380
381   void *md = (void *) Field (mdv, 0);
382
383   if (mmalloc_detach (md) != 0) {
384     perror ("mmalloc_detach");
385     caml_failwith ("mmalloc_detach");
386   }
387
388   CAMLreturn (Val_unit);
389 }
390
391 CAMLprim value
392 ancient_share (value mdv, value keyv, value obj)
393 {
394   CAMLparam3 (mdv, keyv, obj);
395   CAMLlocal1 (proxy);
396
397   void *md = (void *) Field (mdv, 0);
398   int key = Int_val (keyv);
399
400   // Existing key exists?  Free it.
401   void *old_obj = mmalloc_getkey (md, key);
402   if (old_obj != 0) mfree (md, old_obj);
403   mmalloc_setkey (md, key, 0);
404
405   void *ptr = mark (obj, mrealloc, mfree, md);
406
407   mmalloc_setkey (md, key, ptr);
408
409   // Return the proxy.
410   proxy = caml_alloc (1, Abstract_tag);
411   Field (proxy, 0) = (value) ptr;
412
413   CAMLreturn (proxy);
414 }
415
416 CAMLprim value
417 ancient_get (value mdv, value keyv)
418 {
419   CAMLparam2 (mdv, keyv);
420   CAMLlocal1 (proxy);
421
422   void *md = (void *) Field (mdv, 0);
423   int key = Int_val (keyv);
424
425   void *ptr = mmalloc_getkey (md, key);
426   if (!ptr) caml_raise_not_found ();
427
428   // Return the proxy.
429   proxy = caml_alloc (1, Abstract_tag);
430   Field (proxy, 0) = (value) ptr;
431
432   CAMLreturn (proxy);
433 }