292d0f9d6835db38756e9ec055b1117389caf586
[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 #ifdef AO_SCHEME_FEATURE_BIGINT
469         [AO_SCHEME_BIGINT] = &ao_scheme_bigint_type,
470 #endif
471 #ifdef AO_SCHEME_FEATURE_FLOAT
472         [AO_SCHEME_FLOAT] = &ao_scheme_float_type,
473 #endif
474 #ifdef AO_SCHEME_FEATURE_VECTOR
475         [AO_SCHEME_VECTOR] = &ao_scheme_vector_type,
476 #endif
477 };
478
479 static int
480 ao_scheme_mark_ref(const struct ao_scheme_type *type, void **ref)
481 {
482         return ao_scheme_mark(type, *ref);
483 }
484
485 static int
486 ao_scheme_poly_mark_ref(ao_poly *p, uint8_t do_note_cons)
487 {
488         return ao_scheme_poly_mark(*p, do_note_cons);
489 }
490
491 #if DBG_MEM_STATS
492 uint64_t ao_scheme_collects[2];
493 uint64_t ao_scheme_freed[2];
494 uint64_t ao_scheme_loops[2];
495 #endif
496
497 int ao_scheme_last_top;
498
499 int
500 ao_scheme_collect(uint8_t style)
501 {
502         int     i;
503         int     top;
504 #if DBG_MEM_STATS
505         int     loops = 0;
506 #endif
507 #if DBG_MEM
508         struct ao_scheme_record *mark_record = NULL, *move_record = NULL;
509
510         MDBG_MOVE("collect %d\n", ao_scheme_collects[style]);
511 #endif
512         MDBG_DO(ao_scheme_frame_write(ao_scheme_frame_poly(ao_scheme_frame_global)));
513
514         /* The first time through, we're doing a full collect */
515         if (ao_scheme_last_top == 0)
516                 style = AO_SCHEME_COLLECT_FULL;
517
518         /* Clear references to all caches */
519         for (i = 0; i < (int) AO_SCHEME_CACHE; i++)
520                 *ao_scheme_cache[i] = NULL;
521         if (style == AO_SCHEME_COLLECT_FULL) {
522                 chunk_low = top = 0;
523         } else {
524                 chunk_low = top = ao_scheme_last_top;
525         }
526         for (;;) {
527 #if DBG_MEM_STATS
528                 loops++;
529 #endif
530                 MDBG_MOVE("move chunks from %d to %d\n", chunk_low, top);
531                 /* Find the sizes of the first chunk of objects to move */
532                 reset_chunks();
533                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
534 #if DBG_MEM
535
536                 ao_scheme_record_free(mark_record);
537                 mark_record = ao_scheme_record_save();
538                 if (mark_record && move_record)
539                         ao_scheme_record_compare("mark", move_record, mark_record);
540 #endif
541
542                 DUMP_BUSY();
543
544                 /* Find the first moving object */
545                 for (i = 0; i < chunk_last; i++) {
546                         uint16_t        size = ao_scheme_chunk[i].size;
547
548 #if DBG_MEM
549                         if (!size)
550                                 ao_scheme_abort();
551 #endif
552
553                         if (ao_scheme_chunk[i].old_offset > top)
554                                 break;
555
556                         MDBG_MOVE("chunk %d %d not moving\n",
557                                   ao_scheme_chunk[i].old_offset,
558                                   ao_scheme_chunk[i].size);
559 #if DBG_MEM
560                         if (ao_scheme_chunk[i].old_offset != top)
561                                 ao_scheme_abort();
562 #endif
563                         top += size;
564                 }
565
566                 /*
567                  * Limit amount of chunk array used in mapping moves
568                  * to the active region
569                  */
570                 chunk_first = i;
571                 chunk_low = ao_scheme_chunk[i].old_offset;
572
573                 /* Copy all of the objects */
574                 for (; i < chunk_last; i++) {
575                         uint16_t        size = ao_scheme_chunk[i].size;
576
577 #if DBG_MEM
578                         if (!size)
579                                 ao_scheme_abort();
580 #endif
581
582                         MDBG_MOVE("chunk %d %d -> %d\n",
583                                   ao_scheme_chunk[i].old_offset,
584                                   size,
585                                   top);
586                         ao_scheme_chunk[i].new_offset = top;
587
588                         memmove(&ao_scheme_pool[top],
589                                 &ao_scheme_pool[ao_scheme_chunk[i].old_offset],
590                                 size);
591
592                         top += size;
593                 }
594
595                 if (chunk_first < chunk_last) {
596                         /* Relocate all references to the objects */
597                         walk(ao_scheme_move, ao_scheme_poly_move);
598
599 #if DBG_MEM
600                         ao_scheme_record_free(move_record);
601                         move_record = ao_scheme_record_save();
602                         if (mark_record && move_record)
603                                 ao_scheme_record_compare("move", mark_record, move_record);
604 #endif
605                 }
606
607                 /* If we ran into the end of the heap, then
608                  * there's no need to keep walking
609                  */
610                 if (chunk_last != AO_SCHEME_NCHUNK)
611                         break;
612
613                 /* Next loop starts right above this loop */
614                 chunk_low = chunk_high;
615         }
616
617 #if DBG_MEM_STATS
618         /* Collect stats */
619         ++ao_scheme_collects[style];
620         ao_scheme_freed[style] += ao_scheme_top - top;
621         ao_scheme_loops[style] += loops;
622 #endif
623
624         ao_scheme_top = top;
625         if (style == AO_SCHEME_COLLECT_FULL)
626                 ao_scheme_last_top = top;
627
628         MDBG_DO(memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
629                 walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref));
630
631         return AO_SCHEME_POOL - ao_scheme_top;
632 }
633
634 #if DBG_FREE_CONS
635 void
636 ao_scheme_cons_check(struct ao_scheme_cons *cons)
637 {
638         ao_poly cdr;
639         int offset;
640
641         chunk_low = 0;
642         reset_chunks();
643         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
644         while (cons) {
645                 if (!AO_SCHEME_IS_POOL(cons))
646                         break;
647                 offset = pool_offset(cons);
648                 if (busy(ao_scheme_busy, offset)) {
649                         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));
650                         abort();
651                 }
652                 cdr = cons->cdr;
653                 if (!ao_scheme_is_pair(cdr))
654                         break;
655                 cons = ao_scheme_poly_cons(cdr);
656         }
657 }
658 #endif
659
660 /*
661  * Mark interfaces for objects
662  */
663
664
665 /*
666  * Mark a block of memory with an explicit size
667  */
668
669 int
670 ao_scheme_mark_block(void *addr, int size)
671 {
672         int offset;
673         if (!AO_SCHEME_IS_POOL(addr))
674                 return 1;
675
676         offset = pool_offset(addr);
677         MDBG_MOVE("mark memory %d\n", MDBG_OFFSET(addr));
678         if (busy(ao_scheme_busy, offset)) {
679                 MDBG_MOVE("already marked\n");
680                 return 1;
681         }
682         mark(ao_scheme_busy, offset);
683         note_chunk(offset, size);
684         return 0;
685 }
686
687 /*
688  * Note a reference to memory and collect information about a few
689  * object sizes at a time
690  */
691
692 int
693 ao_scheme_mark_memory(const struct ao_scheme_type *type, void *addr)
694 {
695         int offset;
696         if (!AO_SCHEME_IS_POOL(addr))
697                 return 1;
698
699         offset = pool_offset(addr);
700         MDBG_MOVE("mark memory %d\n", MDBG_OFFSET(addr));
701         if (busy(ao_scheme_busy, offset)) {
702                 MDBG_MOVE("already marked\n");
703                 return 1;
704         }
705         mark(ao_scheme_busy, offset);
706         note_chunk(offset, ao_scheme_size(type, addr));
707         return 0;
708 }
709
710 /*
711  * Mark an object and all that it refereces
712  */
713 int
714 ao_scheme_mark(const struct ao_scheme_type *type, void *addr)
715 {
716         int ret;
717         MDBG_MOVE("mark %d\n", MDBG_OFFSET(addr));
718         MDBG_MOVE_IN();
719         ret = ao_scheme_mark_memory(type, addr);
720         if (!ret) {
721                 MDBG_MOVE("mark recurse\n");
722                 type->mark(addr);
723         }
724         MDBG_MOVE_OUT();
725         return ret;
726 }
727
728 /*
729  * Mark an object, unless it is a cons cell and
730  * do_note_cons is set. In that case, just
731  * set a bit in the cons note array; those
732  * will be marked in a separate pass to avoid
733  * deep recursion in the collector
734  */
735 int
736 ao_scheme_poly_mark(ao_poly p, uint8_t do_note_cons)
737 {
738         uint8_t type;
739         void    *addr;
740
741         type = ao_scheme_poly_base_type(p);
742
743         if (type == AO_SCHEME_INT)
744                 return 1;
745
746         addr = ao_scheme_ref(p);
747         if (!AO_SCHEME_IS_POOL(addr))
748                 return 1;
749
750         if (type == AO_SCHEME_CONS && do_note_cons) {
751                 note_cons(pool_offset(addr));
752                 return 1;
753         } else {
754                 if (type == AO_SCHEME_OTHER)
755                         type = ao_scheme_other_type(addr);
756
757                 const struct ao_scheme_type *lisp_type = ao_scheme_types[type];
758 #if DBG_MEM
759                 if (!lisp_type)
760                         ao_scheme_abort();
761 #endif
762
763                 return ao_scheme_mark(lisp_type, addr);
764         }
765 }
766
767 /*
768  * Find the current location of an object
769  * based on the original location. For unmoved
770  * objects, this is simple. For moved objects,
771  * go search for it
772  */
773
774 static uint16_t
775 move_map(uint16_t offset)
776 {
777         int             l;
778
779         if (offset < chunk_low || chunk_high <= offset)
780                 return offset;
781
782         l = find_chunk(offset);
783
784 #if DBG_MEM
785         if (ao_scheme_chunk[l].old_offset != offset)
786                 ao_scheme_abort();
787 #endif
788         return ao_scheme_chunk[l].new_offset;
789 }
790
791 int
792 ao_scheme_move_memory(const struct ao_scheme_type *type, void **ref)
793 {
794         void            *addr = *ref;
795         uint16_t        offset, orig_offset;
796
797         if (!AO_SCHEME_IS_POOL(addr))
798                 return 1;
799
800         (void) type;
801
802         MDBG_MOVE("move memory %d\n", MDBG_OFFSET(addr));
803         orig_offset = pool_offset(addr);
804         offset = move_map(orig_offset);
805         if (offset != orig_offset) {
806                 MDBG_MOVE("update ref %d %d -> %d\n",
807                           AO_SCHEME_IS_POOL(ref) ? MDBG_OFFSET(ref) : -1,
808                           orig_offset, offset);
809                 *ref = ao_scheme_pool + offset;
810         }
811         if (busy(ao_scheme_busy, offset)) {
812                 MDBG_MOVE("already moved\n");
813                 return 1;
814         }
815         mark(ao_scheme_busy, offset);
816         MDBG_DO(ao_scheme_record(type, addr, ao_scheme_size(type, addr)));
817         return 0;
818 }
819
820 int
821 ao_scheme_move(const struct ao_scheme_type *type, void **ref)
822 {
823         int ret;
824         MDBG_MOVE("move object %d\n", MDBG_OFFSET(*ref));
825         MDBG_MOVE_IN();
826         ret = ao_scheme_move_memory(type, ref);
827         if (!ret) {
828                 MDBG_MOVE("move recurse\n");
829                 type->move(*ref);
830         }
831         MDBG_MOVE_OUT();
832         return ret;
833 }
834
835 int
836 ao_scheme_poly_move(ao_poly *ref, uint8_t do_note_cons)
837 {
838         uint8_t         type;
839         ao_poly         p = *ref;
840         int             ret;
841         void            *addr;
842         uint16_t        offset, orig_offset;
843         uint8_t         base_type;
844
845         base_type = type = ao_scheme_poly_base_type(p);
846
847         if (type == AO_SCHEME_INT)
848                 return 1;
849
850         addr = ao_scheme_ref(p);
851         if (!AO_SCHEME_IS_POOL(addr))
852                 return 1;
853
854         orig_offset = pool_offset(addr);
855         offset = move_map(orig_offset);
856
857         if (type == AO_SCHEME_CONS && do_note_cons) {
858                 note_cons(orig_offset);
859                 ret = 1;
860         } else {
861                 if (type == AO_SCHEME_OTHER)
862                         type = ao_scheme_other_type(ao_scheme_pool + offset);
863
864                 const struct ao_scheme_type *lisp_type = ao_scheme_types[type];
865 #if DBG_MEM
866                 if (!lisp_type)
867                         ao_scheme_abort();
868 #endif
869
870                 ret = ao_scheme_move(lisp_type, &addr);
871         }
872
873         /* Re-write the poly value */
874         if (offset != orig_offset) {
875                 ao_poly np = ao_scheme_poly(ao_scheme_pool + offset, base_type);
876                 MDBG_MOVE("poly %d moved %d -> %d\n",
877                           type, orig_offset, offset);
878                 *ref = np;
879         }
880         return ret;
881 }
882
883 #if DBG_MEM
884 void
885 ao_scheme_validate(void)
886 {
887         chunk_low = 0;
888         memset(ao_scheme_chunk, '\0', sizeof (ao_scheme_chunk));
889         walk(ao_scheme_mark_ref, ao_scheme_poly_mark_ref);
890 }
891
892 int dbg_allocs;
893
894 #endif
895
896 void *
897 ao_scheme_alloc(int size)
898 {
899         void    *addr;
900
901         MDBG_DO(++dbg_allocs);
902         MDBG_DO(if (dbg_validate) ao_scheme_validate());
903         size = ao_scheme_size_round(size);
904         if (AO_SCHEME_POOL - ao_scheme_top < size &&
905             ao_scheme_collect(AO_SCHEME_COLLECT_INCREMENTAL) < size &&
906             ao_scheme_collect(AO_SCHEME_COLLECT_FULL) < size)
907         {
908                 ao_scheme_error(AO_SCHEME_OOM, "out of memory");
909                 return NULL;
910         }
911         addr = ao_scheme_pool + ao_scheme_top;
912         ao_scheme_top += size;
913         MDBG_MOVE("alloc %d size %d\n", MDBG_OFFSET(addr), size);
914         return addr;
915 }
916
917 void
918 ao_scheme_cons_stash(int id, struct ao_scheme_cons *cons)
919 {
920         assert(save_cons[id] == 0);
921         save_cons[id] = cons;
922 }
923
924 struct ao_scheme_cons *
925 ao_scheme_cons_fetch(int id)
926 {
927         struct ao_scheme_cons *cons = save_cons[id];
928         save_cons[id] = NULL;
929         return cons;
930 }
931
932 void
933 ao_scheme_poly_stash(int id, ao_poly poly)
934 {
935         assert(save_poly[id] == AO_SCHEME_NIL);
936         save_poly[id] = poly;
937 }
938
939 ao_poly
940 ao_scheme_poly_fetch(int id)
941 {
942         ao_poly poly = save_poly[id];
943         save_poly[id] = AO_SCHEME_NIL;
944         return poly;
945 }
946
947 void
948 ao_scheme_string_stash(int id, char *string)
949 {
950         assert(save_string[id] == NULL);
951         save_string[id] = string;
952 }
953
954 char *
955 ao_scheme_string_fetch(int id)
956 {
957         char *string = save_string[id];
958         save_string[id] = NULL;
959         return string;
960 }
961
962 void
963 ao_scheme_frame_stash(int id, struct ao_scheme_frame *frame)
964 {
965         assert(save_frame[id] == NULL);
966         save_frame[id] = frame;
967 }
968
969 struct ao_scheme_frame *
970 ao_scheme_frame_fetch(int id)
971 {
972         struct ao_scheme_frame *frame = save_frame[id];
973         save_frame[id] = NULL;
974         return frame;
975 }