Added:
[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.8 2006-10-09 12:18:05 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   // XXX This assertion might fail if someone tries to mark an object
149   // which is already ancient.
150   assert (Is_young (obj) || Is_in_heap (obj));
151
152   char *header = Hp_val (obj);
153
154   // If we've already visited this object, just return its offset
155   // in the out-of-heap memory.
156   if (memcmp (header, &visited, sizeof visited) == 0)
157     return (Long_val (Field (obj, 0)));
158
159   // XXX Actually this fails if you try to persist a zero-length
160   // array.  Needs to be fixed, but it breaks some rather important
161   // functions below.
162   assert (Wosize_hp (header) > 0);
163
164   // Offset where we will store this object in the out-of-heap memory.
165   size_t offset = ptr->n;
166
167   // Copy the object out of the OCaml heap.
168   size_t bytes = Bhsize_hp (header);
169   if (area_append (ptr, header, bytes) == -1)
170     return -1;                  // Error out of memory.
171
172   // Scan the fields looking for pointers to blocks.
173   int can_scan = Tag_val (obj) < No_scan_tag;
174   if (can_scan) {
175     mlsize_t nr_words = Wosize_hp (header);
176     mlsize_t i;
177
178     for (i = 0; i < nr_words; ++i) {
179       value field = Field (obj, i);
180
181       if (Is_block (field) &&
182           (Is_young (field) || Is_in_heap (field))) {
183         size_t field_offset = _mark (field, ptr, restore, fixups);
184         if (field_offset == -1) return -1; // Propagate out of memory errors.
185
186         // Since the recursive call to mark above can reallocate the
187         // area, we need to recompute these each time round the loop.
188         char *obj_copy_header = ptr->ptr + offset;
189         value obj_copy = Val_hp (obj_copy_header);
190
191         // Don't store absolute pointers yet because realloc will
192         // move the memory around.  Store a fake pointer instead.
193         // We'll fix up these fake pointers afterwards in do_fixups.
194         Field (obj_copy, i) = field_offset + sizeof (header_t);
195
196         size_t fixup = (void *)&Field(obj_copy, i) - ptr->ptr;
197         area_append (fixups, &fixup, sizeof fixup);
198       }
199     }
200   }
201
202   // Mark this object as having been "visited", but keep track of
203   // what was there before so it can be restored.  We also need to
204   // record the offset.
205   // Observations:
206   // (1) What was in the header before is kept in the out-of-heap
207   // copy, so we don't explicitly need to remember that.
208   // (2) We can keep the offset in the zeroth field, but since
209   // the code above might have modified the copy, we need to remember
210   // what was in that field before.
211   // (3) We can overwrite the header with all 1's to indicate that
212   // we've visited (but see notes on 'static header_t visited' above).
213   // (4) All objects in OCaml are at least one word long (we hope!).
214   struct restore_item restore_item;
215   restore_item.header = header;
216   restore_item.field_zero = Field (obj, 0);
217   area_append (restore, &restore_item, sizeof restore_item);
218
219   memcpy (header, (void *)&visited, sizeof visited);
220   Field (obj, 0) = Val_long (offset);
221
222   return offset;
223 }
224
225 // See comments immediately above.
226 static void
227 do_restore (area *ptr, area *restore)
228 {
229   mlsize_t i;
230   for (i = 0; i < restore->n; i += sizeof (struct restore_item))
231     {
232       struct restore_item *restore_item =
233         (struct restore_item *)(restore->ptr + i);
234       assert (memcmp (restore_item->header, &visited, sizeof visited) == 0);
235
236       value obj = Val_hp (restore_item->header);
237       size_t offset = Long_val (Field (obj, 0));
238
239       char *obj_copy_header = ptr->ptr + offset;
240       //value obj_copy = Val_hp (obj_copy_header);
241
242       // Restore the original header.
243       memcpy (restore_item->header, obj_copy_header, sizeof visited);
244
245       // Restore the original zeroth field.
246       Field (obj, 0) = restore_item->field_zero;
247     }
248 }
249
250 // Fixup fake pointers.
251 static void
252 do_fixups (area *ptr, area *fixups)
253 {
254   long i;
255
256   for (i = 0; i < fixups->n; i += sizeof (size_t))
257     {
258       size_t fixup = *(size_t *)(fixups->ptr + i);
259       size_t offset = *(size_t *)(ptr->ptr + fixup);
260       void *real_ptr = ptr->ptr + offset;
261       *(value *)(ptr->ptr + fixup) = (value) real_ptr;
262     }
263 }
264
265 static void *
266 mark (value obj,
267          void *(*realloc)(void *data, void *ptr, size_t size),
268          void (*free)(void *data, void *ptr),
269          void *data)
270 {
271   area ptr; // This will be the out of heap area.
272   area_init_custom (&ptr, realloc, free, data);
273   area restore; // Headers to be fixed up after.
274   area_init (&restore);
275   area fixups; // List of fake pointers to be fixed up.
276   area_init (&fixups);
277
278   if (_mark (obj, &ptr, &restore, &fixups) == -1) {
279     // Ran out of memory.  Recover and throw an exception.
280     area_free (&fixups);
281     do_restore (&ptr, &restore);
282     area_free (&restore);
283     area_free (&ptr);
284     caml_failwith ("out of memory");
285   }
286   area_shrink (&ptr);
287
288   // Restore Caml heap structures.
289   do_restore (&ptr, &restore);
290   area_free (&restore);
291
292   // Update all fake pointers in the out of heap area to make them real
293   // pointers.
294   do_fixups (&ptr, &fixups);
295   area_free (&fixups);
296
297   return ptr.ptr;
298 }
299
300 static void *
301 my_realloc (void *data __attribute__((unused)), void *ptr, size_t size)
302 {
303   return realloc (ptr, size);
304 }
305
306 static void
307 my_free (void *data __attribute__((unused)), void *ptr)
308 {
309   return free (ptr);
310 }
311
312 CAMLprim value
313 ancient_mark (value obj)
314 {
315   CAMLparam1 (obj);
316   CAMLlocal1 (proxy);
317
318   void *ptr = mark (obj, my_realloc, my_free, 0);
319
320   // Return the proxy.
321   proxy = caml_alloc (1, Abstract_tag);
322   Field (proxy, 0) = (value) ptr;
323
324   CAMLreturn (proxy);
325 }
326
327 CAMLprim value
328 ancient_follow (value obj)
329 {
330   CAMLparam1 (obj);
331   CAMLlocal1 (v);
332
333   v = Field (obj, 0);
334   if (Is_long (v)) caml_invalid_argument ("deleted");
335   v = Val_hp (v); // v points to the header; make it point to the object.
336
337   CAMLreturn (v);
338 }
339
340 CAMLprim value
341 ancient_delete (value obj)
342 {
343   CAMLparam1 (obj);
344   CAMLlocal1 (v);
345
346   v = Field (obj, 0);
347   if (Is_long (v)) caml_invalid_argument ("deleted");
348
349   // Otherwise v is a pointer to the out of heap malloc'd object.
350   assert (!Is_young (v) && !Is_in_heap (v));
351   free ((void *) v);
352
353   // Replace the proxy (a pointer) with an int 0 so we know it's
354   // been deleted in future.
355   Field (obj, 0) = Val_long (0);
356
357   CAMLreturn (Val_unit);
358 }
359
360 CAMLprim value
361 ancient_is_ancient (value obj)
362 {
363   CAMLparam1 (obj);
364   CAMLlocal1 (v);
365
366   v = Is_young (obj) || Is_in_heap (obj) ? Val_false : Val_true;
367
368   CAMLreturn (v);
369 }
370
371 CAMLprim value
372 ancient_attach (value fdv, value baseaddrv)
373 {
374   CAMLparam2 (fdv, baseaddrv);
375   CAMLlocal1 (mdv);
376
377   int fd = Int_val (fdv);
378   void *baseaddr = (void *) Nativeint_val (baseaddrv);
379   void *md = mmalloc_attach (fd, baseaddr);
380   if (md == 0) {
381     perror ("mmalloc_attach");
382     caml_failwith ("mmalloc_attach");
383   }
384
385   mdv = caml_alloc (1, Abstract_tag);
386   Field (mdv, 0) = (value) md;
387
388   CAMLreturn (mdv);
389 }
390
391 CAMLprim value
392 ancient_detach (value mdv)
393 {
394   CAMLparam1 (mdv);
395
396   void *md = (void *) Field (mdv, 0);
397
398   if (mmalloc_detach (md) != 0) {
399     perror ("mmalloc_detach");
400     caml_failwith ("mmalloc_detach");
401   }
402
403   CAMLreturn (Val_unit);
404 }
405
406 CAMLprim value
407 ancient_share (value mdv, value keyv, value obj)
408 {
409   CAMLparam3 (mdv, keyv, obj);
410   CAMLlocal1 (proxy);
411
412   void *md = (void *) Field (mdv, 0);
413   int key = Int_val (keyv);
414
415   // Existing key exists?  Free it.
416   void *old_obj = mmalloc_getkey (md, key);
417   if (old_obj != 0) mfree (md, old_obj);
418   mmalloc_setkey (md, key, 0);
419
420   void *ptr = mark (obj, mrealloc, mfree, md);
421
422   mmalloc_setkey (md, key, ptr);
423
424   // Return the proxy.
425   proxy = caml_alloc (1, Abstract_tag);
426   Field (proxy, 0) = (value) ptr;
427
428   CAMLreturn (proxy);
429 }
430
431 CAMLprim value
432 ancient_get (value mdv, value keyv)
433 {
434   CAMLparam2 (mdv, keyv);
435   CAMLlocal1 (proxy);
436
437   void *md = (void *) Field (mdv, 0);
438   int key = Int_val (keyv);
439
440   void *ptr = mmalloc_getkey (md, key);
441   if (!ptr) caml_raise_not_found ();
442
443   // Return the proxy.
444   proxy = caml_alloc (1, Abstract_tag);
445   Field (proxy, 0) = (value) ptr;
446
447   CAMLreturn (proxy);
448 }