2 * This module contains the garbage collector implementation.
4 * Copyright: Copyright (C) 2001-2007 Digital Mars, www.digitalmars.com.
7 * This software is provided 'as-is', without any express or implied
8 * warranty. In no event will the authors be held liable for any damages
9 * arising from the use of this software.
11 * Permission is granted to anyone to use this software for any purpose,
12 * including commercial applications, and to alter it and redistribute it
13 * freely, in both source and binary form, subject to the following
16 * o The origin of this software must not be misrepresented; you must not
17 * claim that you wrote the original software. If you use this software
18 * in a product, an acknowledgment in the product documentation would be
19 * appreciated but is not required.
20 * o Altered source versions must be plainly marked as such, and must not
21 * be misrepresented as being the original software.
22 * o This notice may not be removed or altered from any source
24 * Authors: Walter Bright, David Friedman, Sean Kelly
29 // D Programming Language Garbage Collector implementation
31 /************** Debugging ***************************/
33 //debug = COLLECT_PRINTF; // turn on printf's
34 //debug = PTRCHECK; // more pointer checking
35 //debug = PTRCHECK2; // thorough but slow pointer checking
37 /*************** Configuration *********************/
39 version = STACKGROWSDOWN; // growing the stack means subtracting from the stack pointer
40 // (use for Intel X86 CPUs)
41 // else growing the stack means adding to the stack pointer
43 /***************************************************/
45 import rt.gc.cdgc.bits: GCBits;
46 import rt.gc.cdgc.stats: GCStats, Stats;
47 import dynarray = rt.gc.cdgc.dynarray;
48 import alloc = rt.gc.cdgc.alloc;
49 import opts = rt.gc.cdgc.opts;
51 import cstdlib = tango.stdc.stdlib;
52 import cstring = tango.stdc.string;
55 * This is a small optimization that proved it's usefulness. For small chunks
56 * or memory memset() seems to be slower (probably because of the call) that
57 * simply doing a simple loop to set the memory.
59 void memset(void* dst, int c, size_t n)
61 // This number (32) has been determined empirically
63 cstring.memset(dst, c, n);
66 auto p = cast(ubyte*)(dst);
73 // BUG: The following import will likely not work, since the gcc
74 // subdirectory is elsewhere. Instead, perhaps the functions
75 // could be declared directly or some other resolution could
77 static import gcc.builtins; // for __builtin_unwind_int
87 package enum BlkAttr : uint
89 FINALIZE = 0b0000_0001,
90 NO_SCAN = 0b0000_0010,
91 NO_MOVE = 0b0000_0100,
92 ALL_BITS = 0b1111_1111
95 package bool has_pointermap(uint attrs)
97 return !opts.options.conservative && !(attrs & BlkAttr.NO_SCAN);
102 alias void delegate(Object) DEvent;
103 alias void delegate( void*, void* ) scanFn;
104 enum { OPFAIL = ~cast(size_t)0 }
108 version (DigitalMars) version(OSX)
109 oid _d_osx_image_init();
111 void* rt_stackBottom();
113 void rt_finalize( void* p, bool det = true );
114 void rt_attachDisposeEvent(Object h, DEvent e);
115 bool rt_detachDisposeEvent(Object h, DEvent e);
116 void rt_scanStaticData( scanFn scan );
119 bool thread_needLock();
120 void thread_suspendAll();
121 void thread_resumeAll();
122 void thread_scanAll( scanFn fn, void* curStackTop = null );
124 void onOutOfMemoryError();
132 POOLSIZE = (4096*256),
146 B_PAGE, // start of large alloc
147 B_PAGEPLUS, // continuation of large alloc
166 int opCmp(in Range other)
168 if (pbot < other.pbot)
171 return cast(int)(pbot > other.pbot);
176 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
177 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
178 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
181 /* ============================ GC =============================== */
184 class GCLock {} // just a dummy so we can get a global lock
195 // !=0 means don't scan stack
200 /// Turn off collections if > 0
203 /// min(pool.baseAddr)
205 /// max(pool.topAddr)
208 /// Free list for each size
209 List*[B_MAX] free_list;
211 dynarray.DynArray!(void*) roots;
212 dynarray.DynArray!(Range) ranges;
213 dynarray.DynArray!(Pool) pools;
218 // call locked if necessary
219 private T locked(T, alias Code)()
221 if (thread_needLock())
222 synchronized (gc.lock) return Code();
231 assert (gc !is null);
233 for (size_t i = 0; i < gc.pools.length; i++) {
234 Pool* pool = gc.pools[i];
237 assert(gc.min_addr == pool.baseAddr);
238 if (i + 1 < gc.pools.length)
239 assert(*pool < gc.pools[i + 1]);
240 else if (i + 1 == gc.pools.length)
241 assert(gc.max_addr == pool.topAddr);
244 gc.roots.Invariant();
245 gc.ranges.Invariant();
247 for (size_t i = 0; i < gc.ranges.length; i++) {
248 assert(gc.ranges[i].pbot);
249 assert(gc.ranges[i].ptop);
250 assert(gc.ranges[i].pbot <= gc.ranges[i].ptop);
253 for (size_t i = 0; i < B_PAGE; i++)
254 for (List *list = gc.free_list[i]; list; list = list.next)
263 * Find Pool that pointer is in.
264 * Return null if not in a Pool.
265 * Assume pools is sorted.
267 Pool *findPool(void *p)
269 if (p >= gc.min_addr && p < gc.max_addr)
271 if (gc.pools.length == 1)
276 for (size_t i = 0; i < gc.pools.length; i++)
278 Pool* pool = gc.pools[i];
279 if (p < pool.topAddr)
281 if (pool.baseAddr <= p)
292 * Determine the base address of the block containing p. If p is not a gc
293 * allocated pointer, return null.
295 BlkInfo getInfo(void* p)
305 size_t offset = cast(size_t)(p - pool.baseAddr);
306 size_t pn = offset / PAGESIZE;
307 Bins bin = cast(Bins)pool.pagetable[pn];
309 ////////////////////////////////////////////////////////////////////
311 ////////////////////////////////////////////////////////////////////
315 info.base = pool.baseAddr + (offset & notbinsize[bin]);
317 else if (bin == B_PAGEPLUS)
321 --pn, offset -= PAGESIZE;
323 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
325 info.base = pool.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
327 // fix bin for use by size calc below
328 bin = cast(Bins)pool.pagetable[pn];
331 ////////////////////////////////////////////////////////////////////
333 ////////////////////////////////////////////////////////////////////
335 info.size = binsize[bin];
341 pt = &pool.pagetable[0];
342 for (i = pn + 1; i < pool.npages; i++)
344 if (pt[i] != B_PAGEPLUS)
347 info.size = (i - pn) * PAGESIZE;
350 ////////////////////////////////////////////////////////////////////
352 ////////////////////////////////////////////////////////////////////
354 info.attr = getAttr(pool, cast(size_t)(offset / 16));
355 if (!(info.attr & BlkAttr.NO_SCAN))
356 info.size -= (size_t*).sizeof; // bitmask
363 * Compute bin for size.
365 static Bins findBin(size_t size)
409 * Allocate a new pool of at least size bytes.
410 * Sort it into pools.
411 * Mark all memory in the pool as B_FREE.
412 * Return the actual number of bytes reserved or 0 on error.
414 size_t reserve(size_t size)
417 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
418 Pool* pool = newPool(npages);
422 return pool.npages * PAGESIZE;
427 * Minimizes physical memory usage by returning free pools to the OS.
435 for (n = 0; n < gc.pools.length; n++)
438 for (pn = 0; pn < pool.npages; pn++)
440 if (cast(Bins)pool.pagetable[pn] != B_FREE)
443 if (pn < pool.npages)
446 gc.pools.remove_at(n);
449 gc.min_addr = gc.pools[0].baseAddr;
450 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
455 * Allocate a chunk of memory that is larger than a page.
456 * Return null if out of memory.
458 void *bigAlloc(size_t size)
468 npages = (size + PAGESIZE - 1) / PAGESIZE;
472 // This code could use some refinement when repeatedly
473 // allocating very large arrays.
475 for (n = 0; n < gc.pools.length; n++)
478 pn = pool.allocPages(npages);
493 freedpages = fullcollectshell();
494 if (freedpages >= gc.pools.length * ((POOLSIZE / PAGESIZE) / 4))
499 // Release empty pools to prevent bloat
502 pool = newPool(npages);
508 pn = pool.allocPages(npages);
509 assert(pn != OPFAIL);
512 // Release empty pools to prevent bloat
515 pool = newPool(npages);
518 pn = pool.allocPages(npages);
519 assert(pn != OPFAIL);
529 pool.pagetable[pn] = B_PAGE;
531 memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
532 p = pool.baseAddr + pn * PAGESIZE;
533 memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
534 if (opts.options.mem_stomp)
535 memset(p, 0xF1, size);
539 return null; // let mallocNoSync handle the error
544 * Allocate a new pool with at least npages in it.
545 * Sort it into pools.
546 * Return null if failed.
548 Pool *newPool(size_t npages)
550 // Minimum of POOLSIZE
551 if (npages < POOLSIZE/PAGESIZE)
552 npages = POOLSIZE/PAGESIZE;
553 else if (npages > POOLSIZE/PAGESIZE)
555 // Give us 150% of requested size, so there's room to extend
556 auto n = npages + (npages >> 1);
557 if (n < size_t.max/PAGESIZE)
561 // Allocate successively larger pools up to 8 megs
564 size_t n = gc.pools.length;
566 n = 8; // cap pool size at 8 megs
567 n *= (POOLSIZE / PAGESIZE);
573 p.initialize(npages);
580 Pool* pool = gc.pools.insert_sorted(p);
583 gc.min_addr = gc.pools[0].baseAddr;
584 gc.max_addr = gc.pools[gc.pools.length - 1].topAddr;
591 * Allocate a page of bin's.
595 int allocPage(Bins bin)
603 for (n = 0; n < gc.pools.length; n++)
606 pn = pool.allocPages(1);
613 pool.pagetable[pn] = cast(ubyte)bin;
615 // Convert page to free list
616 size_t size = binsize[bin];
617 List **b = &gc.free_list[bin];
619 p = pool.baseAddr + pn * PAGESIZE;
621 for (; p < ptop; p += size)
623 (cast(List *)p).next = *b;
631 * Marks a range of memory using the conservative bit mask. Used for
632 * the stack, for the data segment, and additional memory ranges.
634 void mark_conservative(void* pbot, void* ptop)
636 mark(pbot, ptop, PointerMap.init.bits.ptr);
641 * Search a range of memory values and mark any pointers into the GC pool.
643 void mark(void *pbot, void *ptop, size_t* pm_bitmask)
645 // TODO: make our own assert because assert uses the GC
646 assert (pbot <= ptop);
648 const BITS_PER_WORD = size_t.sizeof * 8;
650 void **p1 = cast(void **)pbot;
651 void **p2 = cast(void **)ptop;
655 size_t type_size = pm_bitmask[0];
656 size_t* pm_bits = pm_bitmask + 1;
658 //printf("marking range: %p -> %p\n", pbot, ptop);
659 for (; p1 + type_size <= p2; p1 += type_size) {
660 for (size_t n = 0; n < type_size; n++) {
661 // scan bit set for this word
662 if (!(pm_bits[n / BITS_PER_WORD] & (1 << (n % BITS_PER_WORD))))
667 if (p < gc.min_addr || p >= gc.max_addr)
670 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
673 Pool* pool = findPool(p);
676 size_t offset = cast(size_t)(p - pool.baseAddr);
678 size_t pn = offset / PAGESIZE;
679 Bins bin = cast(Bins)pool.pagetable[pn];
681 // Adjust bit to be at start of allocated memory block
683 bit_i = (offset & notbinsize[bin]) >> 4;
684 else if (bin == B_PAGEPLUS)
690 while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
691 bit_i = pn * (PAGESIZE / 16);
695 // Don't mark bits in B_FREE pages
699 if (bin >= B_PAGE) // Cache B_PAGE and B_PAGEPLUS lookups
700 pcache = cast(size_t)p & ~(PAGESIZE-1);
702 if (!pool.mark.test(bit_i))
704 pool.mark.set(bit_i);
705 if (!pool.noscan.test(bit_i))
707 pool.scan.set(bit_i);
715 gc.any_changes = true;
719 * Return number of full pages free'd.
721 size_t fullcollectshell()
723 gc.stats.collection_started();
725 gc.stats.collection_finished();
727 // The purpose of the 'shell' is to ensure all the registers
728 // get put on the stack so they'll be scanned
733 gcc.builtins.__builtin_unwind_init();
740 uint eax,ecx,edx,ebx,ebp,esi,edi;
753 else version (X86_64)
755 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,r8,r9,r10,r11,r12,r13,r14,r15;
778 static assert( false, "Architecture not supported." );
789 result = fullcollect(sp);
812 size_t fullcollect(void *stackTop)
817 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
820 gc.stats.world_stopped();
825 gc.any_changes = false;
826 for (n = 0; n < gc.pools.length; n++)
831 pool.freebits.zero();
834 // Mark each free entry, so it doesn't get scanned
835 for (n = 0; n < B_PAGE; n++)
837 for (List *list = gc.free_list[n]; list; list = list.next)
839 pool = findPool(list);
841 pool.freebits.set(cast(size_t)(cast(byte*)list - pool.baseAddr) / 16);
845 for (n = 0; n < gc.pools.length; n++)
848 pool.mark.copy(&pool.freebits);
851 void mark_conservative_dg(void* pbot, void* ptop)
853 mark_conservative(pbot, ptop);
856 rt_scanStaticData(&mark_conservative_dg);
860 // Scan stacks and registers for each paused thread
861 thread_scanAll(&mark_conservative_dg, stackTop);
865 debug(COLLECT_PRINTF) printf("scan roots[]\n");
866 mark_conservative(gc.roots.ptr, gc.roots.ptr + gc.roots.length);
869 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
870 for (n = 0; n < gc.ranges.length; n++)
872 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", gc.ranges[n].pbot, gc.ranges[n].ptop);
873 mark_conservative(gc.ranges[n].pbot, gc.ranges[n].ptop);
876 debug(COLLECT_PRINTF) printf("\tscan heap\n");
877 while (gc.any_changes)
879 gc.any_changes = false;
880 for (n = 0; n < gc.pools.length; n++)
888 bbase = pool.scan.base();
889 btop = bbase + pool.scan.nwords;
890 for (b = bbase; b < btop;)
906 o = pool.baseAddr + (b - bbase) * 32 * 16;
907 if (!(bitm & 0xFFFF))
912 for (; bitm; o += 16, bitm >>= 1)
917 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
918 bin = cast(Bins)pool.pagetable[pn];
920 if (opts.options.conservative)
921 mark_conservative(o, o + binsize[bin]);
923 auto end_of_blk = cast(size_t**)(o +
924 binsize[bin] - size_t.sizeof);
925 size_t* pm_bitmask = *end_of_blk;
926 mark(o, end_of_blk, pm_bitmask);
929 else if (bin == B_PAGE || bin == B_PAGEPLUS)
931 if (bin == B_PAGEPLUS)
933 while (pool.pagetable[pn - 1] != B_PAGE)
937 while (pn + u < pool.npages &&
938 pool.pagetable[pn + u] == B_PAGEPLUS)
941 size_t blk_size = u * PAGESIZE;
942 if (opts.options.conservative)
943 mark_conservative(o, o + blk_size);
945 auto end_of_blk = cast(size_t**)(o + blk_size -
947 size_t* pm_bitmask = *end_of_blk;
948 mark(o, end_of_blk, pm_bitmask);
957 gc.stats.world_started();
959 // Free up everything not marked
960 debug(COLLECT_PRINTF) printf("\tfree'ing\n");
961 size_t freedpages = 0;
963 for (n = 0; n < gc.pools.length; n++)
966 uint* bbase = pool.mark.base();
968 for (pn = 0; pn < pool.npages; pn++, bbase += PAGESIZE / (32 * 16))
970 Bins bin = cast(Bins)pool.pagetable[pn];
974 auto size = binsize[bin];
975 byte* p = pool.baseAddr + pn * PAGESIZE;
976 byte* ptop = p + PAGESIZE;
977 size_t bit_i = pn * (PAGESIZE/16);
978 size_t bit_stride = size / 16;
980 version(none) // BUG: doesn't work because freebits() must also be cleared
982 // If free'd entire page
983 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 &&
984 bbase[3] == 0 && bbase[4] == 0 && bbase[5] == 0 &&
985 bbase[6] == 0 && bbase[7] == 0)
987 for (; p < ptop; p += size, bit_i += bit_stride)
989 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
990 if (opts.options.sentinel)
991 rt_finalize(cast(List *)sentinel_add(p), false/*gc.no_stack > 0*/);
993 rt_finalize(cast(List *)p, false/*gc.no_stack > 0*/);
995 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
997 List *list = cast(List *)p;
999 if (opts.options.mem_stomp)
1000 memset(p, 0xF3, size);
1002 pool.pagetable[pn] = B_FREE;
1007 for (; p < ptop; p += size, bit_i += bit_stride)
1009 if (!pool.mark.test(bit_i))
1011 if (opts.options.sentinel)
1012 sentinel_Invariant(sentinel_add(p));
1014 pool.freebits.set(bit_i);
1015 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1016 if (opts.options.sentinel)
1017 rt_finalize(cast(List *)sentinel_add(p), false/*gc.no_stack > 0*/);
1019 rt_finalize(cast(List *)p, false/*gc.no_stack > 0*/);
1021 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1023 List *list = cast(List *)p;
1025 if (opts.options.mem_stomp)
1026 memset(p, 0xF3, size);
1032 else if (bin == B_PAGE)
1034 size_t bit_i = pn * (PAGESIZE / 16);
1035 if (!pool.mark.test(bit_i))
1037 byte *p = pool.baseAddr + pn * PAGESIZE;
1038 if (opts.options.sentinel)
1039 sentinel_Invariant(sentinel_add(p));
1040 if (pool.finals.nbits && pool.finals.testClear(bit_i)) {
1041 if (opts.options.sentinel)
1042 rt_finalize(sentinel_add(p), false/*gc.no_stack > 0*/);
1044 rt_finalize(p, false/*gc.no_stack > 0*/);
1046 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1048 debug(COLLECT_PRINTF) printf("\tcollecting big %x\n", p);
1049 pool.pagetable[pn] = B_FREE;
1051 if (opts.options.mem_stomp)
1052 memset(p, 0xF3, PAGESIZE);
1053 while (pn + 1 < pool.npages && pool.pagetable[pn + 1] == B_PAGEPLUS)
1056 pool.pagetable[pn] = B_FREE;
1059 if (opts.options.mem_stomp)
1062 memset(p, 0xF3, PAGESIZE);
1071 gc.free_list[] = null;
1073 // Free complete pages, rebuild free list
1074 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
1075 size_t recoveredpages = 0;
1076 for (n = 0; n < gc.pools.length; n++)
1079 for (size_t pn = 0; pn < pool.npages; pn++)
1081 Bins bin = cast(Bins)pool.pagetable[pn];
1087 size_t size = binsize[bin];
1088 size_t bit_stride = size / 16;
1089 size_t bit_base = pn * (PAGESIZE / 16);
1090 size_t bit_top = bit_base + (PAGESIZE / 16);
1094 for (; bit_i < bit_top; bit_i += bit_stride)
1096 if (!pool.freebits.test(bit_i))
1099 pool.pagetable[pn] = B_FREE;
1104 p = pool.baseAddr + pn * PAGESIZE;
1105 for (u = 0; u < PAGESIZE; u += size)
1107 bit_i = bit_base + u / 16;
1108 if (pool.freebits.test(bit_i))
1110 List *list = cast(List *)(p + u);
1111 // avoid unnecessary writes
1112 if (list.next != gc.free_list[bin])
1113 list.next = gc.free_list[bin];
1114 gc.free_list[bin] = list;
1121 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
1122 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, gc.pools.length);
1124 return freedpages + recoveredpages;
1131 uint getAttr(Pool* pool, size_t bit_i)
1140 if (pool.finals.nbits &&
1141 pool.finals.test(bit_i))
1142 attrs |= BlkAttr.FINALIZE;
1143 if (pool.noscan.test(bit_i))
1144 attrs |= BlkAttr.NO_SCAN;
1145 // if (pool.nomove.nbits &&
1146 // pool.nomove.test(bit_i))
1147 // attrs |= BlkAttr.NO_MOVE;
1155 void setAttr(Pool* pool, size_t bit_i, uint mask)
1162 if (mask & BlkAttr.FINALIZE)
1164 if (!pool.finals.nbits)
1165 pool.finals.alloc(pool.mark.nbits);
1166 pool.finals.set(bit_i);
1168 if (mask & BlkAttr.NO_SCAN)
1170 pool.noscan.set(bit_i);
1172 // if (mask & BlkAttr.NO_MOVE)
1174 // if (!pool.nomove.nbits)
1175 // pool.nomove.alloc(pool.mark.nbits);
1176 // pool.nomove.set(bit_i);
1184 void clrAttr(Pool* pool, size_t bit_i, uint mask)
1191 if (mask & BlkAttr.FINALIZE && pool.finals.nbits)
1192 pool.finals.clear(bit_i);
1193 if (mask & BlkAttr.NO_SCAN)
1194 pool.noscan.clear(bit_i);
1195 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
1196 // pool.nomove.clear(bit_i);
1204 gc.stack_bottom = cast(char*)&dummy;
1205 opts.parse(cstdlib.getenv("D_GC_OPTS"));
1206 gc.lock = GCLock.classinfo;
1208 setStackBottom(rt_stackBottom());
1209 gc.stats = Stats(gc);
1216 private void *malloc(size_t size, uint attrs, size_t* pm_bitmask)
1220 gc.stats.malloc_started(size, attrs, pm_bitmask);
1222 gc.stats.malloc_finished(p);
1227 if (opts.options.sentinel)
1228 size += SENTINEL_EXTRA;
1230 bool has_pm = has_pointermap(attrs);
1232 size += size_t.sizeof;
1235 // Cache previous binsize lookup - Dave Fladebo.
1236 static size_t lastsize = -1;
1237 static Bins lastbin;
1238 if (size == lastsize)
1242 bin = findBin(size);
1247 size_t capacity; // to figure out where to store the bitmask
1250 p = gc.free_list[bin];
1253 if (!allocPage(bin) && !gc.disabled) // try to find a new page
1255 if (!thread_needLock())
1257 /* Then we haven't locked it yet. Be sure
1258 * and gc.lock for a collection, since a finalizer
1259 * may start a new thread.
1261 synchronized (gc.lock)
1266 else if (!fullcollectshell()) // collect to find a new page
1271 if (!gc.free_list[bin] && !allocPage(bin))
1273 newPool(1); // allocate new pool to find a new page
1274 int result = allocPage(bin);
1276 onOutOfMemoryError();
1278 p = gc.free_list[bin];
1280 capacity = binsize[bin];
1282 // Return next item from free list
1283 gc.free_list[bin] = (cast(List*)p).next;
1284 if (!(attrs & BlkAttr.NO_SCAN))
1285 memset(p + size, 0, capacity - size);
1286 if (opts.options.mem_stomp)
1287 memset(p, 0xF0, size);
1293 onOutOfMemoryError();
1294 // Round the size up to the number of pages needed to store it
1295 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
1296 capacity = npages * PAGESIZE;
1299 // Store the bit mask AFTER SENTINEL_POST
1300 // TODO: store it BEFORE, so the bitmask is protected too
1302 auto end_of_blk = cast(size_t**)(p + capacity - size_t.sizeof);
1303 *end_of_blk = pm_bitmask;
1304 size -= size_t.sizeof;
1307 if (opts.options.sentinel) {
1308 size -= SENTINEL_EXTRA;
1309 p = sentinel_add(p);
1310 sentinel_init(p, size);
1315 Pool *pool = findPool(p);
1318 setAttr(pool, cast(size_t)(p - pool.baseAddr) / 16, attrs);
1327 private void *calloc(size_t size, uint attrs, size_t* pm_bitmask)
1331 void *p = malloc(size, attrs, pm_bitmask);
1340 private void *realloc(void *p, size_t size, uint attrs,
1353 p = malloc(size, attrs, pm_bitmask);
1357 Pool* pool = findPool(p);
1361 // Set or retrieve attributes as appropriate
1362 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1364 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1365 setAttr(pool, bit_i, attrs);
1368 attrs = getAttr(pool, bit_i);
1370 void* blk_base_addr = pool.findBase(p);
1371 size_t blk_size = pool.findSize(p);
1372 bool has_pm = has_pointermap(attrs);
1373 size_t pm_bitmask_size = 0;
1375 pm_bitmask_size = size_t.sizeof;
1376 // Retrieve pointer map bit mask if appropriate
1377 if (pm_bitmask is null) {
1378 auto end_of_blk = cast(size_t**)(blk_base_addr +
1379 blk_size - size_t.sizeof);
1380 pm_bitmask = *end_of_blk;
1384 if (opts.options.sentinel)
1386 sentinel_Invariant(p);
1387 size_t sentinel_stored_size = *sentinel_size(p);
1388 if (sentinel_stored_size != size)
1390 void* p2 = malloc(size, attrs, pm_bitmask);
1391 if (sentinel_stored_size < size)
1392 size = sentinel_stored_size;
1393 cstring.memcpy(p2, p, size);
1399 size += pm_bitmask_size;
1400 if (blk_size >= PAGESIZE && size >= PAGESIZE)
1402 auto psz = blk_size / PAGESIZE;
1403 auto newsz = (size + PAGESIZE - 1) / PAGESIZE;
1407 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1412 if (opts.options.mem_stomp)
1413 memset(p + size - pm_bitmask_size, 0xF2,
1414 blk_size - size - pm_bitmask_size);
1415 pool.freePages(pagenum + newsz, psz - newsz);
1417 auto end_of_blk = cast(size_t**)(
1418 blk_base_addr + (PAGESIZE * newsz) -
1420 *end_of_blk = pm_bitmask;
1424 else if (pagenum + newsz <= pool.npages)
1426 // Attempt to expand in place
1427 for (size_t i = pagenum + psz; 1;)
1429 if (i == pagenum + newsz)
1431 if (opts.options.mem_stomp)
1432 memset(p + blk_size - pm_bitmask_size,
1433 0xF0, size - blk_size
1435 memset(pool.pagetable + pagenum +
1436 psz, B_PAGEPLUS, newsz - psz);
1438 auto end_of_blk = cast(size_t**)(
1440 (PAGESIZE * newsz) -
1442 *end_of_blk = pm_bitmask;
1446 if (i == pool.npages)
1450 if (pool.pagetable[i] != B_FREE)
1456 // if new size is bigger or less than half
1457 if (blk_size < size || blk_size > size * 2)
1459 size -= pm_bitmask_size;
1460 blk_size -= pm_bitmask_size;
1461 void* p2 = malloc(size, attrs, pm_bitmask);
1462 if (blk_size < size)
1464 cstring.memcpy(p2, p, size);
1474 * Attempt to in-place enlarge the memory block pointed to by p by at least
1475 * min_size beyond its current capacity, up to a maximum of max_size. This
1476 * does not attempt to move the memory block (like realloc() does).
1479 * 0 if could not extend p,
1480 * total size of entire memory block if successful.
1482 private size_t extend(void* p, size_t minsize, size_t maxsize)
1485 assert( minsize <= maxsize );
1489 if (opts.options.sentinel)
1492 Pool* pool = findPool(p);
1496 // Retrieve attributes
1497 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1498 uint attrs = getAttr(pool, bit_i);
1500 void* blk_base_addr = pool.findBase(p);
1501 size_t blk_size = pool.findSize(p);
1502 bool has_pm = has_pointermap(attrs);
1503 size_t* pm_bitmask = null;
1504 size_t pm_bitmask_size = 0;
1506 pm_bitmask_size = size_t.sizeof;
1507 // Retrieve pointer map bit mask
1508 auto end_of_blk = cast(size_t**)(blk_base_addr +
1509 blk_size - size_t.sizeof);
1510 pm_bitmask = *end_of_blk;
1512 minsize += size_t.sizeof;
1513 maxsize += size_t.sizeof;
1516 if (blk_size < PAGESIZE)
1517 return 0; // cannot extend buckets
1519 auto psz = blk_size / PAGESIZE;
1520 auto minsz = (minsize + PAGESIZE - 1) / PAGESIZE;
1521 auto maxsz = (maxsize + PAGESIZE - 1) / PAGESIZE;
1523 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
1526 for (sz = 0; sz < maxsz; sz++)
1528 auto i = pagenum + psz + sz;
1529 if (i == pool.npages)
1531 if (pool.pagetable[i] != B_FREE)
1541 size_t new_size = (psz + sz) * PAGESIZE;
1543 if (opts.options.mem_stomp)
1544 memset(p + blk_size - pm_bitmask_size, 0xF0,
1545 new_size - blk_size - pm_bitmask_size);
1546 memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
1551 new_size -= size_t.sizeof;
1552 auto end_of_blk = cast(size_t**)(blk_base_addr + new_size);
1553 *end_of_blk = pm_bitmask;
1562 private void free(void *p)
1571 // Find which page it is in
1573 if (!pool) // if not one of ours
1575 if (opts.options.sentinel) {
1576 sentinel_Invariant(p);
1577 p = sentinel_sub(p);
1579 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1580 bit_i = cast(size_t)(p - pool.baseAddr) / 16;
1581 clrAttr(pool, bit_i, BlkAttr.ALL_BITS);
1583 bin = cast(Bins)pool.pagetable[pagenum];
1584 if (bin == B_PAGE) // if large alloc
1589 while (++n < pool.npages && pool.pagetable[n] == B_PAGEPLUS)
1591 if (opts.options.mem_stomp)
1592 memset(p, 0xF2, npages * PAGESIZE);
1593 pool.freePages(pagenum, npages);
1598 List *list = cast(List*)p;
1600 if (opts.options.mem_stomp)
1601 memset(p, 0xF2, binsize[bin]);
1603 list.next = gc.free_list[bin];
1604 gc.free_list[bin] = list;
1610 * Determine the allocated size of pointer p. If p is an interior pointer
1611 * or not a gc allocated pointer, return 0.
1613 private size_t sizeOf(void *p)
1617 if (opts.options.sentinel)
1618 p = sentinel_sub(p);
1620 Pool* pool = findPool(p);
1624 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
1625 uint attrs = getAttr(pool, biti);
1627 size_t size = pool.findSize(p);
1628 size_t pm_bitmask_size = 0;
1629 if (has_pointermap(attrs))
1630 pm_bitmask_size = size_t.sizeof;
1632 if (opts.options.sentinel) {
1633 // Check for interior pointer
1635 // 1) size is a power of 2 for less than PAGESIZE values
1636 // 2) base of memory pool is aligned on PAGESIZE boundary
1637 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1639 return size - SENTINEL_EXTRA - pm_bitmask_size;
1642 if (p == gc.p_cache)
1643 return gc.size_cache;
1645 // Check for interior pointer
1647 // 1) size is a power of 2 for less than PAGESIZE values
1648 // 2) base of memory pool is aligned on PAGESIZE boundary
1649 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
1653 gc.size_cache = size - pm_bitmask_size;
1655 return gc.size_cache;
1661 * Verify that pointer p:
1662 * 1) belongs to this memory pool
1663 * 2) points to the start of an allocated piece of memory
1664 * 3) is not on a free list
1666 private void checkNoSync(void *p)
1670 if (opts.options.sentinel)
1671 sentinel_Invariant(p);
1679 if (opts.options.sentinel)
1680 p = sentinel_sub(p);
1683 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1684 bin = cast(Bins)pool.pagetable[pagenum];
1685 assert(bin <= B_PAGE);
1686 size = binsize[bin];
1687 assert((cast(size_t)p & (size - 1)) == 0);
1693 // Check that p is not on a free list
1696 for (list = gc.free_list[bin]; list; list = list.next)
1698 assert(cast(void*)list != p);
1709 private void setStackBottom(void *p)
1711 version (STACKGROWSDOWN)
1713 //p = (void *)((uint *)p + 4);
1714 if (p > gc.stack_bottom)
1716 gc.stack_bottom = p;
1721 //p = (void *)((uint *)p - 4);
1722 if (p < gc.stack_bottom)
1724 gc.stack_bottom = cast(char*)p;
1731 * Retrieve statistics about garbage collection.
1732 * Useful for debugging and tuning.
1734 private GCStats getStats()
1744 for (n = 0; n < gc.pools.length; n++)
1746 Pool* pool = gc.pools[n];
1747 psize += pool.npages * PAGESIZE;
1748 for (size_t j = 0; j < pool.npages; j++)
1750 Bins bin = cast(Bins)pool.pagetable[j];
1753 else if (bin == B_PAGE)
1755 else if (bin < B_PAGE)
1760 for (n = 0; n < B_PAGE; n++)
1762 for (List *list = gc.free_list[n]; list; list = list.next)
1763 flsize += binsize[n];
1766 usize = bsize - flsize;
1768 stats.poolsize = psize;
1769 stats.usedsize = bsize - flsize;
1770 stats.freelistsize = flsize;
1774 /******************* weak-reference support *********************/
1776 private struct WeakPointer
1780 void ondestroy(Object r)
1782 assert(r is reference);
1783 // lock for memory consistency (parallel readers)
1784 // also ensures that weakpointerDestroy can be called while another
1785 // thread is freeing the reference with "delete"
1786 return locked!(void, () {
1793 * Create a weak pointer to the given object.
1794 * Returns a pointer to an opaque struct allocated in C memory.
1796 void* weakpointerCreate( Object r )
1800 // must be allocated in C memory
1801 // 1. to hide the reference from the GC
1802 // 2. the GC doesn't scan delegates added by rt_attachDisposeEvent
1804 auto wp = cast(WeakPointer*)(cstdlib.malloc(WeakPointer.sizeof));
1806 onOutOfMemoryError();
1808 rt_attachDisposeEvent(r, &wp.ondestroy);
1815 * Destroy a weak pointer returned by weakpointerCreate().
1816 * If null is passed, nothing happens.
1818 void weakpointerDestroy( void* p )
1822 auto wp = cast(WeakPointer*)p;
1823 // must be extra careful about the GC or parallel threads
1824 // finalizing the reference at the same time
1825 return locked!(void, () {
1827 rt_detachDisposeEvent(wp.reference, &wp.ondestroy);
1834 * Query a weak pointer and return either the object passed to
1835 * weakpointerCreate, or null if it was free'd in the meantime.
1836 * If null is passed, null is returned.
1838 Object weakpointerGet( void* p )
1842 // NOTE: could avoid the lock by using Fawzi style GC counters but
1843 // that'd require core.sync.Atomic and lots of care about memory
1844 // consistency it's an optional optimization see
1845 // http://dsource.org/projects/tango/browser/trunk/user/tango/core/Lifetime.d?rev=5100#L158
1846 return locked!(Object, () {
1847 return (cast(WeakPointer*)p).reference;
1853 /* ============================ Pool =============================== */
1860 GCBits mark; // entries already scanned, or should not be scanned
1861 GCBits scan; // entries that need to be scanned
1862 GCBits freebits; // entries that are on the free list
1863 GCBits finals; // entries that need finalizer run on them
1864 GCBits noscan; // entries that should not be scanned
1870 void initialize(size_t npages)
1872 size_t poolsize = npages * PAGESIZE;
1873 assert(poolsize >= POOLSIZE);
1874 baseAddr = cast(byte *) alloc.os_mem_map(poolsize);
1876 // Some of the code depends on page alignment of memory pools
1877 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
1885 topAddr = baseAddr + poolsize;
1887 mark.alloc(cast(size_t)poolsize / 16);
1888 scan.alloc(cast(size_t)poolsize / 16);
1889 freebits.alloc(cast(size_t)poolsize / 16);
1890 noscan.alloc(cast(size_t)poolsize / 16);
1892 pagetable = cast(ubyte*) cstdlib.malloc(npages);
1894 onOutOfMemoryError();
1895 memset(pagetable, B_FREE, npages);
1897 this.npages = npages;
1909 result = alloc.os_mem_unmap(baseAddr, npages * PAGESIZE);
1917 // See Gcx.Dtor() for the rationale of the null check.
1919 cstdlib.free(pagetable);
1939 //freebits.Invariant();
1940 //finals.Invariant();
1941 //noscan.Invariant();
1945 //if (baseAddr + npages * PAGESIZE != topAddr)
1946 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
1947 assert(baseAddr + npages * PAGESIZE == topAddr);
1950 for (size_t i = 0; i < npages; i++)
1952 Bins bin = cast(Bins)pagetable[i];
1953 assert(bin < B_MAX);
1959 * Allocate n pages from Pool.
1960 * Returns OPFAIL on failure.
1962 size_t allocPages(size_t n)
1968 for (i = 0; i < npages; i++)
1970 if (pagetable[i] == B_FREE)
1983 * Free npages pages starting with pagenum.
1985 void freePages(size_t pagenum, size_t npages)
1987 memset(&pagetable[pagenum], B_FREE, npages);
1992 * Find base address of block containing pointer p.
1993 * Returns null if the pointer doesn't belong to this pool
1995 void* findBase(void *p)
1997 size_t offset = cast(size_t)(p - this.baseAddr);
1998 size_t pagenum = offset / PAGESIZE;
1999 Bins bin = cast(Bins)this.pagetable[pagenum];
2000 // Adjust bit to be at start of allocated memory block
2002 return this.baseAddr + (offset & notbinsize[bin]);
2003 if (bin == B_PAGEPLUS) {
2005 --pagenum, offset -= PAGESIZE;
2006 } while (cast(Bins)this.pagetable[pagenum] == B_PAGEPLUS);
2007 return this.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
2009 // we are in a B_FREE page
2015 * Find size of pointer p.
2016 * Returns 0 if p doesn't belong to this pool if if it's block size is less
2019 size_t findSize(void *p)
2021 size_t pagenum = cast(size_t)(p - this.baseAddr) / PAGESIZE;
2022 Bins bin = cast(Bins)this.pagetable[pagenum];
2024 return binsize[bin];
2025 for (size_t i = pagenum + 1; i < this.npages; i++)
2026 if (this.pagetable[i] != B_PAGEPLUS)
2027 return (i - pagenum) * PAGESIZE;
2028 return (this.npages - pagenum) * PAGESIZE;
2033 * Used for sorting pools
2035 int opCmp(in Pool other)
2037 if (baseAddr < other.baseAddr)
2040 return cast(int)(baseAddr > other.baseAddr);
2045 /* ============================ SENTINEL =============================== */
2048 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2049 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2050 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2053 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2054 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2055 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2058 void sentinel_init(void *p, size_t size)
2060 *sentinel_size(p) = size;
2061 *sentinel_pre(p) = SENTINEL_PRE;
2062 *sentinel_post(p) = SENTINEL_POST;
2066 void sentinel_Invariant(void *p)
2068 assert(*sentinel_pre(p) == SENTINEL_PRE);
2069 assert(*sentinel_post(p) == SENTINEL_POST);
2073 void *sentinel_add(void *p)
2075 return p + 2 * size_t.sizeof;
2079 void *sentinel_sub(void *p)
2081 return p - 2 * size_t.sizeof;
2086 /* ============================ C Public Interface ======================== */
2089 private int _termCleanupLevel=1;
2093 /// sets the cleanup level done by gc
2096 /// 2: fullCollect ignoring stack roots (might crash daemonThreads)
2097 /// result !=0 if the value was invalid
2098 int gc_setTermCleanupLevel(int cLevel)
2100 if (cLevel<0 || cLevel>2) return cLevel;
2101 _termCleanupLevel=cLevel;
2105 /// returns the cleanup level done by gc
2106 int gc_getTermCleanupLevel()
2108 return _termCleanupLevel;
2113 scope (exit) assert (Invariant());
2114 gc = cast(GC*) cstdlib.calloc(1, GC.sizeof);
2117 version (DigitalMars) version(OSX) {
2118 _d_osx_image_init();
2120 // NOTE: The GC must initialize the thread library
2121 // before its first collection.
2127 assert (Invariant());
2128 if (_termCleanupLevel<1) {
2130 } else if (_termCleanupLevel==2){
2131 // a more complete cleanup
2132 // NOTE: There may be daemons threads still running when this routine is
2133 // called. If so, cleaning memory out from under then is a good
2134 // way to make them crash horribly.
2135 // Often this probably doesn't matter much since the app is
2136 // supposed to be shutting down anyway, but for example tests might
2137 // crash (and be considerd failed even if the test was ok).
2138 // thus this is not the default and should be enabled by
2139 // I'm disabling cleanup for now until I can think about it some
2142 // not really a 'collect all' -- still scans static data area, roots,
2144 return locked!(void, () {
2150 // default (safe) clenup
2151 return locked!(void, () {
2159 return locked!(void, () {
2160 assert (Invariant()); scope (exit) assert (Invariant());
2161 assert (gc.disabled > 0);
2168 return locked!(void, () {
2169 assert (Invariant()); scope (exit) assert (Invariant());
2176 return locked!(void, () {
2177 assert (Invariant()); scope (exit) assert (Invariant());
2185 return locked!(void, () {
2186 assert (Invariant()); scope (exit) assert (Invariant());
2191 uint gc_getAttr(void* p)
2195 return locked!(uint, () {
2196 assert (Invariant()); scope (exit) assert (Invariant());
2197 Pool* pool = findPool(p);
2200 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2201 return getAttr(pool, bit_i);
2205 uint gc_setAttr(void* p, uint attrs)
2209 return locked!(uint, () {
2210 assert (Invariant()); scope (exit) assert (Invariant());
2211 Pool* pool = findPool(p);
2214 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2215 uint old_attrs = getAttr(pool, bit_i);
2216 setAttr(pool, bit_i, attrs);
2221 uint gc_clrAttr(void* p, uint attrs)
2225 return locked!(uint, () {
2226 assert (Invariant()); scope (exit) assert (Invariant());
2227 Pool* pool = findPool(p);
2230 auto bit_i = cast(size_t)(p - pool.baseAddr) / 16;
2231 uint old_attrs = getAttr(pool, bit_i);
2232 clrAttr(pool, bit_i, attrs);
2237 void* gc_malloc(size_t size, uint attrs = 0,
2238 PointerMap ptrmap = PointerMap.init)
2242 return locked!(void*, () {
2243 assert (Invariant()); scope (exit) assert (Invariant());
2244 return malloc(size, attrs, ptrmap.bits.ptr);
2248 void* gc_calloc(size_t size, uint attrs = 0,
2249 PointerMap ptrmap = PointerMap.init)
2253 return locked!(void*, () {
2254 assert (Invariant()); scope (exit) assert (Invariant());
2255 return calloc(size, attrs, ptrmap.bits.ptr);
2259 void* gc_realloc(void* p, size_t size, uint attrs = 0,
2260 PointerMap ptrmap = PointerMap.init)
2262 return locked!(void*, () {
2263 assert (Invariant()); scope (exit) assert (Invariant());
2264 return realloc(p, size, attrs, ptrmap.bits.ptr);
2268 size_t gc_extend(void* p, size_t min_size, size_t max_size)
2270 return locked!(size_t, () {
2271 assert (Invariant()); scope (exit) assert (Invariant());
2272 return extend(p, min_size, max_size);
2276 size_t gc_reserve(size_t size)
2280 return locked!(size_t, () {
2281 assert (Invariant()); scope (exit) assert (Invariant());
2282 return reserve(size);
2286 void gc_free(void* p)
2290 return locked!(void, () {
2291 assert (Invariant()); scope (exit) assert (Invariant());
2296 void* gc_addrOf(void* p)
2300 return locked!(void*, () {
2301 assert (Invariant()); scope (exit) assert (Invariant());
2302 Pool* pool = findPool(p);
2305 return pool.findBase(p);
2309 size_t gc_sizeOf(void* p)
2313 return locked!(size_t, () {
2314 assert (Invariant()); scope (exit) assert (Invariant());
2319 BlkInfo gc_query(void* p)
2322 return BlkInfo.init;
2323 return locked!(BlkInfo, () {
2324 assert (Invariant()); scope (exit) assert (Invariant());
2329 // NOTE: This routine is experimental. The stats or function name may change
2330 // before it is made officially available.
2333 return locked!(GCStats, () {
2334 assert (Invariant()); scope (exit) assert (Invariant());
2339 void gc_addRoot(void* p)
2343 return locked!(void, () {
2344 assert (Invariant()); scope (exit) assert (Invariant());
2345 if (gc.roots.append(p) is null)
2346 onOutOfMemoryError();
2350 void gc_addRange(void* p, size_t size)
2352 if (p is null || size == 0)
2354 return locked!(void, () {
2355 assert (Invariant()); scope (exit) assert (Invariant());
2356 if (gc.ranges.append(Range(p, p + size)) is null)
2357 onOutOfMemoryError();
2361 void gc_removeRoot(void* p)
2365 return locked!(void, () {
2366 assert (Invariant()); scope (exit) assert (Invariant());
2367 bool r = gc.roots.remove(p);
2372 void gc_removeRange(void* p)
2376 return locked!(void, () {
2377 assert (Invariant()); scope (exit) assert (Invariant());
2378 bool r = gc.ranges.remove(Range(p, null));
2383 void* gc_weakpointerCreate(Object r)
2385 // weakpointers do their own locking
2386 return weakpointerCreate(r);
2389 void gc_weakpointerDestroy(void* wp)
2391 // weakpointers do their own locking
2392 weakpointerDestroy(wp);
2395 Object gc_weakpointerGet(void* wp)
2397 // weakpointers do their own locking
2398 return weakpointerGet(wp);
2402 // vim: set et sw=4 sts=4 :