Merge branch 'master' of ssh://git.gag.com/scm/git/fw/altos
[fw/altos] / src / scheme / ao_scheme_mem.c
1 /*
2  * Copyright © 2016 Keith Packard <keithp@keithp.com>
3  *
4  * This program is free software; you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 2 of the License, or
7  * (at your option) any later version.
8  *
9  * This program 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  * General Public License for more details.
13  */
14
15 #define AO_SCHEME_CONST_BITS
16
17 #include "ao_scheme.h"
18 #include <stdio.h>
19 #include <assert.h>
20
21 #ifdef AO_SCHEME_MAKE_CONST
22
23 /*
24  * When building the constant table, it is the
25  * pool for allocations.
26  */
27
28 #include <stdlib.h>
29 uint8_t ao_scheme_const[AO_SCHEME_POOL_CONST] __attribute__((aligned(4)));
30 #define ao_scheme_pool ao_scheme_const
31 #undef AO_SCHEME_POOL
32 #define AO_SCHEME_POOL AO_SCHEME_POOL_CONST
33
34 #else
35
36 uint8_t ao_scheme_pool[AO_SCHEME_POOL + AO_SCHEME_POOL_EXTRA] __attribute__((aligned(4)));
37
38 #endif
39
40 #ifndef DBG_MEM_STATS
41 #define DBG_MEM_STATS   DBG_MEM
42 #endif
43
44 #if DBG_MEM
45 int dbg_move_depth;
46 int dbg_mem = DBG_MEM_START;
47 int dbg_validate = 0;
48
49 struct ao_scheme_record {
50         struct ao_scheme_record         *next;
51         const struct ao_scheme_type     *type;
52         void                            *addr;
53         int                             size;
54 };
55
56 static struct ao_scheme_record  *record_head, **record_tail;
57
58 static void
59 ao_scheme_record_free(struct ao_scheme_record *record)
60 {
61         while (record) {
62                 struct ao_scheme_record *next = record->next;
63                 free(record);
64                 record = next;
65         }
66 }
67
68 static void
69 ao_scheme_record_reset(void)
70 {
71         ao_scheme_record_free(record_head);
72         record_head = NULL;
73         record_tail = &record_head;
74 }
75
76 static void
77 ao_scheme_record(const struct ao_scheme_type    *type,
78                void                             *addr,
79                int                              size)
80 {
81         struct ao_scheme_record *r = malloc(sizeof (struct ao_scheme_record));
82
83         r->next = NULL;
84         r->type = type;
85         r->addr = addr;
86         r->size = size;
87         *record_tail = r;
88         record_tail = &r->next;
89 }
90
91 static struct ao_scheme_record *
92 ao_scheme_record_save(void)
93 {
94         struct ao_scheme_record *r = record_head;
95
96         record_head = NULL;
97         record_tail = &record_head;
98         return r;
99 }
100
101 static void
102 ao_scheme_record_compare(char *where,
103                        struct ao_scheme_record *a,
104                        struct ao_scheme_record *b)
105 {
106         while (a && b) {
107                 if (a->type != b->type || a->size != b->size) {
108                         printf("%s record difers %d %s %d -> %d %s %d\n",
109                                where,
110                                MDBG_OFFSET(a->addr),
111                                a->type->name,
112                                a->size,
113                                MDBG_OFFSET(b->addr),
114                                b->type->name,
115                                b->size);
116                         ao_scheme_abort();
117                 }
118                 a = a->next;
119                 b = b->next;
120         }
121         if (a) {
122                 printf("%s record differs %d %s %d -> NULL\n",
123                        where,
124                        MDBG_OFFSET(a->addr),
125                        a->type->name,
126                        a->size);
127                 ao_scheme_abort();
128         }
129         if (b) {
130                 printf("%s record differs NULL -> %d %s %d\n",
131                        where,
132                        MDBG_OFFSET(b->addr),
133                        b->type->name,
134                        b->size);
135                 ao_scheme_abort();
136         }
137 }
138
139 #else
140 #define ao_scheme_record_reset()
141 #endif
142
143 uint8_t ao_scheme_exception;
144
145 struct ao_scheme_root {
146         const struct ao_scheme_type     *type;
147         void                            **addr;
148 };
149
150 static struct ao_scheme_cons    *save_cons[2];
151 static char                     *save_string[2];
152 static struct ao_scheme_frame   *save_frame[1];
153 static ao_poly                  save_poly[3];
154
155 static const struct ao_scheme_root      ao_scheme_root[] = {
156         {
157                 .type = &ao_scheme_cons_type,
158                 .addr = (void **) &save_cons[0],
159         },
160         {
161                 .type = &ao_scheme_cons_type,
162                 .addr = (void **) &save_cons[1],
163         },
164         {
165                 .type = &ao_scheme_string_type,
166                 .addr = (void **) &save_string[0],
167         },
168         {
169                 .type = &ao_scheme_string_type,
170                 .addr = (void **) &save_string[1],
171         },
172         {
173                 .type = &ao_scheme_frame_type,
174                 .addr = (void **) &save_frame[0],
175         },
176         {
177                 .type = NULL,
178                 .addr = (void **) (void *) &save_poly[0]
179         },
180         {
181                 .type = NULL,
182                 .addr = (void **) (void *) &save_poly[1]
183         },
184         {
185                 .type = NULL,
186                 .addr = (void **) (void *) &save_poly[2]
187         },
188         {
189                 .type = &ao_scheme_atom_type,
190                 .addr = (void **) &ao_scheme_atoms
191         },
192         {
193                 .type = &ao_scheme_frame_type,
194                 .addr = (void **) &ao_scheme_frame_global,
195         },
196         {
197                 .type = &ao_scheme_frame_type,
198                 .addr = (void **) &ao_scheme_frame_current,
199         },
200         {
201                 .type = &ao_scheme_stack_type,
202                 .addr = (void **) &ao_scheme_stack,
203         },
204         {
205                 .type = NULL,
206                 .addr = (void **) (void *) &ao_scheme_v,
207         },
208         {
209                 .type = &ao_scheme_cons_type,
210                 .addr = (void **) &ao_scheme_read_cons,
211         },
212         {
213                 .type = &ao_scheme_cons_type,
214                 .addr = (void **) &ao_scheme_read_cons_tail,
215         },
216         {
217                 .type = &ao_scheme_cons_type,
218                 .addr = (void **) &ao_scheme_read_stack,
219         },
220 #ifdef AO_SCHEME_MAKE_CONST
221         {
222                 .type = &ao_scheme_bool_type,
223                 .addr = (void **) &ao_scheme_false,
224         },
225         {
226                 .type = &ao_scheme_bool_type,
227                 .addr = (void **) &ao_scheme_true,
228         },
229 #endif
230 };
231
232 #define AO_SCHEME_ROOT  (sizeof (ao_scheme_root) / sizeof (ao_scheme_root[0]))
233
234 static const void ** const ao_scheme_cache[] = {
235         (const void **) &ao_scheme_cons_free_list,
236         (const void **) &ao_scheme_stack_free_list,
237         (const void **) &ao_scheme_frame_free_list[0],
238         (const void **) &ao_scheme_frame_free_list[1],
239         (const void **) &ao_scheme_frame_free_list[2],
240         (const void **) &ao_scheme_frame_free_list[3],
241         (const void **) &ao_scheme_frame_free_list[4],
242         (const void **) &ao_scheme_frame_free_list[5],
243 };
244
245 #if AO_SCHEME_FRAME_FREE != 6
246 #error Unexpected AO_SCHEME_FRAME_FREE value
247 #endif
248
249 #define AO_SCHEME_CACHE (sizeof (ao_scheme_cache) / sizeof (ao_scheme_cache[0]))
250
251 #define AO_SCHEME_BUSY_SIZE     ((AO_SCHEME_POOL + 31) / 32)
252
253 static uint8_t  ao_scheme_busy[AO_SCHEME_BUSY_SIZE];
254 static uint8_t  ao_scheme_cons_note[AO_SCHEME_BUSY_SIZE];
255 static uint8_t  ao_scheme_cons_last[AO_SCHEME_BUSY_SIZE];
256 static uint8_t  ao_scheme_cons_noted;
257
258 uint16_t        ao_scheme_top;
259
260 struct ao_scheme_chunk {
261         uint16_t                old_offset;
262         union {
263                 uint16_t        size;
264                 uint16_t        new_offset;
265         };
266 };
267
268 #define AO_SCHEME_NCHUNK        64
269
270 static struct ao_scheme_chunk ao_scheme_chunk[AO_SCHEME_NCHUNK];
271
272 /* Offset of an address within the pool. */
273 static inline uint16_t pool_offset(void *addr) {
274 #if DBG_MEM
275         if (!AO_SCHEME_IS_POOL(addr))
276                 ao_scheme_abort();
277 #endif
278         return ((uint8_t *) addr) - ao_scheme_pool;
279 }
280
281 static inline void mark(uint8_t *tag, int offset) {
282         int     byte = offset >> 5;
283         int     bit = (offset >> 2) & 7;
284         tag[byte] |= (1 << bit);
285 }
286
287 static inline void clear(uint8_t *tag, int offset) {
288         int     byte = offset >> 5;
289         int     bit = (offset >> 2) & 7;
290         tag[byte] &= ~(1 << bit);
291 }
292
293 static inline int busy(uint8_t *tag, int offset) {
294         int     byte = offset >> 5;
295         int     bit = (offset >> 2) & 7;
296         return (tag[byte] >> bit) & 1;
297 }
298
299 static inline int min(int a, int b) { return a < b ? a : b; }
300 static inline int max(int a, int b) { return a > b ? a : b; }
301
302 static inline int limit(int offset) {
303         return min(AO_SCHEME_POOL, max(offset, 0));
304 }
305
306 static void
307 note_cons(uint16_t offset)
308 {
309         MDBG_MOVE("note cons %d\n", offset);
310         ao_scheme_cons_noted = 1;
311         mark(ao_scheme_cons_note, offset);
312 }
313
314 static uint16_t chunk_low, chunk_high;
315 static uint16_t chunk_first, chunk_last;
316
317 static int
318 find_chunk(uint16_t offset)
319 {
320         int l, r;
321         /* Binary search for the location */
322         l = chunk_first;
323         r = chunk_last - 1;
324         while (l <= r) {
325                 int m = (l + r) >> 1;
326                 if (ao_scheme_chunk[m].old_offset < offset)
327                         l = m + 1;
328                 else
329                         r = m - 1;
330         }
331         return l;
332 }
333
334 static void
335 note_chunk(uint16_t offset, uint16_t size)
336 {
337         int l;
338
339         if (offset < chunk_low || chunk_high <= offset)
340                 return;
341
342         l = find_chunk(offset);
343
344         /*
345          * The correct location is always in 'l', with r = l-1 being
346          * the entry before the right one
347          */
348
349 #if DBG_MEM
350         /* Off the right side */
351         if (l >= AO_SCHEME_NCHUNK)
352                 ao_scheme_abort();
353
354         /* Off the left side */
355         if (l == 0 && chunk_last && offset > ao_scheme_chunk[0].old_offset)
356                 ao_scheme_abort();
357 #endif
358
359         /* Shuffle existing entries right */
360         int end = min(AO_SCHEME_NCHUNK, chunk_last + 1);
361
362         memmove(&ao_scheme_chunk[l+1],
363                 &ao_scheme_chunk[l],
364                 (end - (l+1)) * sizeof (struct ao_scheme_chunk));
365
366         /* Add new entry */
367         ao_scheme_chunk[l].old_offset = offset;
368         ao_scheme_chunk[l].size = size;
369
370         /* Increment the number of elements up to the size of the array */
371         if (chunk_last < AO_SCHEME_NCHUNK)
372                 chunk_last++;
373
374         /* Set the top address if the array is full */
375         if (chunk_last == AO_SCHEME_NCHUNK)
376                 chunk_high = ao_scheme_chunk[AO_SCHEME_NCHUNK-1].old_offset +
377                         ao_scheme_chunk[AO_SCHEME_NCHUNK-1].size;
378 }
379
380 static void
381 reset_chunks(void)
382 {
383         chunk_high = ao_scheme_top;
384         chunk_last = 0;
385         chunk_first = 0;
386 }
387
388 /*
389  * Walk all referenced objects calling functions on each one
390  */
391
392 static void
393 walk(int (*visit_addr)(const struct ao_scheme_type *type, void **addr),
394      int (*visit_poly)(ao_poly *p, uint8_t do_note_cons))
395 {
396         int i;
397
398         ao_scheme_record_reset();
399         memset(ao_scheme_busy, '\0', sizeof (ao_scheme_busy));
400         memset(ao_scheme_cons_note, '\0', sizeof (ao_scheme_cons_note));
401         ao_scheme_cons_noted = 0;
402         for (i = 0; i < (int) AO_SCHEME_ROOT; i++) {
403                 if (ao_scheme_root[i].type) {
404                         void **a = ao_scheme_root[i].addr, *v;
405                         if (a && (v = *a)) {
406                                 MDBG_MOVE("root ptr %d\n", MDBG_OFFSET(v));
407                                 visit_addr(ao_scheme_root[i].type, a);
408                         }
409                 } else {
410                         ao_poly *a = (ao_poly *) ao_scheme_root[i].addr, p;
411                         if (a && (p = *a)) {
412                                 MDBG_MOVE("root poly %d\n", MDBG_OFFSET(ao_scheme_ref(p)));
413                                 visit_poly(a, 0);
414                         }
415                 }
416         }
417         while (ao_scheme_cons_noted) {
418                 memcpy(ao_scheme_cons_last, ao_scheme_cons_note, sizeof (ao_scheme_cons_note));
419                 memset(ao_scheme_cons_note, '\0', sizeof (ao_scheme_cons_note));
420                 ao_scheme_cons_noted = 0;
421                 for (i = 0; i < AO_SCHEME_POOL; i += 4) {
422                         if (busy(ao_scheme_cons_last, i)) {
423                                 void *v = ao_scheme_pool + i;
424                                 MDBG_MOVE("root cons %d\n", MDBG_OFFSET(v));
425                                 visit_addr(&ao_scheme_cons_type, &v);
426                         }
427                 }
428         }
429 }
430
431 #if MDBG_DUMP
432 static void
433 dump_busy(void)
434 {
435         int     i;
436         MDBG_MOVE("busy:");
437         for (i = 0; i < ao_scheme_top; i += 4) {
438                 if ((i & 0xff) == 0) {
439                         MDBG_MORE("\n");
440                         MDBG_MOVE("%s", "");
441                 }
442                 else if ((i & 0x1f) == 0)
443                         MDBG_MORE(" ");
444                 if (busy(ao_scheme_busy, i))
445                         MDBG_MORE("*");
446                 else
447                         MDBG_MORE("-");
448         }
449         MDBG_MORE ("\n");
450 }
451 #define DUMP_BUSY()     dump_busy()
452 #else
453 #define DUMP_BUSY()
454 #endif
455
456 static const struct ao_scheme_type * const ao_scheme_types[AO_SCHEME_NUM_TYPE] = {
457         [AO_SCHEME_CONS] = &ao_scheme_cons_type,
458         [AO_SCHEME_INT] = NULL,
459         [AO_SCHEME_STRING] = &ao_scheme_string_type,
460         [AO_SCHEME_OTHER] = (void *) 0x1,
461         [AO_SCHEME_ATOM] = &ao_scheme_atom_type,
462         [AO_SCHEME_BUILTIN] = &ao_scheme_builtin_type,
463         [AO_SCHEME_FRAME] = &ao_scheme_frame_type,
464         [AO_SCHEME_FRAME_VALS] = &ao_scheme_frame_vals_type,
465         [AO_SCHEME_LAMBDA] = &ao_scheme_lambda_type,
466         [AO_SCHEME_STACK] = &ao_scheme_stack_type,
467         [AO_SCHEME_BOOL] = &ao_scheme_bool_type,
468         [AO_SCHEME_BIGINT] = &ao_scheme_bigint_type,
469         [AO_SCHEME_FLOAT] = &ao_scheme_float_type,
470         [AO_SCHEME_VECTOR] = &ao_scheme_vector_type,
471 };
472
473 static int
474 ao_scheme_mark_ref(const struct ao_scheme_type *type, void **ref)
475 {
476         return ao_scheme_mark(type, *ref);
477 }
478
479 static int
480 ao_scheme_poly_mark_ref(ao_poly *p, uint8_t do_note_cons)
481 {
482         return ao_scheme_poly_mark(*p, do_note_cons);
483 }
484
485 #if DBG_MEM_STATS
486 int ao_scheme_collects[2];
487 int ao_scheme_freed[2];
488 int ao_scheme_loops[2];
489 #endif
490
491 int ao_scheme_last_top;
492
493 int
494 ao_scheme_collect(uint8_t style)
495 {
496         int     i;
497         int     top;
498 #if DBG_MEM_STATS
499         int     loops = 0;
500 #endif
501 #if DBG_MEM
502         struct ao_scheme_record *mark_record = NULL, *move_record = NULL;
503
504         MDBG_MOVE("collect %d\n", ao_scheme_collects[style]);
505 #endif
506         MDBG_DO(ao_scheme_frame_write(ao_scheme_frame_poly(ao_scheme_frame_global)));
507
508         /* The first time through, we're doing a full collect */
509         if (ao_scheme_last_top == 0)
510                 style = AO_SCHEME_COLLECT_FULL;
511
512         /* Clear references to all caches */
513         for (i = 0; i < (int) AO_SCHEME_CACHE; i++)
514                 *ao_scheme_cache[i] = NULL;
515         if (style == AO_SCHEME_COLLECT_FULL) {
516                 chunk_low = top = 0;
517         } else {
518                 chunk_low = top = ao_scheme_last_top;
519         }
520         for (;;) {
521 #if DBG_MEM_STATS
522                 loops++;
523 #endif
524                 MDBG_MOVE("move chunks from %d to %d\n", chunk_low, top);
525                 /* Find the sizes of the first chunk of objects to move */
526                 reset_chunks();
527                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
528 #if DBG_MEM
529
530                 ao_scheme_record_free(mark_record);
531                 mark_record = ao_scheme_record_save();
532                 if (mark_record && move_record)
533                         ao_scheme_record_compare("mark", move_record, mark_record);
534 #endif
535
536                 DUMP_BUSY();
537
538                 /* Find the first moving object */
539                 for (i = 0; i < chunk_last; i++) {
540                         uint16_t        size = ao_scheme_chunk[i].size;
541
542 #if DBG_MEM
543                         if (!size)
544                                 ao_scheme_abort();
545 #endif
546
547                         if (ao_scheme_chunk[i].old_offset > top)
548                                 break;
549
550                         MDBG_MOVE("chunk %d %d not moving\n",
551                                   ao_scheme_chunk[i].old_offset,
552                                   ao_scheme_chunk[i].size);
553 #if DBG_MEM
554                         if (ao_scheme_chunk[i].old_offset != top)
555                                 ao_scheme_abort();
556 #endif
557                         top += size;
558                 }
559
560                 /*
561                  * Limit amount of chunk array used in mapping moves
562                  * to the active region
563                  */
564                 chunk_first = i;
565                 chunk_low = ao_scheme_chunk[i].old_offset;
566
567                 /* Copy all of the objects */
568                 for (; i < chunk_last; i++) {
569                         uint16_t        size = ao_scheme_chunk[i].size;
570
571 #if DBG_MEM
572                         if (!size)
573                                 ao_scheme_abort();
574 #endif
575
576                         MDBG_MOVE("chunk %d %d -> %d\n",
577                                   ao_scheme_chunk[i].old_offset,
578                                   size,
579                                   top);
580                         ao_scheme_chunk[i].new_offset = top;
581
582                         memmove(&ao_scheme_pool[top],
583                                 &ao_scheme_pool[ao_scheme_chunk[i].old_offset],
584                                 size);
585
586                         top += size;
587                 }
588
589                 if (chunk_first < chunk_last) {
590                         /* Relocate all references to the objects */
591                         walk(ao_scheme_move, ao_scheme_poly_move);
592
593 #if DBG_MEM
594                         ao_scheme_record_free(move_record);
595                         move_record = ao_scheme_record_save();
596                         if (mark_record && move_record)
597                                 ao_scheme_record_compare("move", mark_record, move_record);
598 #endif
599                 }
600
601                 /* If we ran into the end of the heap, then
602                  * there's no need to keep walking
603                  */
604                 if (chunk_last != AO_SCHEME_NCHUNK)
605                         break;
606
607                 /* Next loop starts right above this loop */
608                 chunk_low = chunk_high;
609         }
610
611 #if DBG_MEM_STATS
612         /* Collect stats */
613         ++ao_scheme_collects[style];
614         ao_scheme_freed[style] += ao_scheme_top - top;
615         ao_scheme_loops[style] += loops;
616 #endif
617
618         ao_scheme_top = top;
619         if (style == AO_SCHEME_COLLECT_FULL)
620                 ao_scheme_last_top = top;
621
622         MDBG_DO(memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
623                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref));
624
625         return AO_SCHEME_POOL - ao_scheme_top;
626 }
627
628 #if DBG_FREE_CONS
629 void
630 ao_scheme_cons_check(struct ao_scheme_cons *cons)
631 {
632         ao_poly cdr;
633         int offset;
634
635         chunk_low = 0;
636         reset_chunks();
637         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
638         while (cons) {
639                 if (!AO_SCHEME_IS_POOL(cons))
640                         break;
641                 offset = pool_offset(cons);
642                 if (busy(ao_scheme_busy, offset)) {
643                         ao_scheme_printf("cons at %p offset %d poly %d is busy\n\t%v\n", cons, offset, ao_scheme_cons_poly(cons), ao_scheme_cons_poly(cons));
644                         abort();
645                 }
646                 cdr = cons->cdr;
647                 if (!ao_scheme_is_pair(cdr))
648                         break;
649                 cons = ao_scheme_poly_cons(cdr);
650         }
651 }
652 #endif
653
654 /*
655  * Mark interfaces for objects
656  */
657
658
659 /*
660  * Mark a block of memory with an explicit size
661  */
662
663 int
664 ao_scheme_mark_block(void *addr, int size)
665 {
666         int offset;
667         if (!AO_SCHEME_IS_POOL(addr))
668                 return 1;
669
670         offset = pool_offset(addr);
671         MDBG_MOVE("mark memory %d\n", MDBG_OFFSET(addr));
672         if (busy(ao_scheme_busy, offset)) {
673                 MDBG_MOVE("already marked\n");
674                 return 1;
675         }
676         mark(ao_scheme_busy, offset);
677         note_chunk(offset, size);
678         return 0;
679 }
680
681 /*
682  * Note a reference to memory and collect information about a few
683  * object sizes at a time
684  */
685
686 int
687 ao_scheme_mark_memory(const struct ao_scheme_type *type, void *addr)
688 {
689         int offset;
690         if (!AO_SCHEME_IS_POOL(addr))
691                 return 1;
692
693         offset = pool_offset(addr);
694         MDBG_MOVE("mark memory %d\n", MDBG_OFFSET(addr));
695         if (busy(ao_scheme_busy, offset)) {
696                 MDBG_MOVE("already marked\n");
697                 return 1;
698         }
699         mark(ao_scheme_busy, offset);
700         note_chunk(offset, ao_scheme_size(type, addr));
701         return 0;
702 }
703
704 /*
705  * Mark an object and all that it refereces
706  */
707 int
708 ao_scheme_mark(const struct ao_scheme_type *type, void *addr)
709 {
710         int ret;
711         MDBG_MOVE("mark %d\n", MDBG_OFFSET(addr));
712         MDBG_MOVE_IN();
713         ret = ao_scheme_mark_memory(type, addr);
714         if (!ret) {
715                 MDBG_MOVE("mark recurse\n");
716                 type->mark(addr);
717         }
718         MDBG_MOVE_OUT();
719         return ret;
720 }
721
722 /*
723  * Mark an object, unless it is a cons cell and
724  * do_note_cons is set. In that case, just
725  * set a bit in the cons note array; those
726  * will be marked in a separate pass to avoid
727  * deep recursion in the collector
728  */
729 int
730 ao_scheme_poly_mark(ao_poly p, uint8_t do_note_cons)
731 {
732         uint8_t type;
733         void    *addr;
734
735         type = ao_scheme_poly_base_type(p);
736
737         if (type == AO_SCHEME_INT)
738                 return 1;
739
740         addr = ao_scheme_ref(p);
741         if (!AO_SCHEME_IS_POOL(addr))
742                 return 1;
743
744         if (type == AO_SCHEME_CONS && do_note_cons) {
745                 note_cons(pool_offset(addr));
746                 return 1;
747         } else {
748                 if (type == AO_SCHEME_OTHER)
749                         type = ao_scheme_other_type(addr);
750
751                 const struct ao_scheme_type *lisp_type = ao_scheme_types[type];
752 #if DBG_MEM
753                 if (!lisp_type)
754                         ao_scheme_abort();
755 #endif
756
757                 return ao_scheme_mark(lisp_type, addr);
758         }
759 }
760
761 /*
762  * Find the current location of an object
763  * based on the original location. For unmoved
764  * objects, this is simple. For moved objects,
765  * go search for it
766  */
767
768 static uint16_t
769 move_map(uint16_t offset)
770 {
771         int             l;
772
773         if (offset < chunk_low || chunk_high <= offset)
774                 return offset;
775
776         l = find_chunk(offset);
777
778 #if DBG_MEM
779         if (ao_scheme_chunk[l].old_offset != offset)
780                 ao_scheme_abort();
781 #endif
782         return ao_scheme_chunk[l].new_offset;
783 }
784
785 int
786 ao_scheme_move_memory(const struct ao_scheme_type *type, void **ref)
787 {
788         void            *addr = *ref;
789         uint16_t        offset, orig_offset;
790
791         if (!AO_SCHEME_IS_POOL(addr))
792                 return 1;
793
794         (void) type;
795
796         MDBG_MOVE("move memory %d\n", MDBG_OFFSET(addr));
797         orig_offset = pool_offset(addr);
798         offset = move_map(orig_offset);
799         if (offset != orig_offset) {
800                 MDBG_MOVE("update ref %d %d -> %d\n",
801                           AO_SCHEME_IS_POOL(ref) ? MDBG_OFFSET(ref) : -1,
802                           orig_offset, offset);
803                 *ref = ao_scheme_pool + offset;
804         }
805         if (busy(ao_scheme_busy, offset)) {
806                 MDBG_MOVE("already moved\n");
807                 return 1;
808         }
809         mark(ao_scheme_busy, offset);
810         MDBG_DO(ao_scheme_record(type, addr, ao_scheme_size(type, addr)));
811         return 0;
812 }
813
814 int
815 ao_scheme_move(const struct ao_scheme_type *type, void **ref)
816 {
817         int ret;
818         MDBG_MOVE("move object %d\n", MDBG_OFFSET(*ref));
819         MDBG_MOVE_IN();
820         ret = ao_scheme_move_memory(type, ref);
821         if (!ret) {
822                 MDBG_MOVE("move recurse\n");
823                 type->move(*ref);
824         }
825         MDBG_MOVE_OUT();
826         return ret;
827 }
828
829 int
830 ao_scheme_poly_move(ao_poly *ref, uint8_t do_note_cons)
831 {
832         uint8_t         type;
833         ao_poly         p = *ref;
834         int             ret;
835         void            *addr;
836         uint16_t        offset, orig_offset;
837         uint8_t         base_type;
838
839         base_type = type = ao_scheme_poly_base_type(p);
840
841         if (type == AO_SCHEME_INT)
842                 return 1;
843
844         addr = ao_scheme_ref(p);
845         if (!AO_SCHEME_IS_POOL(addr))
846                 return 1;
847
848         orig_offset = pool_offset(addr);
849         offset = move_map(orig_offset);
850
851         if (type == AO_SCHEME_CONS && do_note_cons) {
852                 note_cons(orig_offset);
853                 ret = 1;
854         } else {
855                 if (type == AO_SCHEME_OTHER)
856                         type = ao_scheme_other_type(ao_scheme_pool + offset);
857
858                 const struct ao_scheme_type *lisp_type = ao_scheme_types[type];
859 #if DBG_MEM
860                 if (!lisp_type)
861                         ao_scheme_abort();
862 #endif
863
864                 ret = ao_scheme_move(lisp_type, &addr);
865         }
866
867         /* Re-write the poly value */
868         if (offset != orig_offset) {
869                 ao_poly np = ao_scheme_poly(ao_scheme_pool + offset, base_type);
870                 MDBG_MOVE("poly %d moved %d -> %d\n",
871                           type, orig_offset, offset);
872                 *ref = np;
873         }
874         return ret;
875 }
876
877 #if DBG_MEM
878 void
879 ao_scheme_validate(void)
880 {
881         chunk_low = 0;
882         memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
883         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
884 }
885
886 int dbg_allocs;
887
888 #endif
889
890 void *
891 ao_scheme_alloc(int size)
892 {
893         void    *addr;
894
895         MDBG_DO(++dbg_allocs);
896         MDBG_DO(if (dbg_validate) ao_scheme_validate());
897         size = ao_scheme_size_round(size);
898         if (AO_SCHEME_POOL - ao_scheme_top < size &&
899             ao_scheme_collect(AO_SCHEME_COLLECT_INCREMENTAL) < size &&
900             ao_scheme_collect(AO_SCHEME_COLLECT_FULL) < size)
901         {
902                 ao_scheme_error(AO_SCHEME_OOM, "out of memory");
903                 return NULL;
904         }
905         addr = ao_scheme_pool + ao_scheme_top;
906         ao_scheme_top += size;
907         MDBG_MOVE("alloc %d size %d\n", MDBG_OFFSET(addr), size);
908         return addr;
909 }
910
911 void
912 ao_scheme_cons_stash(int id, struct ao_scheme_cons *cons)
913 {
914         assert(save_cons[id] == 0);
915         save_cons[id] = cons;
916 }
917
918 struct ao_scheme_cons *
919 ao_scheme_cons_fetch(int id)
920 {
921         struct ao_scheme_cons *cons = save_cons[id];
922         save_cons[id] = NULL;
923         return cons;
924 }
925
926 void
927 ao_scheme_poly_stash(int id, ao_poly poly)
928 {
929         assert(save_poly[id] == AO_SCHEME_NIL);
930         save_poly[id] = poly;
931 }
932
933 ao_poly
934 ao_scheme_poly_fetch(int id)
935 {
936         ao_poly poly = save_poly[id];
937         save_poly[id] = AO_SCHEME_NIL;
938         return poly;
939 }
940
941 void
942 ao_scheme_string_stash(int id, char *string)
943 {
944         assert(save_string[id] == NULL);
945         save_string[id] = string;
946 }
947
948 char *
949 ao_scheme_string_fetch(int id)
950 {
951         char *string = save_string[id];
952         save_string[id] = NULL;
953         return string;
954 }
955
956 void
957 ao_scheme_frame_stash(int id, struct ao_scheme_frame *frame)
958 {
959         assert(save_frame[id] == NULL);
960         save_frame[id] = frame;
961 }
962
963 struct ao_scheme_frame *
964 ao_scheme_frame_fetch(int id)
965 {
966         struct ao_scheme_frame *frame = save_frame[id];
967         save_frame[id] = NULL;
968         return frame;
969 }