altos/scheme: Use memory manager mark code to note recursive print
[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 int      ao_scheme_printing, ao_scheme_print_cleared;
284 #if DBG_MEM
285 static int      ao_scheme_collecting;
286 #endif
287 static uint8_t  ao_scheme_busy[AO_SCHEME_BUSY_SIZE];
288 static uint8_t  ao_scheme_cons_note[AO_SCHEME_BUSY_SIZE];
289 static uint8_t  ao_scheme_cons_last[AO_SCHEME_BUSY_SIZE];
290 static uint8_t  ao_scheme_cons_noted;
291
292 uint16_t        ao_scheme_top;
293
294 struct ao_scheme_chunk {
295         uint16_t                old_offset;
296         union {
297                 uint16_t        size;
298                 uint16_t        new_offset;
299         };
300 };
301
302 #define AO_SCHEME_NCHUNK        64
303
304 static struct ao_scheme_chunk ao_scheme_chunk[AO_SCHEME_NCHUNK];
305
306 /* Offset of an address within the pool. */
307 static inline uint16_t pool_offset(void *addr) {
308 #if DBG_MEM
309         if (!AO_SCHEME_IS_POOL(addr))
310                 ao_scheme_abort();
311 #endif
312         return ((uint8_t *) addr) - ao_scheme_pool;
313 }
314
315 static inline void mark(uint8_t *tag, int offset) {
316         int     byte = offset >> 5;
317         int     bit = (offset >> 2) & 7;
318         ao_scheme_check_stack();
319         tag[byte] |= (1 << bit);
320 }
321
322 static inline void clear(uint8_t *tag, int offset) {
323         int     byte = offset >> 5;
324         int     bit = (offset >> 2) & 7;
325         tag[byte] &= ~(1 << bit);
326 }
327
328 static inline int busy(uint8_t *tag, int offset) {
329         int     byte = offset >> 5;
330         int     bit = (offset >> 2) & 7;
331         return (tag[byte] >> bit) & 1;
332 }
333
334 static inline int min(int a, int b) { return a < b ? a : b; }
335 static inline int max(int a, int b) { return a > b ? a : b; }
336
337 static inline int limit(int offset) {
338         return min(AO_SCHEME_POOL, max(offset, 0));
339 }
340
341 static inline void
342 note_cons(uint16_t offset)
343 {
344         MDBG_MOVE("note cons %d\n", offset);
345         ao_scheme_cons_noted = 1;
346         mark(ao_scheme_cons_note, offset);
347 }
348
349 static uint16_t chunk_low, chunk_high;
350 static uint16_t chunk_first, chunk_last;
351
352 static int
353 find_chunk(uint16_t offset)
354 {
355         int l, r;
356         /* Binary search for the location */
357         l = chunk_first;
358         r = chunk_last - 1;
359         while (l <= r) {
360                 int m = (l + r) >> 1;
361                 if (ao_scheme_chunk[m].old_offset < offset)
362                         l = m + 1;
363                 else
364                         r = m - 1;
365         }
366         return l;
367 }
368
369 static void
370 note_chunk(uint16_t offset, uint16_t size)
371 {
372         int l;
373         int end;
374
375         if (offset < chunk_low || chunk_high <= offset)
376                 return;
377
378         l = find_chunk(offset);
379
380         /*
381          * The correct location is always in 'l', with r = l-1 being
382          * the entry before the right one
383          */
384
385 #if DBG_MEM
386         /* Off the right side */
387         if (l >= AO_SCHEME_NCHUNK)
388                 ao_scheme_abort();
389
390         /* Off the left side */
391         if (l == 0 && chunk_last && offset > ao_scheme_chunk[0].old_offset)
392                 ao_scheme_abort();
393 #endif
394
395         /* Shuffle existing entries right */
396         end = min(AO_SCHEME_NCHUNK, chunk_last + 1);
397
398         memmove(&ao_scheme_chunk[l+1],
399                 &ao_scheme_chunk[l],
400                 (end - (l+1)) * sizeof (struct ao_scheme_chunk));
401
402         /* Add new entry */
403         ao_scheme_chunk[l].old_offset = offset;
404         ao_scheme_chunk[l].size = size;
405
406         /* Increment the number of elements up to the size of the array */
407         if (chunk_last < AO_SCHEME_NCHUNK)
408                 chunk_last++;
409
410         /* Set the top address if the array is full */
411         if (chunk_last == AO_SCHEME_NCHUNK)
412                 chunk_high = ao_scheme_chunk[AO_SCHEME_NCHUNK-1].old_offset +
413                         ao_scheme_chunk[AO_SCHEME_NCHUNK-1].size;
414 }
415
416 static void
417 reset_chunks(void)
418 {
419         chunk_high = ao_scheme_top;
420         chunk_last = 0;
421         chunk_first = 0;
422 }
423
424 /*
425  * Walk all referenced objects calling functions on each one
426  */
427
428 static void
429 walk(int (*visit_addr)(const struct ao_scheme_type *type, void **addr),
430      int (*visit_poly)(ao_poly *p, uint8_t do_note_cons))
431 {
432         int i;
433
434         ao_scheme_record_reset();
435         memset(ao_scheme_busy, '\0', sizeof (ao_scheme_busy));
436         memset(ao_scheme_cons_note, '\0', sizeof (ao_scheme_cons_note));
437         ao_scheme_cons_noted = 0;
438         for (i = 0; i < (int) AO_SCHEME_ROOT; i++) {
439                 if (ao_scheme_root[i].type) {
440                         void **a = ao_scheme_root[i].addr, *v;
441                         if (a && (v = *a)) {
442                                 MDBG_MOVE("root ptr %d\n", MDBG_OFFSET(v));
443                                 visit_addr(ao_scheme_root[i].type, a);
444                         }
445                 } else {
446                         ao_poly *a = (ao_poly *) ao_scheme_root[i].addr, p;
447                         if (a && (p = *a)) {
448                                 MDBG_MOVE("root poly %d\n", MDBG_OFFSET(ao_scheme_ref(p)));
449                                 visit_poly(a, 0);
450                         }
451                 }
452         }
453         while (ao_scheme_cons_noted) {
454                 memcpy(ao_scheme_cons_last, ao_scheme_cons_note, sizeof (ao_scheme_cons_note));
455                 memset(ao_scheme_cons_note, '\0', sizeof (ao_scheme_cons_note));
456                 ao_scheme_cons_noted = 0;
457                 for (i = 0; i < AO_SCHEME_POOL; i += 4) {
458                         if (busy(ao_scheme_cons_last, i)) {
459                                 void *v = ao_scheme_pool + i;
460                                 MDBG_MOVE("root cons %d\n", MDBG_OFFSET(v));
461                                 visit_addr(&ao_scheme_cons_type, &v);
462                         }
463                 }
464         }
465 }
466
467 #if MDBG_DUMP
468 static void
469 dump_busy(void)
470 {
471         int     i;
472         MDBG_MOVE("busy:");
473         for (i = 0; i < ao_scheme_top; i += 4) {
474                 if ((i & 0xff) == 0) {
475                         MDBG_MORE("\n");
476                         MDBG_MOVE("%s", "");
477                 }
478                 else if ((i & 0x1f) == 0)
479                         MDBG_MORE(" ");
480                 if (busy(ao_scheme_busy, i))
481                         MDBG_MORE("*");
482                 else
483                         MDBG_MORE("-");
484         }
485         MDBG_MORE ("\n");
486 }
487 #define DUMP_BUSY()     dump_busy()
488 #else
489 #define DUMP_BUSY()
490 #endif
491
492 static const struct ao_scheme_type * const ao_scheme_types[AO_SCHEME_NUM_TYPE] = {
493         [AO_SCHEME_CONS] = &ao_scheme_cons_type,
494         [AO_SCHEME_INT] = NULL,
495 #ifdef AO_SCHEME_FEATURE_BIGINT
496         [AO_SCHEME_BIGINT] = &ao_scheme_bigint_type,
497 #endif
498         [AO_SCHEME_OTHER] = (void *) 0x1,
499         [AO_SCHEME_ATOM] = &ao_scheme_atom_type,
500         [AO_SCHEME_BUILTIN] = &ao_scheme_builtin_type,
501         [AO_SCHEME_FRAME] = &ao_scheme_frame_type,
502         [AO_SCHEME_FRAME_VALS] = &ao_scheme_frame_vals_type,
503         [AO_SCHEME_LAMBDA] = &ao_scheme_lambda_type,
504         [AO_SCHEME_STACK] = &ao_scheme_stack_type,
505         [AO_SCHEME_BOOL] = &ao_scheme_bool_type,
506         [AO_SCHEME_STRING] = &ao_scheme_string_type,
507 #ifdef AO_SCHEME_FEATURE_FLOAT
508         [AO_SCHEME_FLOAT] = &ao_scheme_float_type,
509 #endif
510 #ifdef AO_SCHEME_FEATURE_VECTOR
511         [AO_SCHEME_VECTOR] = &ao_scheme_vector_type,
512 #endif
513 };
514
515 static int
516 ao_scheme_mark(const struct ao_scheme_type *type, void *addr);
517
518 static int
519 ao_scheme_move(const struct ao_scheme_type *type, void **ref);
520
521 static int
522 ao_scheme_mark_ref(const struct ao_scheme_type *type, void **ref)
523 {
524         return ao_scheme_mark(type, *ref);
525 }
526
527 static int
528 ao_scheme_poly_mark_ref(ao_poly *p, uint8_t do_note_cons)
529 {
530         return ao_scheme_poly_mark(*p, do_note_cons);
531 }
532
533 #if DBG_MEM_STATS
534 uint64_t ao_scheme_collects[2];
535 uint64_t ao_scheme_freed[2];
536 uint64_t ao_scheme_loops[2];
537 #endif
538
539 int ao_scheme_last_top;
540 int ao_scheme_collect_counts;
541
542 int
543 ao_scheme_collect(uint8_t style)
544 {
545         ao_scheme_declare_stack
546         int     i;
547         int     top;
548 #if DBG_MEM_STATS
549         int     loops = 0;
550 #endif
551 #if DBG_MEM
552         struct ao_scheme_record *mark_record = NULL, *move_record = NULL;
553
554         MDBG_MOVE("collect %d\n", ao_scheme_collects[style]);
555 #endif
556         MDBG_DO(ao_scheme_frame_write(ao_scheme_frame_poly(ao_scheme_frame_global)));
557         MDBG_DO(++ao_scheme_collecting);
558
559         ao_scheme_reset_stack();
560
561         /* The first time through, we're doing a full collect */
562         if (ao_scheme_last_top == 0)
563                 style = AO_SCHEME_COLLECT_FULL;
564
565         /* One in a while, just do a full collect */
566
567         if (ao_scheme_collect_counts >= 128)
568                 style = AO_SCHEME_COLLECT_FULL;
569
570         if (style == AO_SCHEME_COLLECT_FULL)
571                 ao_scheme_collect_counts = 0;
572
573         /* Clear references to all caches */
574         for (i = 0; i < (int) AO_SCHEME_CACHE; i++)
575                 *ao_scheme_cache[i] = NULL;
576         if (style == AO_SCHEME_COLLECT_FULL) {
577                 chunk_low = top = 0;
578         } else {
579                 chunk_low = top = ao_scheme_last_top;
580         }
581         for (;;) {
582 #if DBG_MEM_STATS
583                 loops++;
584 #endif
585                 MDBG_MOVE("move chunks from %d to %d\n", chunk_low, top);
586                 /* Find the sizes of the first chunk of objects to move */
587                 reset_chunks();
588                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
589 #if DBG_MEM
590
591                 ao_scheme_record_free(mark_record);
592                 mark_record = ao_scheme_record_save();
593                 if (mark_record && move_record)
594                         ao_scheme_record_compare("mark", move_record, mark_record);
595 #endif
596
597                 DUMP_BUSY();
598
599                 /* Find the first moving object */
600                 for (i = 0; i < chunk_last; i++) {
601                         uint16_t        size = ao_scheme_chunk[i].size;
602
603 #if DBG_MEM
604                         if (!size)
605                                 ao_scheme_abort();
606 #endif
607
608                         if (ao_scheme_chunk[i].old_offset > top)
609                                 break;
610
611                         MDBG_MOVE("chunk %d %d not moving\n",
612                                   ao_scheme_chunk[i].old_offset,
613                                   ao_scheme_chunk[i].size);
614 #if DBG_MEM
615                         if (ao_scheme_chunk[i].old_offset != top)
616                                 ao_scheme_abort();
617 #endif
618                         top += size;
619                 }
620
621                 /*
622                  * Limit amount of chunk array used in mapping moves
623                  * to the active region
624                  */
625                 chunk_first = i;
626                 chunk_low = ao_scheme_chunk[i].old_offset;
627
628                 /* Copy all of the objects */
629                 for (; i < chunk_last; i++) {
630                         uint16_t        size = ao_scheme_chunk[i].size;
631
632 #if DBG_MEM
633                         if (!size)
634                                 ao_scheme_abort();
635 #endif
636
637                         MDBG_MOVE("chunk %d %d -> %d\n",
638                                   ao_scheme_chunk[i].old_offset,
639                                   size,
640                                   top);
641                         ao_scheme_chunk[i].new_offset = top;
642
643                         memmove(&ao_scheme_pool[top],
644                                 &ao_scheme_pool[ao_scheme_chunk[i].old_offset],
645                                 size);
646
647                         top += size;
648                 }
649
650                 if (chunk_first < chunk_last) {
651                         /* Relocate all references to the objects */
652                         walk(ao_scheme_move, ao_scheme_poly_move);
653
654 #if DBG_MEM
655                         ao_scheme_record_free(move_record);
656                         move_record = ao_scheme_record_save();
657                         if (mark_record && move_record)
658                                 ao_scheme_record_compare("move", mark_record, move_record);
659 #endif
660                 }
661
662                 /* If we ran into the end of the heap, then
663                  * there's no need to keep walking
664                  */
665                 if (chunk_last != AO_SCHEME_NCHUNK)
666                         break;
667
668                 /* Next loop starts right above this loop */
669                 chunk_low = chunk_high;
670         }
671
672 #if DBG_MEM_STATS
673         /* Collect stats */
674         ++ao_scheme_collects[style];
675         ao_scheme_freed[style] += ao_scheme_top - top;
676         ao_scheme_loops[style] += loops;
677 #endif
678
679         ao_scheme_top = top;
680         if (style == AO_SCHEME_COLLECT_FULL)
681                 ao_scheme_last_top = top;
682
683         MDBG_DO(memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
684                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref));
685
686 #if DBG_MEM_STACK
687         fprintf(stderr, "max collect stack depth %lu\n", mem_collect_max_depth);
688 #endif
689         MDBG_DO(--ao_scheme_collecting);
690         return AO_SCHEME_POOL - ao_scheme_top;
691 }
692
693 #if DBG_FREE_CONS
694 void
695 ao_scheme_cons_check(struct ao_scheme_cons *cons)
696 {
697         ao_poly cdr;
698         int offset;
699
700         chunk_low = 0;
701         reset_chunks();
702         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
703         while (cons) {
704                 if (!AO_SCHEME_IS_POOL(cons))
705                         break;
706                 offset = pool_offset(cons);
707                 if (busy(ao_scheme_busy, offset)) {
708                         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));
709                         abort();
710                 }
711                 cdr = cons->cdr;
712                 if (!ao_scheme_is_pair(cdr))
713                         break;
714                 cons = ao_scheme_poly_cons(cdr);
715         }
716 }
717 #endif
718
719 /*
720  * Mark interfaces for objects
721  */
722
723
724 /*
725  * Note a reference to memory and collect information about a few
726  * object sizes at a time
727  */
728
729 int
730 ao_scheme_mark_memory(const struct ao_scheme_type *type, void *addr)
731 {
732         int offset;
733         if (!AO_SCHEME_IS_POOL(addr))
734                 return 1;
735
736         offset = pool_offset(addr);
737         MDBG_MOVE("mark memory %d\n", MDBG_OFFSET(addr));
738         if (busy(ao_scheme_busy, offset)) {
739                 MDBG_MOVE("already marked\n");
740                 return 1;
741         }
742         mark(ao_scheme_busy, offset);
743         note_chunk(offset, ao_scheme_size(type, addr));
744         return 0;
745 }
746
747 /*
748  * Mark an object and all that it refereces
749  */
750 static int
751 ao_scheme_mark(const struct ao_scheme_type *type, void *addr)
752 {
753         int ret;
754         MDBG_MOVE("mark %d\n", MDBG_OFFSET(addr));
755         MDBG_MOVE_IN();
756         ret = ao_scheme_mark_memory(type, addr);
757         if (!ret) {
758                 MDBG_MOVE("mark recurse\n");
759                 type->mark(addr);
760         }
761         MDBG_MOVE_OUT();
762         return ret;
763 }
764
765 /*
766  * Mark an object, unless it is a cons cell and
767  * do_note_cons is set. In that case, just
768  * set a bit in the cons note array; those
769  * will be marked in a separate pass to avoid
770  * deep recursion in the collector
771  */
772 int
773 ao_scheme_poly_mark(ao_poly p, uint8_t do_note_cons)
774 {
775         uint8_t type;
776         void    *addr;
777         int     ret;
778
779         type = ao_scheme_poly_base_type(p);
780
781         if (type == AO_SCHEME_INT)
782                 return 1;
783
784         addr = ao_scheme_ref(p);
785         if (!AO_SCHEME_IS_POOL(addr))
786                 return 1;
787
788         if (type == AO_SCHEME_CONS && do_note_cons) {
789                 note_cons(pool_offset(addr));
790                 return 1;
791         } else {
792                 const struct ao_scheme_type *lisp_type;
793
794                 if (type == AO_SCHEME_OTHER)
795                         type = ao_scheme_other_type(addr);
796
797                 lisp_type = ao_scheme_types[type];
798 #if DBG_MEM
799                 if (!lisp_type)
800                         ao_scheme_abort();
801 #endif
802
803                 MDBG_MOVE("mark %d\n", MDBG_OFFSET(addr));
804                 MDBG_MOVE_IN();
805                 ret = ao_scheme_mark_memory(lisp_type, addr);
806                 if (!ret) {
807                         MDBG_MOVE("mark recurse\n");
808                         lisp_type->mark(addr);
809                 }
810                 MDBG_MOVE_OUT();
811                 return ret;
812         }
813 }
814
815 /*
816  * Find the current location of an object
817  * based on the original location. For unmoved
818  * objects, this is simple. For moved objects,
819  * go search for it
820  */
821
822 static uint16_t
823 move_map(uint16_t offset)
824 {
825         int             l;
826
827         if (offset < chunk_low || chunk_high <= offset)
828                 return offset;
829
830         l = find_chunk(offset);
831
832 #if DBG_MEM
833         if (ao_scheme_chunk[l].old_offset != offset)
834                 ao_scheme_abort();
835 #endif
836         return ao_scheme_chunk[l].new_offset;
837 }
838
839 int
840 ao_scheme_move_memory(const struct ao_scheme_type *type, void **ref)
841 {
842         void            *addr = *ref;
843         uint16_t        offset, orig_offset;
844
845         if (!AO_SCHEME_IS_POOL(addr))
846                 return 1;
847
848         (void) type;
849
850         MDBG_MOVE("move memory %d\n", MDBG_OFFSET(addr));
851         orig_offset = pool_offset(addr);
852         offset = move_map(orig_offset);
853         if (offset != orig_offset) {
854                 MDBG_MOVE("update ref %d %d -> %d\n",
855                           AO_SCHEME_IS_POOL(ref) ? MDBG_OFFSET(ref) : -1,
856                           orig_offset, offset);
857                 *ref = ao_scheme_pool + offset;
858         }
859         if (busy(ao_scheme_busy, offset)) {
860                 MDBG_MOVE("already moved\n");
861                 return 1;
862         }
863         mark(ao_scheme_busy, offset);
864         MDBG_DO(ao_scheme_record(type, addr, ao_scheme_size(type, addr)));
865         return 0;
866 }
867
868 static int
869 ao_scheme_move(const struct ao_scheme_type *type, void **ref)
870 {
871         int ret;
872         MDBG_MOVE("move object %d\n", MDBG_OFFSET(*ref));
873         MDBG_MOVE_IN();
874         ret = ao_scheme_move_memory(type, ref);
875         if (!ret) {
876                 MDBG_MOVE("move recurse\n");
877                 type->move(*ref);
878         }
879         MDBG_MOVE_OUT();
880         return ret;
881 }
882
883 int
884 ao_scheme_poly_move(ao_poly *ref, uint8_t do_note_cons)
885 {
886         ao_poly         p = *ref;
887         int             ret;
888         void            *addr;
889         uint16_t        offset, orig_offset;
890
891         if (ao_scheme_poly_base_type(p) == AO_SCHEME_INT)
892                 return 1;
893
894         addr = ao_scheme_ref(p);
895         if (!AO_SCHEME_IS_POOL(addr))
896                 return 1;
897
898         orig_offset = pool_offset(addr);
899         offset = move_map(orig_offset);
900
901         if (ao_scheme_poly_base_type(p) == AO_SCHEME_CONS && do_note_cons) {
902                 note_cons(orig_offset);
903                 ret = 1;
904         } else {
905                 uint8_t type = ao_scheme_poly_base_type(p);
906                 const struct ao_scheme_type *lisp_type;
907
908                 if (type == AO_SCHEME_OTHER)
909                         type = ao_scheme_other_type(ao_scheme_pool + offset);
910
911                 lisp_type = ao_scheme_types[type];
912 #if DBG_MEM
913                 if (!lisp_type)
914                         ao_scheme_abort();
915 #endif
916                 /* inline ao_scheme_move to save stack space */
917                 MDBG_MOVE("move object %d\n", MDBG_OFFSET(addr));
918                 MDBG_MOVE_IN();
919                 ret = ao_scheme_move_memory(lisp_type, &addr);
920                 if (!ret) {
921                         MDBG_MOVE("move recurse\n");
922                         lisp_type->move(addr);
923                 }
924                 MDBG_MOVE_OUT();
925         }
926
927         /* Re-write the poly value */
928         if (offset != orig_offset) {
929                 ao_poly np = ao_scheme_poly(ao_scheme_pool + offset, ao_scheme_poly_base_type(p));
930                 MDBG_MOVE("poly %d moved %d -> %d\n",
931                           type, orig_offset, offset);
932                 *ref = np;
933         }
934         return ret;
935 }
936
937 #if DBG_MEM
938 void
939 ao_scheme_validate(void)
940 {
941         chunk_low = 0;
942         memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
943         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
944 }
945
946 int dbg_allocs;
947
948 #endif
949
950 void *
951 ao_scheme_alloc(int size)
952 {
953         void    *addr;
954
955         MDBG_DO(++dbg_allocs);
956         MDBG_DO(if (dbg_validate) ao_scheme_validate());
957         size = ao_scheme_size_round(size);
958         if (AO_SCHEME_POOL - ao_scheme_top < size &&
959             ao_scheme_collect(AO_SCHEME_COLLECT_INCREMENTAL) < size &&
960             ao_scheme_collect(AO_SCHEME_COLLECT_FULL) < size)
961         {
962                 ao_scheme_error(AO_SCHEME_OOM, "out of memory");
963                 return NULL;
964         }
965         addr = ao_scheme_pool + ao_scheme_top;
966         ao_scheme_top += size;
967         MDBG_MOVE("alloc %d size %d\n", MDBG_OFFSET(addr), size);
968         return addr;
969 }
970
971 void
972 ao_scheme_cons_stash(int id, struct ao_scheme_cons *cons)
973 {
974         assert(save_cons[id] == 0);
975         save_cons[id] = cons;
976 }
977
978 struct ao_scheme_cons *
979 ao_scheme_cons_fetch(int id)
980 {
981         struct ao_scheme_cons *cons = save_cons[id];
982         save_cons[id] = NULL;
983         return cons;
984 }
985
986 void
987 ao_scheme_poly_stash(int id, ao_poly poly)
988 {
989         assert(save_poly[id] == AO_SCHEME_NIL);
990         save_poly[id] = poly;
991 }
992
993 ao_poly
994 ao_scheme_poly_fetch(int id)
995 {
996         ao_poly poly = save_poly[id];
997         save_poly[id] = AO_SCHEME_NIL;
998         return poly;
999 }
1000
1001 void
1002 ao_scheme_string_stash(int id, struct ao_scheme_string *string)
1003 {
1004         assert(save_string[id] == NULL);
1005         save_string[id] = string;
1006 }
1007
1008 struct ao_scheme_string *
1009 ao_scheme_string_fetch(int id)
1010 {
1011         struct ao_scheme_string *string = save_string[id];
1012         save_string[id] = NULL;
1013         return string;
1014 }
1015
1016 void
1017 ao_scheme_frame_stash(int id, struct ao_scheme_frame *frame)
1018 {
1019         assert(save_frame[id] == NULL);
1020         save_frame[id] = frame;
1021 }
1022
1023 struct ao_scheme_frame *
1024 ao_scheme_frame_fetch(int id)
1025 {
1026         struct ao_scheme_frame *frame = save_frame[id];
1027         save_frame[id] = NULL;
1028         return frame;
1029 }
1030
1031 int
1032 ao_scheme_print_mark_addr(void *addr)
1033 {
1034         int     offset;
1035
1036 #if DBG_MEM
1037         if (ao_scheme_collecting)
1038                 ao_scheme_abort();
1039 #endif
1040
1041         if (!AO_SCHEME_IS_POOL(addr))
1042                 return 1;
1043
1044         if (!ao_scheme_print_cleared) {
1045                 ao_scheme_print_cleared = 1;
1046                 memset(ao_scheme_busy, '\0', sizeof (ao_scheme_busy));
1047         }
1048         offset = pool_offset(addr);
1049         if (busy(ao_scheme_busy, offset))
1050                 return 1;
1051         mark(ao_scheme_busy, offset);
1052         return 0;
1053 }
1054
1055 int
1056 ao_scheme_print_mark_poly(ao_poly p)
1057 {
1058         uint8_t type = ao_scheme_poly_base_type(p);
1059
1060         if (type == AO_SCHEME_INT)
1061                 return 1;
1062         return ao_scheme_print_mark_addr(ao_scheme_ref(p));
1063 }
1064
1065 /* Notes that printing has started */
1066 void
1067 ao_scheme_print_start(void)
1068 {
1069         ao_scheme_printing++;
1070 }
1071
1072 /* Notes that printing has ended */
1073 void
1074 ao_scheme_print_stop(void)
1075 {
1076         ao_scheme_printing--;
1077         if (ao_scheme_printing == 0)
1078                 ao_scheme_print_cleared = 0;
1079 }