Debian Codegraph @

utils/xml2pmx/xml2pmx-src/gc.c

raw
1 /*
2 * gc.c
3 *
4 * This file is part of the Oxford Oberon-2 compiler
5 * Copyright (c) 2006--2016 J. M. Spivey
6 * All rights reserved
7 *
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright notice,
12 * this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright notice,
14 * this list of conditions and the following disclaimer in the documentation
15 * and/or other materials provided with the distribution.
16 * 3. The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
24 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
25 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
26 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
27 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
28 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31 #include "obx.h"
32 #include <string.h>
33 #include <stdio.h>
34
35 /* Define MULTIBLOCKS to allow splitting of multi-page blocks */
36 #undef MULTIBLOCKS
37
38 static mybool debug[256]; /* Debugging flags */
39 /* a - print addresses;
40 g - print [GC...];
41 b - print chunks allocated;
42 c - print every allocation;
43 d - general debugging;
44 l - trace low-level allocator;
45 m - print maps;
46 s - scribble on freed storage (obsolete);
47 z - GC on each allocation */
48
49 /* Assertions are enabled in all programs if DEBUG is defined */
50 #ifdef DEBUG
51 static const char *assert_fmt = "*assertion %s failed on line %d of file %s";
52 #define ASSERT(p) \
53 if (! (p)) panic(assert_fmt, #p, __LINE__, __FILE__);
54 #else
55 #define ASSERT(p)
56 #endif
57
58 /* Debugging messages are present only in 'obtrace'. */
59 #ifdef TRACE
60 #define DEBUG_PRINT(flag, args) \
61 if (debug[flag]) { printf args; fflush(stdout); }
62 #else
63 #define DEBUG_PRINT(flags, args)
64 #endif
65
66 /* [GC] message is always present. */
67 #define GC_TRACE(s) if (debug['g']) { printf("%s", s); fflush(stdout); }
68
69 /* There are three storage allocators: the lower one that deals in
70 whole pages, the upper one that gets pages from the lower one and
71 splits them into smaller objects, and a separate scratch allocator
72 that is used for internal data structures of the heap, and for the
73 program's symbol table. Objects allocated in the scratch space are
74 not garbage collected, but they don't need to follow the
75 collector's layout rules. All this can coexist with malloc(),
76 which may well be used by stdio to allocate buffers. */
77
78 /* Terminology: a PAGE has a fixed size, determined by configure. A
79 BLOCK is a contiguous area of one or more pages. An OBJECT is a
80 memory area allocated for a client. For the allocator to function
81 correctly, the function get_memory must be able to allocate memory
82 in chunks of size CHUNK_SIZE aligned on a PAGESIZE boundary: this
83 more-or-less implies that CHUNK_SIZE is a multiple of the VM page
84 size, and the VM page size is a multiple of PAGESIZE. Configure
85 satisfies this by making PAGESIZE equal to the size of a VM page.
86
87 For each small size of object, there is a POOL of blocks that are
88 split up by the upper-level allocator into objects of that size.
89 Large objects occupy an entire block of one or more pages.
90 We use compaction in each pool of small objects; large objects are
91 not compacted, and never move. */
92
93 #define BYTES_PER_WORD 4
94 #define PAGE_WORDS (PAGESIZE / BYTES_PER_WORD)
95
96 #define MB 1024*1024
97 #define INIT_SIZE (2*MB) /* Initial heap size */
98 #define CHUNK_SIZE (1*MB) /* Amount that heap grows */
99
100 #define round_down(x, n) ((x)/(n)*(n))
101 #define round_up(x, n) round_down((x)+(n)-1, n)
102
103 /* Most of the manipulations here are done in terms of words, and to
104 save brain cells, we assume a word has 32 bits; there are lots of
105 constants that need changing if that is not true. */
106
107 #ifndef SEGMEM
108
109 #ifdef HAVE_MMAP
110 #include <fcntl.h>
111 #include <sys/mman.h>
112
113 #ifdef MACOS
114 #define MAP_ANONYMOUS MAP_ANON
115 #define HINT (void *) 0x10000000L
116 #define MMAP_FLAGS MAP_PRIVATE
117 #else
118 #define HINT NULL
119 #ifdef M64X32
120 #define MMAP_FLAGS MAP_PRIVATE|MAP_32BIT
121 #else
122 #define MMAP_FLAGS MAP_PRIVATE
123 #endif
124 #endif
125
126 static void *grab_chunk(unsigned size) {
127 void *p;
128 static void *last_addr = HINT;
129
130 #ifdef MAP_ANONYMOUS
131 p = mmap(last_addr, size, PROT_READ|PROT_WRITE,
132 MMAP_FLAGS|MAP_ANONYMOUS, -1, 0);
133 #else
134 static int zero_fd = -1;
135
136 if (zero_fd < 0) {
137 zero_fd = open("/dev/zero", O_RDONLY);
138 if (zero_fd < 0) panic("couldn't open /dev/zero");
139 }
140
141 p = mmap(last_addr, size, PROT_READ|PROT_WRITE,
142 MMAP_FLAGS, zero_fd, 0);
143 #endif
144
145 if (p == MAP_FAILED) return NULL;
146 #ifdef M64X32
147 if ((((unsigned long) p) & ~0x7fffffff) != 0)
148 panic("inaccessible memory allocated at %p", p);
149 #endif
150 last_addr = p + size;
151 return p;
152 }
153 #endif
154
155 #ifdef WINDOWS
156 #include <windows.h>
157
158 #ifdef M64X32
159 /* With thanks to the LuaJIT people */
160 typedef long (*ntavm_ptr)(void *, void **, unsigned long, size_t *,
161 unsigned long, unsigned long);
162
163 #define NTAVM_ZEROBITS 1
164
165 static void *grab_chunk(unsigned size0) {
166 static ntavm_ptr ntavm = NULL;
167
168 if (ntavm == NULL) {
169 void *module = GetModuleHandleA("ntdll.dll");
170 ntavm = (ntavm_ptr)
171 GetProcAddress(module, "NtAllocateVirtualMemory");
172 }
173
174 void *p = NULL;
175 size_t size = size0;
176 ntavm(INVALID_HANDLE_VALUE, &p, NTAVM_ZEROBITS, &size,
177 MEM_COMMIT|MEM_RESERVE, PAGE_READWRITE);
178 return p;
179 }
180
181 #else
182
183 static void *grab_chunk(unsigned size) {
184 return VirtualAlloc(NULL, size, MEM_COMMIT|MEM_RESERVE,
185 PAGE_READWRITE);
186 }
187
188 #endif
189 #endif
190
191 /* get_memory -- grab one or more pages from the operating system */
192 static void *get_memory(unsigned size) {
193 unsigned alloc_size = round_up(size, PAGESIZE);
194 void *p;
195
196 /* This happens e.g. if custom translation makes the code size zero */
197 if (alloc_size == 0) return NULL;
198
199 DEBUG_PRINT('b', ("Need %u; requesting chunk of size %u\n",
200 size, alloc_size));
201 p = grab_chunk(alloc_size);
202 if (p == NULL) panic("out of memory");
203 DEBUG_PRINT('b', ("Allocated chunk at %p\n", p));
204 ASSERT((ptrtype) p % PAGESIZE == 0);
205 return p;
206 }
207
208 /* get_chunk -- grab memory addressible by the garbage collector */
209 #define get_chunk(size) pun_memory(get_memory(size))
210
211
212 /* SCRATCH ALLOCATOR */
213
214 /* Scratch storage is managed separately from the heap. We allocate
215 whole pages (e.g. for the page table) on page boundaries. Scratch
216 blocks must be aligned on an 8-byte boundary for architectures that
217 don't support unaligned loads and stores of uint64_t, a type that is
218 used for profiling counts. */
219
220 #define SCRATCH_ALIGN 8
221
222 /* In order to manage a 4MB heap, we need about 1024 headers and 2 or
223 3 page indexes, making about 8 pages of scratch storage. We also
224 need space for the program's symbol table. Grabbing scratch space
225 16 pages at a time seems a fair compromise. */
226
227 #define SCRATCH_CHUNK (16 * PAGESIZE)
228
229 /* The scratch allocator keeps hold of just one piece of free memory,
230 and wastefully discards it if it is too small to satisfy the next
231 memory request. */
232
233 static void *scratch_free = NULL;
234 static void *scratch_limit = NULL;
235
236 void *scratch_alloc(unsigned size) {
237 unsigned alloc_size = round_up(size, SCRATCH_ALIGN);
238 void *p;
239
240 if (scratch_free == NULL || alloc_size > scratch_limit - scratch_free) {
241 if (alloc_size >= SCRATCH_CHUNK/2
242 || (scratch_free != NULL
243 && scratch_limit - scratch_free >= 4*PAGESIZE))
244 /* Avoid discarding a largish piece */
245 return get_memory(alloc_size);
246
247 scratch_free = get_memory(SCRATCH_CHUNK);
248 scratch_limit = scratch_free + SCRATCH_CHUNK;
249 }
250
251 if (alloc_size % PAGESIZE == 0) {
252 scratch_limit -= alloc_size;
253 p = scratch_limit;
254 } else {
255 p = scratch_free;
256 scratch_free += alloc_size;
257 }
258
259 ASSERT((ptrtype) p % SCRATCH_ALIGN == 0);
260
261 return p;
262 }
263
264 #else /* SEGMEM */
265
266 /* To permit the use of malloc() as the only way of getting storage,
267 we can simulate segmented memory in software. The key to this is
268 the inlined routine physmap defined in obx.h, which convert a
269 32-bit 'address' into a geniuine native pointer. It is implicitly
270 used in the macros ptrcast, valptr and pointer by which the
271 interpreter interprets one of these addresses as a pointer.
272
273 A 32-bit address splits as 12 + 20 bits, with a 12-bit segment
274 number, and index into segmap, and a 20-bit offset within the
275 segment. The segmap array gives the base address (64 bits) for a
276 piece of storage obtained from malloc. These segments do not have
277 to be contiguous with each other. We can deal with pieces of
278 memory bigger than 1MB by allocating several slots in segmap to
279 them, and exploit the fact that incrementing virtual addresses will
280 carry from the offset into the segment bits.
281
282 The garbage collector operates entirely within the 'virtual' address
283 space, and completely independently splits the virtual addresses as
284 10 + 10 + 12 bits to access the 'page table'. Adjust it if you like! */
285
286 #include <stdlib.h>
287
288 /* scratch_alloc -- allocate storage without making it addressible */
289 void *scratch_alloc(unsigned size) {
290 void *p = malloc(size);
291 if (p == NULL) panic("malloc failed");
292 memset(p, 0, size);
293 return p;
294 }
295
296 void *segmap[NSEGMENTS]; /* Base of each segment as a (maybe 64-bit) pointer */
297 static int nsegs = 1; /* Segment 0 used for NULL */
298
299 /* map_segment -- allocate segment registers */
300 word map_segment(void *p, unsigned len) {
301 word base = nsegs * SEGMENT;
302 char *q = p;
303
304 while (nsegs * SEGMENT < base + len) {
305 segmap[nsegs++] = q;
306 q += SEGMENT;
307 }
308
309 return base;
310 }
311
312 /* get_chunk -- allocate a chunk of storage and make it addressible */
313 word get_chunk(unsigned size) {
314 void *p = scratch_alloc(size);
315 return map_segment(p, size);
316 }
317
318 static word alloc_ptr = 0, alloc_limit;
319
320 /* virtual_alloc -- allocate unreclaimable storage that is addressible */
321 word virtual_alloc(unsigned size) {
322 word p;
323
324 ASSERT(size < SEGMENT);
325
326 if (alloc_ptr == 0 || alloc_ptr + size > alloc_limit) {
327 alloc_ptr = get_chunk(SEGMENT);
328 alloc_limit = alloc_ptr + SEGMENT;
329 }
330
331 p = alloc_ptr;
332 alloc_ptr += size;
333 return p;
334 }
335
336 #endif
337
338
339 /* BLOCK HEADERS */
340
341 /* Each heap block has a header, separate from the block itself, that
342 is allocated in scratch space. A heap block contains only one size
343 of object, given by the h_objsize field; this makes it possible to
344 find the start of an object given a pointer to its interior. Also,
345 heap blocks are given a timestamp that allows us to identify during
346 GC which semispace they belong to.
347
348 We may as well use 32-bit pointers for headers and allocate the
349 space for them in addressible scratch storage. This works well
350 except with SEGMEM, where it's going to be faster to use actual
351 pointers. */
352
353 #ifndef SEGMEM
354 typedef word hdrptr;
355 #define hdr(h) ptrcast(header, h)
356 #define header_alloc() virtual_alloc(sizeof(header))
357 #else
358 typedef struct _header *hdrptr;
359 #define hdr(h) h
360 #define header_alloc() scratch_alloc(sizeof(header))
361 #endif
362
363 #define charptr(a) ptrcast(char, a)
364
365 typedef struct _header {
366 word h_memory; /* The block itself */
367 unsigned h_size; /* Size of block (bytes) */
368 unsigned h_objsize; /* Size of each object (bytes), or 0 if free */
369 unsigned h_epoch; /* Timestamp to identify semispace */
370 hdrptr h_next, h_prev; /* Adjacent blocks in some list */
371 } header;
372
373 /* Headers can become free when two blocks merge into one, so we keep
374 a free list for them and allocate from it when possible */
375
376 static hdrptr hdr_free = 0;
377
378 /* alloc_header -- create a block header */
379 static hdrptr alloc_header(void) {
380 hdrptr h;
381
382 if (hdr_free == 0)
383 h = header_alloc();
384 else {
385 h = hdr_free;
386 hdr_free = hdr(h)->h_next;
387 }
388
389 hdr(h)->h_memory = 0;
390 hdr(h)->h_size = 0;
391 hdr(h)->h_objsize = 0;
392 hdr(h)->h_epoch = 0;
393 hdr(h)->h_next = hdr(h)->h_prev = 0;
394 return h;
395 }
396
397 #define free_header(h) hdr(h)->h_next = hdr_free; hdr_free = h;
398
399 /* Each block is linked into one of several doubly-linked lists: there
400 are lists of free blocks of various sizes, lists of blocks that are
401 in use for allocating various small sizes of object, and a list of
402 blocks in use for big objects. All these lists are given a
403 dummy node to simplify pointer manipulations. */
404
405 static hdrptr new_list(void) {
406 hdrptr h = alloc_header();
407 hdr(h)->h_next = hdr(h)->h_prev = h;
408 return h;
409 }
410
411 #define empty(list) (hdr(list)->h_next == (list))
412
413 #define insert(h, h2) \
414 hdr(h2)->h_next = h; hdr(h2)->h_prev = hdr(h)->h_prev; \
415 hdr(hdr(h)->h_prev)->h_next = h2; hdr(h)->h_prev = h2;
416
417 #define unlink(h) \
418 hdr(hdr(h)->h_prev)->h_next = hdr(h)->h_next; \
419 hdr(hdr(h)->h_next)->h_prev = hdr(h)->h_prev
420
421 /* Say "for (headers(h, list))" to traverse a cyclic list of headers. */
422 #define headers(h, list) \
423 h = hdr(list)->h_next; h != list; h = hdr(h)->h_next
424
425
426 /* PAGE TABLE */
427
428 /* We must deal with interior pointers, so we need to find the start
429 of any object, given an address anywhere within it. (Unlike C, we
430 don't need to deal with addresses that are just off the end.) To
431 this end, we keep a kind of page table covering the whole address
432 space, organising it as a two-level tree (an idea from the Boehm
433 collector). For large blocks we make several entries in the table
434 point to the same block header. All storage, both allocated and
435 free, that belongs to the heap is mapped in the page table. The
436 page table also makes it easy to find the neighbours of any
437 block. */
438
439 /* To use the two-level table, we need to split an address into three
440 parts: the top part (10 bits for PAGESIZE = 4096), which selects
441 an index; the bottom part (10 bits), which selects a page under
442 that index, and the offset (12 bits) within the page. In general,
443 we arrange that a page index occupies one page itself, and
444 calculate the size of the root table to cover the address space. */
445
446 #define PAGESIZE 4096
447 #define LOG_PAGESIZE 12
448
449 #define BOT_BITS (LOG_PAGESIZE - 2)
450 #define BOT_SIZE (1 << BOT_BITS)
451 #define TOP_BITS (8*BYTES_PER_WORD - BOT_BITS - LOG_PAGESIZE)
452 #define TOP_SIZE (1 << TOP_BITS)
453
454 #define mask(x, n) ((x) & ((1 << (n)) - 1))
455
456 #define top_part(p) ((p) >> (BOT_BITS + LOG_PAGESIZE))
457 #define bot_part(p) mask((p) >> LOG_PAGESIZE, BOT_BITS)
458
459 /* Here's the layout of the page table; unused elements of the
460 top-level table are all initialized to empty_index, a page full
461 of NULLs. */
462
463 typedef hdrptr page_index[BOT_SIZE];
464
465 static word page_table[TOP_SIZE];
466 static word empty_index;
467
468 #define get_header(p) \
469 (*ptrcast(page_index, page_table[top_part(p)]))[bot_part(p)]
470
471 /* To assist in merging free blocks, we can find the two blocks that
472 surround a given block */
473 #define left_neighbour(h) get_header(hdr(h)->h_memory - 1)
474 #define right_neighbour(h) get_header(hdr(h)->h_memory + hdr(h)->h_size)
475
476 /* page_setup -- make page table entries point to a given header */
477 static void page_setup(word base, unsigned size, hdrptr h) {
478 word p;
479
480 ASSERT(size % PAGESIZE == 0);
481 for (p = base; p < base + size; p += PAGESIZE) {
482 /* Make sure lower index exists */
483 if (page_table[top_part(p)] == empty_index)
484 page_table[top_part(p)] = virtual_alloc(sizeof(page_index));
485
486 get_header(p) = h;
487 }
488 }
489
490 static void init_pagetable(void) {
491 int i;
492
493 empty_index = virtual_alloc(sizeof(page_index));
494 for (i = 0; i < TOP_SIZE; i++) page_table[i] = empty_index;
495 }
496
497
498 /* LOWER-LEVEL ALLOCATOR */
499
500 /* We maintain BIG_BLOCK free lists for free blocks of size 1, 2,
501 ... BIG_BLOCK-1 pages, and a last free list for those with size >=
502 BIG_BLOCK pages. Free blocks are merged with their neighbours, and
503 all storage on the free lists is zeroed. (free_list[0] is never
504 used.)
505
506 The purpose here is to reduce fragmentation by using small blocks
507 when possible. Since a very common case is allocating a single
508 page when only a few big blocks are free, we should keep BIG_BLOCK
509 fairly small, however. */
510
511 #define BIG_BLOCK 8
512
513 static hdrptr free_list[BIG_BLOCK+1];
514 static unsigned gencount = 1; /* Timestamp */
515
516 /* make_free -- add a block to the appropriate free list */
517 static void make_free(hdrptr h) {
518 int index = hdr(h)->h_size/PAGESIZE;
519
520 if (index > BIG_BLOCK) index = BIG_BLOCK;
521
522 DEBUG_PRINT('l', ("Make free %#x %#x (free list %d)\n",
523 hdr(h)->h_memory, hdr(h)->h_size, index));
524
525 hdr(h)->h_objsize = 0;
526 insert(free_list[index], h);
527 }
528
529 #ifdef SEGMEM
530 /* contiguous -- test if blocks are physically contiguous */
531 #define contiguous(h1, h2) \
532 charptr(hdr(h1)->h_memory) + hdr(h1)->h_size \
533 == charptr(hdr(h2)->h_memory)
534 #endif
535
536
537 /* free_block -- free a block, merging it with its neighbours */
538 static hdrptr free_block(hdrptr h, mybool mapped) {
539 /* Mapped is true if this memory is being recycled: it's already
540 in the page table, but we'll need to zero it. */
541
542 hdrptr prev = left_neighbour(h), next = right_neighbour(h);
543
544 /* Base and size of area where page table needs updating */
545 word update_mem = hdr(h)->h_memory;
546 unsigned update_size = (mapped ? 0 : hdr(h)->h_size);
547
548 #ifdef TRACE
549 if (debug['l']) {
550 printf("Freeing block at %#x, size %#x\n",
551 hdr(h)->h_memory, hdr(h)->h_size);
552
553 if (prev == 0)
554 printf("prev=null, ");
555 else
556 printf("prev=%#x, ", hdr(prev)->h_memory);
557
558 if (next == 0)
559 printf("next=null\n");
560 else
561 printf("next=%#x\n", hdr(next)->h_memory);
562 }
563 #endif
564
565 if (mapped) memset(charptr(hdr(h)->h_memory), 0, hdr(h)->h_size);
566
567 if (prev != 0 && hdr(prev)->h_objsize == 0
568 #ifdef SEGMEM
569 && contiguous(prev, h)
570 #endif
571 ) {
572 DEBUG_PRINT('l', ("Merging with prev\n"));
573 unlink(prev);
574 hdr(prev)->h_size += hdr(h)->h_size;
575 update_mem = hdr(h)->h_memory;
576 update_size = hdr(h)->h_size;
577 free_header(h);
578 h = prev;
579 }
580
581 if (next != 0 && hdr(next)->h_objsize == 0
582 #ifdef SEGMEM
583 && contiguous(h, next)
584 #endif
585 ) {
586 DEBUG_PRINT('l', ("Merging with next\n"));
587 unlink(next);
588 hdr(next)->h_memory = hdr(h)->h_memory;
589 hdr(next)->h_size += hdr(h)->h_size;
590 update_mem = hdr(h)->h_memory;
591 update_size = hdr(h)->h_size;
592 free_header(h);
593 h = next;
594 }
595
596 if (update_size > 0)
597 page_setup(update_mem, update_size, h);
598 make_free(h);
599
600 /* Return the merged block */
601 return h;
602 }
603
604 /* find_block -- find a free block of specified size */
605 static hdrptr find_block(unsigned size, unsigned objsize) {
606 hdrptr h = 0, h2;
607 int i = min(size/PAGESIZE, BIG_BLOCK);
608
609 ASSERT(size % PAGESIZE == 0);
610
611 do {
612 for (headers(h2, free_list[i])) {
613 /* This always succeeds for small blocks, and gives
614 first-fit allocation for big blocks. */
615 if (size <= hdr(h2)->h_size) {
616 h = h2; break;
617 }
618 }
619 i++;
620 } while (h == 0 && i <= BIG_BLOCK);
621
622 if (h == 0) {
623 /* No suitable block was found. Get a big chunk. */
624 unsigned chunk = max(size, CHUNK_SIZE);
625 GC_TRACE("[ex]");
626 ASSERT(chunk % PAGESIZE == 0);
627 h = alloc_header();
628 hdr(h)->h_memory = get_chunk(chunk);
629 hdr(h)->h_size = chunk;
630 /* Add to the free list for merging and page table setup */
631 h = free_block(h, FALSE);
632 }
633
634 ASSERT(hdr(h)->h_memory != 0 && hdr(h)->h_size >= size);
635 unlink(h);
636
637 if (size < hdr(h)->h_size) {
638 /* Split the block, and return the waste to the free
639 list. It's best to use header h for the waste: that
640 way, we don't have to reset lots of page table
641 entries when we chip a small piece off a big block. */
642 hdrptr h2 = alloc_header();
643 hdr(h2)->h_memory = hdr(h)->h_memory;
644 hdr(h2)->h_size = size;
645 page_setup(hdr(h2)->h_memory, size, h2);
646
647 hdr(h)->h_memory += size;
648 hdr(h)->h_size -= size;
649 make_free(h);
650
651 h = h2;
652 }
653
654 hdr(h)->h_objsize = objsize;
655 hdr(h)->h_epoch = gencount;
656 return h;
657 }
658
659
660 /* OBJECT SIZES */
661
662 /* Requests are always rounded up to a whole number of words. Those of
663 size <= MAX_SMALL_BYTES are further rounded up to one of a small
664 number of sizes from the array size_bytes, and bigger requests are
665 rounded up to a number of whole pages. The size_map table gives
666 the appropriate index into size_bytes for each small size in words.
667 Thus size_bytes[size_map[s]-1] < 4*s <= size_bytes[size_map[s]] for
668 each index s up to half the page size in words. The sizes are
669 almost all multiples of 16 bytes to help with cache alignment.
670 Small objects of size size_bytes[i] are allocated by splitting up a
671 block of size size_block[i]. */
672
673 #define N_SIZES (2*LOG_PAGESIZE)
674
675 #ifdef MULTIBLOCKS
676 #define MAX_SMALL_WORDS (4*(PAGE_WORDS/3))
677 #else
678 #define MAX_SMALL_WORDS (PAGE_WORDS/2)
679 #endif
680 #define MAX_SMALL_BYTES (BYTES_PER_WORD * MAX_SMALL_WORDS)
681
682 static unsigned n_sizes;
683
684 static unsigned size_bytes[N_SIZES];
685 #define pool_size(i) size_bytes[i]
686
687 #ifdef MULTIBLOCKS
688 static unsigned size_block[N_SIZES];
689 #define pool_block(i) size_block[i]
690 #else
691 #define pool_block(i) PAGESIZE
692 #endif
693
694 #define pool_count(i) (pool_block(i) / pool_size(i))
695
696 static unsigned char size_map[MAX_SMALL_WORDS+1];
697 #define pool_map(size) size_map[(size)/BYTES_PER_WORD]
698
699 #define GRANULE 16 /* Should be about the size of a cache line */
700
701 /* new_size -- adjust and register an object size */
702 static void new_size(int size, int block) {
703 ASSERT(n_sizes < N_SIZES);
704
705 /* Round up while same number will fit in a block */
706 size = block / (block / size);
707
708 /* Round down to a multiple of GRANULE */
709 if (size >= GRANULE) size = GRANULE * (size / GRANULE);
710
711 size_bytes[n_sizes] = size;
712 #ifdef MULTIBLOCKS
713 size_block[n_sizes] = block;
714 #endif
715 n_sizes++;
716 }
717
718 static void init_sizes(void) {
719 /* Establish size_bytes and size_map. Single-word objects
720 (containing only a descriptor) are not allowed, because we
721 need to assume that a pointer to the object itself, i.e. to
722 the word after the descriptor, is still inside the object. The
723 sequence is 2, 4, 8, 12, 16, 24, 32 ... words, rounded up to
724 the biggest multiple of GRANULE that allows the same number
725 of objects in a page. */
726
727 int i;
728 unsigned k;
729
730 n_sizes = 0;
731 new_size(8, PAGESIZE);
732 new_size(16, PAGESIZE);
733 k = 16;
734 while (k < PAGESIZE/8) {
735 new_size(2*k, PAGESIZE);
736 new_size(3*k, PAGESIZE);
737 k *= 2;
738 }
739
740 /* Then ... 1/4, 1/3, 1/2, 2/3, 1, 4/3 pages. The larger sizes
741 are enabled only if MULTIBLOCKS is defined; the extra cost in
742 compaction overhead may not be worth the reduction in internal
743 fragmentation that is achieved. */
744 new_size(PAGESIZE/4, PAGESIZE);
745 new_size(PAGESIZE/3, PAGESIZE);
746 new_size(PAGESIZE/2, PAGESIZE);
747 #ifdef MULTIBLOCKS
748 new_size(2*PAGESIZE/3, 2*PAGESIZE);
749 new_size(PAGESIZE, PAGESIZE);
750 new_size(4*PAGESIZE/3, 4*PAGESIZE);
751 #endif
752
753 ASSERT(size_bytes[n_sizes-1] == MAX_SMALL_BYTES);
754
755 k = 0;
756 for (i = 0; i < n_sizes; i++)
757 while (k * BYTES_PER_WORD <= size_bytes[i]) size_map[k++] = i;
758
759 ASSERT(size_map[MAX_SMALL_WORDS] == n_sizes-1);
760 }
761
762
763 /* UPPER-LEVEL ALLOCATOR */
764
765 /* For each small size, there is a doubly-linked pool of pages
766 containing objects of that size, and a separate pool for large
767 objects. A second set of pools is used during garbage collection.
768 The blocks in a pools are not necessarily sorted by address. */
769 static hdrptr block_pool[N_SIZES+1], old_pool[N_SIZES+1];
770
771 /* The free storage in each pool is in the upper part of one of the
772 last block of the pool. */
773 static word free_ptr[N_SIZES+1]; /* First free object */
774 static int free_count[N_SIZES+1]; /* Number of free objects */
775
776 /* To allocate an object of a given size, we first round up the size,
777 then look at the free storage in the pool for that size. If there
778 is none, then we try to add a free block to the pool. But if this
779 semispace is full, then we must either run the collector or expand
780 the semispace (or maybe both). We expand the semispace immediately
781 if the amount of storage allocated since the last collection is
782 less than THRESHOLD times the heap size.
783
784 Running the collector may yield free space in the relevant pool,
785 and may yield one or more free blocks; so afterwards we try the
786 whole allocation process again. */
787
788 #define THRESHOLD 0.5
789
790 mybool gcflag = TRUE;
791 static unsigned alloc_since_gc = 0;
792 static unsigned pool_total = 0; /* Total size of all pools */
793 static unsigned heap_size = 0; /* Size of one semispace */
794
795 /* scavenge -- run the collector or expand the heap */
796 void scavenge(value *sp, unsigned size) {
797 if (gcflag && heap_size > 0
798 && alloc_since_gc > THRESHOLD * heap_size)
799 gc_collect(sp);
800 else
801 heap_size += round_up(size, PAGESIZE);
802 }
803
804 static void add_block(int index) {
805 hdrptr h = find_block(pool_block(index), pool_size(index));
806 insert(block_pool[index], h);
807 pool_total += pool_block(index);
808 free_ptr[index] = hdr(h)->h_memory;
809 free_count[index] = pool_count(index);
810 }
811
812 word gc_alloc(unsigned size, value *sp) {
813 unsigned alloc_size;
814 word p = 0;
815 hdrptr h;
816
817 if (debug['z']) gc_collect(sp);
818
819 size = round_up(size, BYTES_PER_WORD);
820
821 if (size <= MAX_SMALL_BYTES) {
822 /* Try to allocate from the appropriate pool */
823 unsigned index = pool_map(size);
824 alloc_size = pool_size(index);
825 ASSERT(alloc_size >= size);
826
827 if (free_count[index] == 0) {
828 while (pool_total + pool_block(index) > heap_size
829 && free_count[index] == 0)
830 scavenge(sp, pool_block(index));
831
832 if (free_count[index] == 0)
833 add_block(index);
834 }
835
836 p = free_ptr[index];
837 free_ptr[index] += alloc_size;
838 free_count[index]--;
839 } else {
840 /* Allocate whole pages */
841 alloc_size = round_up(size, PAGESIZE);
842
843 while (pool_total + alloc_size > heap_size)
844 scavenge(sp, alloc_size);
845
846 h = find_block(alloc_size, alloc_size);
847 insert(block_pool[n_sizes], h);
848 pool_total += alloc_size;
849 p = hdr(h)->h_memory;
850 }
851
852 alloc_since_gc += alloc_size;
853 DEBUG_PRINT('c', ("[Alloc %d %#x]", size, p));
854 return p;
855 }
856
857
858 /* GARBAGE COLLECTOR */
859
860 /* Now it's time to tackle the toughest part: the garbage collector
861 itself. We use a stop-and-copy method, refined to deal with the
862 allocation of different sizes of objects from different blocks.
863 Garbage collection works by copying needed objects out of the old
864 heap space into a new space. When an object is copied, its
865 descriptor gets overwritten with the BROKEN_HEART token, and the
866 second word gives the location of the copy. Big objects that
867 occupy a block to themselves are not copied but just linked into
868 the new pool. */
869
870 #define BROKEN_HEART 0xbabeface
871
872 #define get_word(p, i) ptrcast(word, p)[i]
873 #define desc(p) ptrcast(word, get_word(p, 0))
874
875 /* redirect -- translate pointer into new space */
876 static void redirect(word *p) {
877 word q, r, s;
878 hdrptr h;
879 int index;
880 unsigned objsize;
881
882 q = *p; /* q is the old pointer value */
883 if (q == 0) return;
884 h = get_header(q);
885 if (h == 0) return; /* Not in the managed heap */
886 objsize = hdr(h)->h_objsize;
887 ASSERT(objsize > 0);
888
889 if (objsize <= MAX_SMALL_BYTES) {
890 /* A small object */
891 index = pool_map(objsize);
892 ASSERT(pool_size(index) == objsize);
893 r = hdr(h)->h_memory + round_down(q - hdr(h)->h_memory, objsize);
894 /* r is the start of the object containing q */
895
896 if (get_word(r, 0) == BROKEN_HEART)
897 s = get_word(r, 1);
898 else {
899 /* Evacuate object at r */
900 if (free_count[index] == 0) add_block(index);
901 s = free_ptr[index];
902 memcpy(charptr(s), charptr(r), pool_size(index));
903 free_ptr[index] += pool_size(index);
904 free_count[index]--;
905 get_word(r, 0) = BROKEN_HEART;
906 get_word(r, 1) = s;
907 }
908 /* s is the new location for the object r */
909 *p = s + (q - r);
910 } else if (hdr(h)->h_epoch < gencount) {
911 /* A big block, not already moved to the new semispace */
912 unlink(h);
913 insert(block_pool[n_sizes], h);
914 hdr(h)->h_epoch = gencount;
915 }
916 }
917
918 /* map_next -- skip over a map item */
919 static word map_next(word p) {
920 if (get_word(p, 0) % 4 != 2)
921 return p+4; /* A pointer offset or bitmap */
922
923 switch (get_word(p, 0) >> 2) {
924 case GC_BASE >> 2:
925 case GC_MAP >> 2:
926 case GC_POINTER >> 2:
927 return p+8;
928
929 case GC_REPEAT >> 2:
930 case GC_FLEX >> 2:
931 p += 16;
932 if (get_word(p, 0) % 2 == 0) {
933 while (get_word(p, 0) != GC_END) p = map_next(p);
934 }
935 return p+4;
936
937 case GC_BLOCK >> 2:
938 return p+12;
939
940 default:
941 panic("*bad map code %d", get_word(p, 0));
942 return 0;
943 }
944 }
945
946 /* redir_map -- interpret a pointer map, redirecting each pointer */
947 static void redir_map(unsigned map, word origin, int bmshift) {
948 int count, stride, op, ndim, i;
949 word base, p;
950
951 if (map == 0) return;
952
953 if ((map & 0x1) != 0) {
954 /* A bitmap */
955 int i = -bmshift;
956 map >>= 1;
957
958 #define mrk(j) redirect((word *) &get_word(origin, i+j))
959
960 while (map != 0) {
961 switch (map & 15) {
962 case 15: mrk(0);
963 case 14: mrk(1);
964 case 12: mrk(3); mrk(2); break;
965 case 13: mrk(2);
966 case 9: mrk(3); mrk(0); break;
967 case 11: mrk(0);
968 case 10: mrk(1);
969 case 8: mrk(3); break;
970 case 7: mrk(1);
971 case 5: mrk(0);
972 case 4: mrk(2); break;
973 case 6: mrk(2);
974 case 2: mrk(1); break;
975 case 3: mrk(1);
976 case 1: mrk(0);
977 case 0: break;
978 }
979
980 i += 4; map >>= 4;
981 }
982
983 return;
984 }
985
986 for (p = map;;) {
987 op = get_word(p, 0);
988
989 switch (op & 0x3) {
990 case 0:
991 /* A pointer offset */
992 redirect(ptrcast(word, origin + op));
993 p += 4; break;
994
995
996 case 1:
997 case 3:
998 /* A bitmap */
999 redir_map(op, origin, 0);
1000 p += 4; break;
1001
1002 default:
1003 switch (op >> 2) {
1004 case GC_BASE >> 2:
1005 origin = get_word(p, 1);
1006 break;
1007
1008 case GC_POINTER >> 2:
1009 redirect(ptrcast(word, get_word(p, 1)));
1010 break;
1011
1012 case GC_REPEAT >> 2:
1013 base = origin + get_word(p, 1);
1014 count = get_word(p, 2);
1015 stride = get_word(p, 3);
1016
1017 for (i = 0; i < count; i++)
1018 redir_map(p + 16, base + i*stride, 0);
1019
1020 break;
1021
1022 case GC_BLOCK >> 2:
1023 base = origin + get_word(p, 1);
1024 count = get_word(p, 2);
1025
1026 for (i = 0; i < count; i++)
1027 redirect((word *) &get_word(base, i));
1028
1029 break;
1030
1031 case GC_MAP >> 2:
1032 redir_map(get_word(p, 1), origin, 0);
1033 break;
1034
1035 case GC_FLEX >> 2:
1036 /* Mark pointer in the local copy of an open array
1037 parameter passed by value */
1038
1039 base = origin + get_word(p, 1);
1040 ndim = get_word(p, 2);
1041 stride = get_word(p, 3);
1042
1043 /* Compute the number of elements */
1044 count = 1;
1045 for (i = 0; i < ndim; i++)
1046 count *= get_word(base, i+1);
1047
1048 /* Get address of the local copy */
1049 base = get_word(base, 0);
1050
1051 for (i = 0; i < count; i++)
1052 redir_map(p + 16, base + i*stride, 0);
1053
1054 break;
1055
1056 case GC_END >> 2:
1057 return;
1058
1059 default:
1060 panic("*bad map code %d", op);
1061 }
1062
1063 p = map_next(p);
1064 }
1065 }
1066 }
1067
1068 /* traverse_stack -- chain down the stack, redirecting in each frame */
1069 static void traverse_stack(value *xsp) {
1070 value *sp = NULL, *f;
1071 unsigned pc = 0;
1072
1073 for (f = xsp; f != NULL; f = valptr(f[BP])) {
1074 value *c = valptr(f[CP]);
1075 unsigned stkmap = 0;
1076
1077 /* Local variables and parameters */
1078 DEBUG_PRINT('m', ("\nFrame for %s",
1079 find_proc(dsegaddr(c))->p_name));
1080 if (c[CP_MAP].i != 0)
1081 redir_map(c[CP_MAP].i, stkaddr(f), FRAME_SHIFT);
1082
1083 /* Evaluation stack */
1084 if (! interpreted(c)) {
1085 /* Compiled primitive: f[PC].i is stack map */
1086 stkmap = pc;
1087 } else if (pc != 0 && c[CP_STKMAP].a != 0) {
1088 /* Look up calling PC value in stack map table. */
1089 unsigned *r = pointer(c[CP_STKMAP]);
1090 DEBUG_PRINT('m', ("\n<SM pc=%#x>", pc));
1091 while (r[0] != 0) {
1092 DEBUG_PRINT('m', (" %#x", r[0]));
1093 if (r[0] == pc) { stkmap = r[1]; break; }
1094 r += 2;
1095 }
1096 }
1097
1098 if (stkmap != 0) {
1099 DEBUG_PRINT('m', ("\nEval stack (%#x)", stkmap));
1100 redir_map(stkmap, stkaddr(sp), 0);
1101 }
1102
1103 pc = f[PC].i; sp = f + HEAD;
1104 }
1105 }
1106
1107 /* migrate -- redirect within the heap, recursively copying to new space */
1108 static void migrate(void) {
1109 hdrptr thumb[N_SIZES], big_thumb = block_pool[n_sizes];
1110 word finger[N_SIZES], p;
1111 mybool changed;
1112 int i;
1113
1114 /* For each pool, we keep a 'thumb' pointing to one of the blocks
1115 in the pool, and a 'finger' pointing somewhere in that block.
1116 We're up to date with the pool when the finger coincides with
1117 the free pointer for the pool: that implies that the thumb is
1118 on the last block. Otherwise, we must check whether the
1119 finger has reached the end of the block, and if so move to a
1120 new block. The free pointer is never at the start of a block,
1121 so we can be sure there is work to do. The migration process
1122 is finished when we're up to date with all the pools.
1123
1124 For initialisation, we set the thumb to point to the list
1125 header, and also set the finger to NULL. For an empty pool,
1126 free_ptr is NULL too, so that makes us up to date. After any
1127 change, we must check all pools again in case more objects
1128 have migrated into the new space. */
1129
1130 for (i = 0; i < n_sizes; i++) {
1131 thumb[i] = block_pool[i];
1132 finger[i] = 0;
1133 }
1134
1135 do {
1136 changed = FALSE;
1137
1138 for (i = 0; i < n_sizes; i++) {
1139 while (finger[i] != free_ptr[i]) {
1140 if (thumb[i] == block_pool[i] ||
1141 finger[i] + pool_size(i)
1142 > hdr(thumb[i])->h_memory + pool_block(i)) {
1143 thumb[i] = hdr(thumb[i])->h_next;
1144 finger[i] = hdr(thumb[i])->h_memory;
1145 }
1146
1147 changed = TRUE;
1148 p = finger[i];
1149 if (desc(p) != NULL)
1150 redir_map(desc(p)[DESC_MAP], p + BYTES_PER_WORD, 0);
1151 finger[i] = p + pool_size(i);
1152 }
1153 }
1154
1155 while (hdr(big_thumb)->h_next != block_pool[n_sizes]) {
1156 changed = TRUE;
1157 big_thumb = hdr(big_thumb)->h_next;
1158 p = hdr(big_thumb)->h_memory;
1159 if (desc(p) != NULL)
1160 redir_map(desc(p)[DESC_MAP], p+BYTES_PER_WORD, 0);
1161 }
1162 } while (changed);
1163 }
1164
1165 #ifdef HAVE_SIGPROCMASK
1166 #include <signal.h>
1167
1168 static sigset_t oldmask;
1169
1170 /* mask_signals -- block all signals */
1171 static void mask_signals(void) {
1172 sigset_t mask;
1173 sigfillset(&mask);
1174 sigprocmask(SIG_SETMASK, &mask, &oldmask);
1175 }
1176
1177 /* unmask_signals -- restore the old signal mask */
1178 static void unmask_signals(void) {
1179 sigprocmask(SIG_SETMASK, &oldmask, NULL);
1180 }
1181 #else
1182
1183 /* On Windows and other systems, just forget it */
1184 #define mask_signals()
1185 #define unmask_signals()
1186
1187 #endif
1188
1189 void gc_dump(void) {
1190 #ifdef DEBUG
1191 unsigned i;
1192 unsigned total, small_total = 0, big_total = 0, free_total = 0;
1193 hdrptr h;
1194
1195 printf("Active blocks\n");
1196 for (i = 0; i < n_sizes; i++) {
1197 if (!empty(block_pool[i])) {
1198 total = 0;
1199 printf(" %4d:", pool_size(i));
1200 for (headers(h, block_pool[i])) {
1201 ASSERT(hdr(h)->h_memory != 0
1202 && hdr(h)->h_objsize == pool_size(i));
1203 printf(" %#x", hdr(h)->h_memory);
1204 total += hdr(h)->h_size;
1205 }
1206 printf(" total %#x\n", total);
1207 small_total += total;
1208 }
1209 }
1210 if (!empty(block_pool[n_sizes])) {
1211 printf("Big blocks:");
1212 for (headers(h, block_pool[n_sizes])) {
1213 ASSERT(hdr(h)->h_memory != 0
1214 && hdr(h)->h_objsize == hdr(h)->h_size);
1215 printf(" %#x (%#x)", hdr(h)->h_memory, hdr(h)->h_size);
1216 big_total += hdr(h)->h_size;
1217 }
1218 }
1219 printf("\n");
1220
1221 printf("Free block list\n");
1222 for (i = 1; i <= BIG_BLOCK; i++) {
1223 if (!empty(free_list[i])) {
1224 if (i == BIG_BLOCK)
1225 printf(" Big:");
1226 else
1227 printf(" %4d:", i);
1228
1229 for (headers(h, free_list[i])) {
1230 ASSERT(hdr(h)->h_objsize == 0);
1231 printf(" %#x (%#x)", hdr(h)->h_memory, hdr(h)->h_size);
1232 free_total += hdr(h)->h_size;
1233 }
1234
1235 printf("\n");
1236 }
1237 }
1238 printf("\n");
1239
1240 printf("Small: %10u\n", small_total);
1241 printf("Big: %10u\n", big_total);
1242 printf("Heap: %10u", pool_total);
1243 if (small_total + big_total != pool_total) printf(" (oops)");
1244 printf("\n");
1245 printf("Free: %10u\n", free_total);
1246 #endif
1247 }
1248
1249 value *gc_collect(value *sp) {
1250 int i;
1251
1252 if (!gcflag) return sp;
1253
1254 GC_TRACE("[gc");
1255 mask_signals();
1256 gencount++;
1257 pool_total = 0;
1258
1259 /* Flip semispaces */
1260 for (i = 0; i <= n_sizes; i++) {
1261 hdrptr h = block_pool[i];
1262 block_pool[i] = old_pool[i]; old_pool[i] = h;
1263 ASSERT(empty(block_pool[i]));
1264 free_ptr[i] = 0; free_count[i] = 0;
1265 }
1266
1267 redir_map(dsegaddr(gcmap), 0, 0); /* Redirect global variables */
1268 traverse_stack(sp); /* Redirect pointers in the stack */
1269 migrate(); /* Redirect internal pointers */
1270
1271 /* Free old semispace */
1272 for (i = 0; i <= n_sizes; i++) {
1273 while (! empty(old_pool[i])) {
1274 hdrptr h = hdr(old_pool[i])->h_next;
1275 unlink(h);
1276 free_block(h, TRUE);
1277 }
1278 }
1279
1280 unmask_signals();
1281 alloc_since_gc = 0;
1282 GC_TRACE("]");
1283 return sp;
1284 }
1285
1286 /* gc_init -- initialise everything */
1287 void gc_init(void) {
1288 unsigned i;
1289
1290 init_pagetable();
1291 init_sizes();
1292
1293 /* Set up list headers */
1294 for (i = 0; i <= BIG_BLOCK; i++) free_list[i] = new_list();
1295
1296 for (i = 0; i <= n_sizes; i++) {
1297 block_pool[i] = new_list();
1298 old_pool[i] = new_list();
1299 }
1300
1301 heap_size = INIT_SIZE;
1302 }
1303
1304
1305 /* gc_debug -- set debugging flags */
1306 void gc_debug(char *flags) {
1307 int i;
1308
1309 for (i = 0; flags[i] != '\0'; i++)
1310 debug[(uchar) flags[i]] = TRUE;
1311 }
1312
1313 int gc_heap_size() {
1314 return heap_size;
1315 }
1316
1317 /* vm_alloc -- upcall from vm to allocate code buffer */
1318 void *vm_alloc(int size) {
1319 /* scratch_alloc will allocate whole pages */
1320 return scratch_alloc(size);
1321 }