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