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
27 // D Programming Language Garbage Collector implementation
29 /************** Debugging ***************************/
31 //debug = PRINTF; // turn on printf's
32 //debug = COLLECT_PRINTF; // turn on printf's
33 //debug = THREADINVARIANT; // check thread integrity
34 //debug = LOGGING; // log allocations / frees
35 //debug = MEMSTOMP; // stomp on memory
36 //debug = SENTINEL; // add underrun/overrrun protection
37 //debug = PTRCHECK; // more pointer checking
38 //debug = PTRCHECK2; // thorough but slow pointer checking
40 /*************** Configuration *********************/
42 version = STACKGROWSDOWN; // growing the stack means subtracting from the stack pointer
43 // (use for Intel X86 CPUs)
44 // else growing the stack means adding to the stack pointer
45 version = MULTI_THREADED; // produce multithreaded version
47 /***************************************************/
49 private import gcbits;
50 private import gcstats;
51 private import gcalloc;
53 private import cstdlib = tango.stdc.stdlib : calloc, free, malloc, realloc;
54 private import cstring = tango.stdc.string : memcpy, memmove, memset;
55 debug(THREADINVARIANT) private import tango.stdc.posix.pthread;
56 debug(PRINTF) private import tango.stdc.posix.pthread : pthread_self, pthread_t;
57 debug private import tango.stdc.stdio : printf;
61 // BUG: The following import will likely not work, since the gcc
62 // subdirectory is elsewhere. Instead, perhaps the functions
63 // could be declared directly or some other resolution could
65 private import gcc.builtins; // for __builtin_unwind_init
80 FINALIZE = 0b0000_0001,
81 NO_SCAN = 0b0000_0010,
82 NO_MOVE = 0b0000_0100,
83 ALL_BITS = 0b1111_1111
86 extern (C) void* rt_stackBottom();
87 extern (C) void* rt_stackTop();
89 extern (C) void rt_finalize( void* p, bool det = true );
91 alias void delegate( void*, void* ) scanFn;
93 extern (C) void rt_scanStaticData( scanFn scan );
95 version (MULTI_THREADED)
97 extern (C) bool thread_needLock();
98 extern (C) void thread_suspendAll();
99 extern (C) void thread_resumeAll();
101 extern (C) void thread_scanAll( scanFn fn, void* curStackTop = null );
104 extern (C) void onOutOfMemoryError();
108 OPFAIL = ~cast(size_t)0
116 /* ======================= Leak Detector =========================== */
131 printf(" p = %x, size = %d, parent = %x ", p, size, parent);
134 printf("%s(%u)", file, line);
154 void reserve(size_t nentries)
156 assert(dim <= allocdim);
157 if (allocdim - dim < nentries)
159 allocdim = (dim + nentries) * 2;
160 assert(dim + nentries <= allocdim);
163 data = cast(Log*)cstdlib.malloc(allocdim * Log.sizeof);
164 if (!data && allocdim)
165 onOutOfMemoryError();
170 newdata = cast(Log*)cstdlib.malloc(allocdim * Log.sizeof);
171 if (!newdata && allocdim)
172 onOutOfMemoryError();
173 cstring.memcpy(newdata, data, dim * Log.sizeof);
187 void remove(size_t i)
189 cstring.memmove(data + i, data + i + 1, (dim - i) * Log.sizeof);
196 for (size_t i = 0; i < dim; i++)
201 return OPFAIL; // not found
205 void copy(LogArray *from)
207 reserve(from.dim - dim);
208 assert(from.dim <= allocdim);
209 cstring.memcpy(data, from.data, from.dim * Log.sizeof);
216 /* ============================ GC =============================== */
219 class GCLock { } // just a dummy so we can get a global lock
222 const uint GCVERSION = 1; // increment every time we change interface
227 // For passing to debug code
231 uint gcversion = GCVERSION;
233 Gcx *gcx; // implementation
234 static ClassInfo gcLock; // global lock
239 gcLock = GCLock.classinfo;
240 gcx = cast(Gcx*)cstdlib.calloc(1, Gcx.sizeof);
242 onOutOfMemoryError();
244 setStackBottom(rt_stackBottom());
252 //debug(PRINTF) printf("Thread %x ", pthread_self());
253 //debug(PRINTF) printf("GC.Dtor()\n");
269 gcx.thread_Invariant();
279 if (!thread_needLock())
281 assert(gcx.disabled > 0);
284 else synchronized (gcLock)
286 assert(gcx.disabled > 0);
297 if (!thread_needLock())
301 else synchronized (gcLock)
311 uint getAttr(void* p)
320 Pool* pool = gcx.findPool(p);
325 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
327 oldb = gcx.getBits(pool, biti);
332 if (!thread_needLock())
336 else synchronized (gcLock)
346 uint setAttr(void* p, uint mask)
355 Pool* pool = gcx.findPool(p);
360 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
362 oldb = gcx.getBits(pool, biti);
363 gcx.setBits(pool, biti, mask);
368 if (!thread_needLock())
372 else synchronized (gcLock)
382 uint clrAttr(void* p, uint mask)
391 Pool* pool = gcx.findPool(p);
396 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
398 oldb = gcx.getBits(pool, biti);
399 gcx.clrBits(pool, biti, mask);
404 if (!thread_needLock())
408 else synchronized (gcLock)
418 void *malloc(size_t size, uint bits = 0)
425 if (!thread_needLock())
427 return mallocNoSync(size, bits);
429 else synchronized (gcLock)
431 return mallocNoSync(size, bits);
439 private void *mallocNoSync(size_t size, uint bits = 0)
446 //debug(PRINTF) printf("GC::malloc(size = %d, gcx = %p)\n", size, gcx);
448 //debug(PRINTF) printf("gcx.self = %x, pthread_self() = %x\n", gcx.self, pthread_self());
450 size += SENTINEL_EXTRA;
453 // Cache previous binsize lookup - Dave Fladebo.
454 static size_t lastsize = -1;
456 if (size == lastsize)
460 bin = gcx.findBin(size);
470 if (!gcx.allocPage(bin) && !gcx.disabled) // try to find a new page
472 if (!thread_needLock())
474 /* Then we haven't locked it yet. Be sure
475 * and lock for a collection, since a finalizer
476 * may start a new thread.
478 synchronized (gcLock)
480 gcx.fullcollectshell();
483 else if (!gcx.fullcollectshell()) // collect to find a new page
488 if (!gcx.bucket[bin] && !gcx.allocPage(bin))
491 gcx.newPool(1); // allocate new pool to find a new page
492 result = gcx.allocPage(bin);
494 onOutOfMemoryError();
499 // Return next item from free list
500 gcx.bucket[bin] = (cast(List*)p).next;
501 if( !(bits & BlkAttr.NO_SCAN) )
502 cstring.memset(p + size, 0, binsize[bin] - size);
503 //debug(PRINTF) printf("\tmalloc => %x\n", p);
504 debug (MEMSTOMP) cstring.memset(p, 0xF0, size);
508 p = gcx.bigAlloc(size);
510 onOutOfMemoryError();
512 size -= SENTINEL_EXTRA;
514 sentinel_init(p, size);
515 gcx.log_malloc(p, size);
519 Pool *pool = gcx.findPool(p);
522 gcx.setBits(pool, cast(size_t)(p - pool.baseAddr) / 16, bits);
531 void *calloc(size_t size, uint bits = 0)
538 if (!thread_needLock())
540 return callocNoSync(size, bits);
542 else synchronized (gcLock)
544 return callocNoSync(size, bits);
552 private void *callocNoSync(size_t size, uint bits = 0)
556 //debug(PRINTF) printf("calloc: %x len %d\n", p, len);
557 void *p = mallocNoSync(size, bits);
558 cstring.memset(p, 0, size);
566 void *realloc(void *p, size_t size, uint bits = 0)
568 if (!thread_needLock())
570 return reallocNoSync(p, size, bits);
572 else synchronized (gcLock)
574 return reallocNoSync(p, size, bits);
582 private void *reallocNoSync(void *p, size_t size, uint bits = 0)
592 p = mallocNoSync(size, bits);
598 //debug(PRINTF) printf("GC::realloc(p = %x, size = %u)\n", p, size);
601 sentinel_Invariant(p);
602 psize = *sentinel_size(p);
607 Pool *pool = gcx.findPool(p);
611 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
615 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
616 gcx.setBits(pool, biti, bits);
620 bits = gcx.getBits(pool, biti);
624 p2 = mallocNoSync(size, bits);
627 //debug(PRINTF) printf("\tcopying %d bytes\n",size);
628 cstring.memcpy(p2, p, size);
634 psize = gcx.findSize(p); // find allocated size
635 if (psize >= PAGESIZE && size >= PAGESIZE)
637 auto psz = psize / PAGESIZE;
638 auto newsz = (size + PAGESIZE - 1) / PAGESIZE;
642 auto pool = gcx.findPool(p);
643 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
647 synchronized (gcLock)
649 debug (MEMSTOMP) cstring.memset(p + size, 0xF2, psize - size);
650 pool.freePages(pagenum + newsz, psz - newsz);
654 else if (pagenum + newsz <= pool.npages)
656 // Attempt to expand in place
657 synchronized (gcLock)
659 for (size_t i = pagenum + psz; 1;)
661 if (i == pagenum + newsz)
663 debug (MEMSTOMP) cstring.memset(p + psize, 0xF0, size - psize);
664 cstring.memset(&pool.pagetable[pagenum + psz], B_PAGEPLUS, newsz - psz);
667 if (i == pool.ncommitted)
669 auto u = pool.extendPages(pagenum + newsz - pool.ncommitted);
675 if (pool.pagetable[i] != B_FREE)
682 if (psize < size || // if new size is bigger
683 psize > size * 2) // or less than half
687 Pool *pool = gcx.findPool(p);
691 auto biti = cast(size_t)(p - pool.baseAddr) / 16;
695 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
696 gcx.setBits(pool, biti, bits);
700 bits = gcx.getBits(pool, biti);
704 p2 = mallocNoSync(size, bits);
707 //debug(PRINTF) printf("\tcopying %d bytes\n",size);
708 cstring.memcpy(p2, p, size);
718 * Attempt to in-place enlarge the memory block pointed to by p by at least
719 * minbytes beyond its current capacity, up to a maximum of maxsize. This
720 * does not attempt to move the memory block (like realloc() does).
723 * 0 if could not extend p,
724 * total size of entire memory block if successful.
726 size_t extend(void* p, size_t minsize, size_t maxsize)
728 if (!thread_needLock())
730 return extendNoSync(p, minsize, maxsize);
732 else synchronized (gcLock)
734 return extendNoSync(p, minsize, maxsize);
742 private size_t extendNoSync(void* p, size_t minsize, size_t maxsize)
745 assert( minsize <= maxsize );
749 //debug(PRINTF) printf("GC::extend(p = %x, minsize = %u, maxsize = %u)\n", p, minsize, maxsize);
754 auto psize = gcx.findSize(p); // find allocated size
755 if (psize < PAGESIZE)
756 return 0; // cannot extend buckets
758 auto psz = psize / PAGESIZE;
759 auto minsz = (minsize + PAGESIZE - 1) / PAGESIZE;
760 auto maxsz = (maxsize + PAGESIZE - 1) / PAGESIZE;
762 auto pool = gcx.findPool(p);
763 auto pagenum = (p - pool.baseAddr) / PAGESIZE;
766 for (sz = 0; sz < maxsz; sz++)
768 auto i = pagenum + psz + sz;
769 if (i == pool.ncommitted)
771 if (pool.pagetable[i] != B_FREE)
780 else if (pagenum + psz + sz == pool.ncommitted)
782 auto u = pool.extendPages(minsz - sz);
789 debug (MEMSTOMP) cstring.memset(p + psize, 0xF0, (psz + sz) * PAGESIZE - psize);
790 cstring.memset(pool.pagetable + pagenum + psz, B_PAGEPLUS, sz);
793 return (psz + sz) * PAGESIZE;
800 size_t reserve(size_t size)
807 if (!thread_needLock())
809 return reserveNoSync(size);
811 else synchronized (gcLock)
813 return reserveNoSync(size);
821 private size_t reserveNoSync(size_t size)
826 return gcx.reserve(size);
840 if (!thread_needLock())
842 return freeNoSync(p);
844 else synchronized (gcLock)
846 return freeNoSync(p);
854 private void freeNoSync(void *p)
863 // Find which page it is in
864 pool = gcx.findPool(p);
865 if (!pool) // if not one of ours
867 sentinel_Invariant(p);
869 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
870 biti = cast(size_t)(p - pool.baseAddr) / 16;
871 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
873 bin = cast(Bins)pool.pagetable[pagenum];
874 if (bin == B_PAGE) // if large alloc
881 while (++n < pool.ncommitted && pool.pagetable[n] == B_PAGEPLUS)
883 debug (MEMSTOMP) cstring.memset(p, 0xF2, npages * PAGESIZE);
884 pool.freePages(pagenum, npages);
887 { // Add to free list
888 List *list = cast(List*)p;
890 debug (MEMSTOMP) cstring.memset(p, 0xF2, binsize[bin]);
892 list.next = gcx.bucket[bin];
893 gcx.bucket[bin] = list;
895 gcx.log_free(sentinel_add(p));
900 * Determine the base address of the block containing p. If p is not a gc
901 * allocated pointer, return null.
903 void* addrOf(void *p)
910 if (!thread_needLock())
912 return addrOfNoSync(p);
914 else synchronized (gcLock)
916 return addrOfNoSync(p);
924 void* addrOfNoSync(void *p)
931 return gcx.findBase(p);
936 * Determine the allocated size of pointer p. If p is an interior pointer
937 * or not a gc allocated pointer, return 0.
939 size_t sizeOf(void *p)
946 if (!thread_needLock())
948 return sizeOfNoSync(p);
950 else synchronized (gcLock)
952 return sizeOfNoSync(p);
960 private size_t sizeOfNoSync(void *p)
967 size_t size = gcx.findSize(p);
969 // Check for interior pointer
971 // 1) size is a power of 2 for less than PAGESIZE values
972 // 2) base of memory pool is aligned on PAGESIZE boundary
973 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
975 return size ? size - SENTINEL_EXTRA : 0;
979 if (p == gcx.p_cache)
980 return gcx.size_cache;
982 size_t size = gcx.findSize(p);
984 // Check for interior pointer
986 // 1) size is a power of 2 for less than PAGESIZE values
987 // 2) base of memory pool is aligned on PAGESIZE boundary
988 if (cast(size_t)p & (size - 1) & (PAGESIZE - 1))
993 gcx.size_cache = size;
1002 * Determine the base address of the block containing p. If p is not a gc
1003 * allocated pointer, return null.
1005 BlkInfo query(void *p)
1013 if (!thread_needLock())
1015 return queryNoSync(p);
1017 else synchronized (gcLock)
1019 return queryNoSync(p);
1027 BlkInfo queryNoSync(void *p)
1031 return gcx.getInfo(p);
1036 * Verify that pointer p:
1037 * 1) belongs to this memory pool
1038 * 2) points to the start of an allocated piece of memory
1039 * 3) is not on a free list
1048 if (!thread_needLock())
1052 else synchronized (gcLock)
1062 private void checkNoSync(void *p)
1066 sentinel_Invariant(p);
1074 p = sentinel_sub(p);
1075 pool = gcx.findPool(p);
1077 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1078 bin = cast(Bins)pool.pagetable[pagenum];
1079 assert(bin <= B_PAGE);
1080 size = binsize[bin];
1081 assert((cast(size_t)p & (size - 1)) == 0);
1087 // Check that p is not on a free list
1090 for (list = gcx.bucket[bin]; list; list = list.next)
1092 assert(cast(void*)list != p);
1103 private void setStackBottom(void *p)
1105 version (STACKGROWSDOWN)
1107 //p = (void *)((uint *)p + 4);
1108 if (p > gcx.stackBottom)
1110 //debug(PRINTF) printf("setStackBottom(%x)\n", p);
1111 gcx.stackBottom = p;
1116 //p = (void *)((uint *)p - 4);
1117 if (p < gcx.stackBottom)
1119 //debug(PRINTF) printf("setStackBottom(%x)\n", p);
1120 gcx.stackBottom = cast(char*)p;
1127 * add p to list of roots
1129 void addRoot(void *p)
1136 if (!thread_needLock())
1140 else synchronized (gcLock)
1148 * remove p from list of roots
1150 void removeRoot(void *p)
1157 if (!thread_needLock())
1161 else synchronized (gcLock)
1169 * add range to scan for roots
1171 void addRange(void *p, size_t sz)
1178 //debug(PRINTF) printf("+GC.addRange(pbot = x%x, ptop = x%x)\n", pbot, ptop);
1179 if (!thread_needLock())
1181 gcx.addRange(p, p + sz);
1183 else synchronized (gcLock)
1185 gcx.addRange(p, p + sz);
1187 //debug(PRINTF) printf("-GC.addRange()\n");
1194 void removeRange(void *p)
1201 if (!thread_needLock())
1205 else synchronized (gcLock)
1213 * do full garbage collection
1217 debug(PRINTF) printf("GC.fullCollect()\n");
1219 if (!thread_needLock())
1221 gcx.fullcollectshell();
1223 else synchronized (gcLock)
1225 gcx.fullcollectshell();
1233 debug(PRINTF) printf("poolsize = %x, usedsize = %x, freelistsize = %x\n",
1234 stats.poolsize, stats.usedsize, stats.freelistsize);
1242 * do full garbage collection ignoring roots
1244 void fullCollectNoStack()
1246 if (!thread_needLock())
1249 gcx.fullcollectshell();
1252 else synchronized (gcLock)
1255 gcx.fullcollectshell();
1262 * minimize free space usage
1266 if (!thread_needLock())
1270 else synchronized (gcLock)
1278 * Retrieve statistics about garbage collection.
1279 * Useful for debugging and tuning.
1281 void getStats(out GCStats stats)
1283 if (!thread_needLock())
1285 getStatsNoSync(stats);
1287 else synchronized (gcLock)
1289 getStatsNoSync(stats);
1297 private void getStatsNoSync(out GCStats stats)
1306 //debug(PRINTF) printf("getStats()\n");
1307 cstring.memset(&stats, 0, GCStats.sizeof);
1309 for (n = 0; n < gcx.npools; n++)
1310 { Pool *pool = gcx.pooltable[n];
1312 psize += pool.ncommitted * PAGESIZE;
1313 for (size_t j = 0; j < pool.ncommitted; j++)
1315 Bins bin = cast(Bins)pool.pagetable[j];
1318 else if (bin == B_PAGE)
1320 else if (bin < B_PAGE)
1325 for (n = 0; n < B_PAGE; n++)
1327 //debug(PRINTF) printf("bin %d\n", n);
1328 for (List *list = gcx.bucket[n]; list; list = list.next)
1330 //debug(PRINTF) printf("\tlist %x\n", list);
1331 flsize += binsize[n];
1335 usize = bsize - flsize;
1337 stats.poolsize = psize;
1338 stats.usedsize = bsize - flsize;
1339 stats.freelistsize = flsize;
1344 /* ============================ Gcx =============================== */
1348 COMMITSIZE = (4096*16),
1349 POOLSIZE = (4096*256),
1363 B_PAGE, // start of large alloc
1364 B_PAGEPLUS, // continuation of large alloc
1365 B_FREE, // free page
1366 B_UNCOMMITTED, // memory not committed for this page
1387 const uint binsize[B_MAX] = [ 16,32,64,128,256,512,1024,2048,4096 ];
1388 const uint notbinsize[B_MAX] = [ ~(16u-1),~(32u-1),~(64u-1),~(128u-1),~(256u-1),
1389 ~(512u-1),~(1024u-1),~(2048u-1),~(4096u-1) ];
1391 /* ============================ Gcx =============================== */
1396 debug (THREADINVARIANT)
1399 void thread_Invariant()
1401 if (self != pthread_self())
1402 printf("thread_Invariant(): gcx = %x, self = %x, pthread_self() = %x\n", this, self, pthread_self());
1403 assert(self == pthread_self());
1408 void thread_Invariant() { }
1422 uint noStack; // !=0 means don't scan stack
1423 uint log; // turn on logging
1427 int disabled; // turn off collections if >0
1429 byte *minAddr; // min(baseAddr)
1430 byte *maxAddr; // max(topAddr)
1435 List *bucket[B_MAX]; // free list for each size
1441 (cast(byte*)this)[0 .. Gcx.sizeof] = 0;
1442 stackBottom = cast(char*)&dummy;
1444 debug (THREADINVARIANT)
1445 self = pthread_self();
1446 //printf("gcx = %p, self = %x\n", this, self);
1455 for (size_t i = 0; i < npools; i++)
1456 { Pool *pool = pooltable[i];
1462 cstdlib.free(pooltable);
1465 cstdlib.free(roots);
1468 cstdlib.free(ranges);
1472 void Invariant() { }
1479 //printf("Gcx.invariant(): this = %p\n", this);
1482 // Assure we're called on the right thread
1483 debug (THREADINVARIANT) assert(self == pthread_self());
1485 for (i = 0; i < npools; i++)
1486 { Pool *pool = pooltable[i];
1491 assert(minAddr == pool.baseAddr);
1495 assert(pool.opCmp(pooltable[i + 1]) < 0);
1497 else if (i + 1 == npools)
1499 assert(maxAddr == pool.topAddr);
1505 assert(rootdim != 0);
1506 assert(nroots <= rootdim);
1511 assert(rangedim != 0);
1512 assert(nranges <= rangedim);
1514 for (i = 0; i < nranges; i++)
1516 assert(ranges[i].pbot);
1517 assert(ranges[i].ptop);
1518 assert(ranges[i].pbot <= ranges[i].ptop);
1522 for (i = 0; i < B_PAGE; i++)
1524 for (List *list = bucket[i]; list; list = list.next)
1535 void addRoot(void *p)
1537 if (nroots == rootdim)
1539 size_t newdim = rootdim * 2 + 16;
1542 newroots = cast(void**)cstdlib.malloc(newdim * newroots[0].sizeof);
1544 onOutOfMemoryError();
1546 { cstring.memcpy(newroots, roots, nroots * newroots[0].sizeof);
1547 cstdlib.free(roots);
1560 void removeRoot(void *p)
1562 for (size_t i = nroots; i--;)
1567 cstring.memmove(roots + i, roots + i + 1, (nroots - i) * roots[0].sizeof);
1578 void addRange(void *pbot, void *ptop)
1580 debug(PRINTF) printf("Thread %x ", pthread_self());
1581 debug(PRINTF) printf("%x.Gcx::addRange(%x, %x), nranges = %d\n", this, pbot, ptop, nranges);
1582 if (nranges == rangedim)
1584 size_t newdim = rangedim * 2 + 16;
1587 newranges = cast(Range*)cstdlib.malloc(newdim * newranges[0].sizeof);
1589 onOutOfMemoryError();
1591 { cstring.memcpy(newranges, ranges, nranges * newranges[0].sizeof);
1592 cstdlib.free(ranges);
1597 ranges[nranges].pbot = pbot;
1598 ranges[nranges].ptop = ptop;
1606 void removeRange(void *pbot)
1608 debug(PRINTF) printf("Thread %x ", pthread_self());
1609 debug(PRINTF) printf("%x.Gcx.removeRange(%x), nranges = %d\n", this, pbot, nranges);
1610 for (size_t i = nranges; i--;)
1612 if (ranges[i].pbot == pbot)
1615 cstring.memmove(ranges + i, ranges + i + 1, (nranges - i) * ranges[0].sizeof);
1619 debug(PRINTF) printf("Wrong thread\n");
1621 // This is a fatal error, but ignore it.
1622 // The problem is that we can get a Close() call on a thread
1623 // other than the one the range was allocated on.
1629 * Find Pool that pointer is in.
1630 * Return null if not in a Pool.
1631 * Assume pooltable[] is sorted.
1633 Pool *findPool(void *p)
1635 if (p >= minAddr && p < maxAddr)
1639 return pooltable[0];
1642 for (size_t i = 0; i < npools; i++)
1645 pool = pooltable[i];
1646 if (p < pool.topAddr)
1647 { if (pool.baseAddr <= p)
1658 * Find base address of block containing pointer p.
1659 * Returns null if not a gc'd pointer
1661 void* findBase(void *p)
1668 size_t offset = cast(size_t)(p - pool.baseAddr);
1669 size_t pn = offset / PAGESIZE;
1670 Bins bin = cast(Bins)pool.pagetable[pn];
1672 // Adjust bit to be at start of allocated memory block
1675 return pool.baseAddr + (offset & notbinsize[bin]);
1677 else if (bin == B_PAGEPLUS)
1680 { --pn, offset -= PAGESIZE;
1681 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
1683 return pool.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
1687 // we are in a B_FREE or B_UNCOMMITTED page
1696 * Find size of pointer p.
1697 * Returns 0 if not a gc'd pointer
1699 size_t findSize(void *p)
1710 pagenum = cast(size_t)(p - pool.baseAddr) / PAGESIZE;
1711 bin = cast(Bins)pool.pagetable[pagenum];
1712 size = binsize[bin];
1714 { size_t npages = pool.ncommitted;
1718 pt = &pool.pagetable[0];
1719 for (i = pagenum + 1; i < npages; i++)
1721 if (pt[i] != B_PAGEPLUS)
1724 size = (i - pagenum) * PAGESIZE;
1734 BlkInfo getInfo(void* p)
1742 size_t offset = cast(size_t)(p - pool.baseAddr);
1743 size_t pn = offset / PAGESIZE;
1744 Bins bin = cast(Bins)pool.pagetable[pn];
1746 ////////////////////////////////////////////////////////////////////
1748 ////////////////////////////////////////////////////////////////////
1752 info.base = pool.baseAddr + (offset & notbinsize[bin]);
1754 else if (bin == B_PAGEPLUS)
1757 { --pn, offset -= PAGESIZE;
1758 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
1760 info.base = pool.baseAddr + (offset & (offset.max ^ (PAGESIZE-1)));
1762 // fix bin for use by size calc below
1763 bin = cast(Bins)pool.pagetable[pn];
1766 ////////////////////////////////////////////////////////////////////
1768 ////////////////////////////////////////////////////////////////////
1770 info.size = binsize[bin];
1772 { size_t npages = pool.ncommitted;
1776 pt = &pool.pagetable[0];
1777 for (i = pn + 1; i < npages; i++)
1779 if (pt[i] != B_PAGEPLUS)
1782 info.size = (i - pn) * PAGESIZE;
1785 ////////////////////////////////////////////////////////////////////
1787 ////////////////////////////////////////////////////////////////////
1789 info.attr = getBits(pool, cast(size_t)(offset / 16));
1796 * Compute bin for size.
1798 static Bins findBin(size_t size)
1807 else if (size <= 32)
1842 * Allocate a new pool of at least size bytes.
1843 * Sort it into pooltable[].
1844 * Mark all memory in the pool as B_FREE.
1845 * Return the actual number of bytes reserved or 0 on error.
1847 size_t reserve(size_t size)
1849 size_t npages = (size + PAGESIZE - 1) / PAGESIZE;
1850 Pool* pool = newPool(npages);
1852 if (!pool || pool.extendPages(npages) == OPFAIL)
1854 return pool.ncommitted * PAGESIZE;
1859 * Minimizes physical memory usage by returning free pools to the OS.
1868 for (n = 0; n < npools; n++)
1870 pool = pooltable[n];
1871 ncommitted = pool.ncommitted;
1872 for (pn = 0; pn < ncommitted; pn++)
1874 if (cast(Bins)pool.pagetable[pn] != B_FREE)
1877 if (pn < ncommitted)
1884 cstring.memmove(pooltable + n,
1886 (--npools - n) * (Pool*).sizeof);
1887 minAddr = pooltable[0].baseAddr;
1888 maxAddr = pooltable[npools - 1].topAddr;
1894 * Allocate a chunk of memory that is larger than a page.
1895 * Return null if out of memory.
1897 void *bigAlloc(size_t size)
1907 npages = (size + PAGESIZE - 1) / PAGESIZE;
1911 // This code could use some refinement when repeatedly
1912 // allocating very large arrays.
1914 for (n = 0; n < npools; n++)
1916 pool = pooltable[n];
1917 pn = pool.allocPages(npages);
1931 freedpages = fullcollectshell();
1932 if (freedpages >= npools * ((POOLSIZE / PAGESIZE) / 4))
1936 // Release empty pools to prevent bloat
1938 // Allocate new pool
1939 pool = newPool(npages);
1944 pn = pool.allocPages(npages);
1945 assert(pn != OPFAIL);
1948 // Release empty pools to prevent bloat
1950 // Allocate new pool
1951 pool = newPool(npages);
1954 pn = pool.allocPages(npages);
1955 assert(pn != OPFAIL);
1965 pool.pagetable[pn] = B_PAGE;
1967 cstring.memset(&pool.pagetable[pn + 1], B_PAGEPLUS, npages - 1);
1968 p = pool.baseAddr + pn * PAGESIZE;
1969 cstring.memset(cast(char *)p + size, 0, npages * PAGESIZE - size);
1970 debug (MEMSTOMP) cstring.memset(p, 0xF1, size);
1971 //debug(PRINTF) printf("\tp = %x\n", p);
1975 return null; // let mallocNoSync handle the error
1980 * Allocate a new pool with at least npages in it.
1981 * Sort it into pooltable[].
1982 * Return null if failed.
1984 Pool *newPool(size_t npages)
1987 Pool** newpooltable;
1991 //debug(PRINTF) printf("************Gcx::newPool(npages = %d)****************\n", npages);
1993 // Round up to COMMITSIZE pages
1994 npages = (npages + (COMMITSIZE/PAGESIZE) - 1) & ~(COMMITSIZE/PAGESIZE - 1);
1996 // Minimum of POOLSIZE
1997 if (npages < POOLSIZE/PAGESIZE)
1998 npages = POOLSIZE/PAGESIZE;
1999 else if (npages > POOLSIZE/PAGESIZE)
2000 { // Give us 150% of requested size, so there's room to extend
2001 auto n = npages + (npages >> 1);
2002 if (n < size_t.max/PAGESIZE)
2006 // Allocate successively larger pools up to 8 megs
2012 n = 8; // cap pool size at 8 megs
2013 n *= (POOLSIZE / PAGESIZE);
2018 pool = cast(Pool *)cstdlib.calloc(1, Pool.sizeof);
2021 pool.initialize(npages);
2025 newnpools = npools + 1;
2026 newpooltable = cast(Pool **)cstdlib.realloc(pooltable, newnpools * (Pool *).sizeof);
2030 // Sort pool into newpooltable[]
2031 for (i = 0; i < npools; i++)
2033 if (pool.opCmp(newpooltable[i]) < 0)
2036 cstring.memmove(newpooltable + i + 1, newpooltable + i, (npools - i) * (Pool *).sizeof);
2037 newpooltable[i] = pool;
2039 pooltable = newpooltable;
2042 minAddr = pooltable[0].baseAddr;
2043 maxAddr = pooltable[npools - 1].topAddr;
2055 * Allocate a page of bin's.
2059 int allocPage(Bins bin)
2067 //debug(PRINTF) printf("Gcx::allocPage(bin = %d)\n", bin);
2068 for (n = 0; n < npools; n++)
2070 pool = pooltable[n];
2071 pn = pool.allocPages(1);
2078 pool.pagetable[pn] = cast(ubyte)bin;
2080 // Convert page to free list
2081 size_t size = binsize[bin];
2082 List **b = &bucket[bin];
2084 p = pool.baseAddr + pn * PAGESIZE;
2085 ptop = p + PAGESIZE;
2086 for (; p < ptop; p += size)
2088 (cast(List *)p).next = *b;
2096 * Search a range of memory values and mark any pointers into the GC pool.
2098 void mark(void *pbot, void *ptop)
2100 void **p1 = cast(void **)pbot;
2101 void **p2 = cast(void **)ptop;
2105 //printf("marking range: %p -> %p\n", pbot, ptop);
2106 for (; p1 < p2; p1++)
2109 byte *p = cast(byte *)(*p1);
2111 //if (log) debug(PRINTF) printf("\tmark %x\n", p);
2112 if (p >= minAddr && p < maxAddr)
2114 if ((cast(size_t)p & ~(PAGESIZE-1)) == pcache)
2120 size_t offset = cast(size_t)(p - pool.baseAddr);
2122 size_t pn = offset / PAGESIZE;
2123 Bins bin = cast(Bins)pool.pagetable[pn];
2125 //debug(PRINTF) printf("\t\tfound pool %x, base=%x, pn = %d, bin = %d, biti = x%x\n", pool, pool.baseAddr, pn, bin, biti);
2127 // Adjust bit to be at start of allocated memory block
2130 biti = (offset & notbinsize[bin]) >> 4;
2131 //debug(PRINTF) printf("\t\tbiti = x%x\n", biti);
2133 else if (bin == B_PAGEPLUS)
2137 } while (cast(Bins)pool.pagetable[pn] == B_PAGEPLUS);
2138 biti = pn * (PAGESIZE / 16);
2142 // Don't mark bits in B_FREE or B_UNCOMMITTED pages
2146 if (bin >= B_PAGE) // Cache B_PAGE and B_PAGEPLUS lookups
2147 pcache = cast(size_t)p & ~(PAGESIZE-1);
2149 //debug(PRINTF) printf("\t\tmark(x%x) = %d\n", biti, pool.mark.test(biti));
2150 if (!pool.mark.test(biti))
2152 //if (log) debug(PRINTF) printf("\t\tmarking %x\n", p);
2153 pool.mark.set(biti);
2154 if (!pool.noscan.test(biti))
2156 pool.scan.set(biti);
2159 log_parent(sentinel_add(pool.baseAddr + biti * 16), sentinel_add(pbot));
2164 anychanges |= changes;
2169 * Return number of full pages free'd.
2171 size_t fullcollectshell()
2173 // The purpose of the 'shell' is to ensure all the registers
2174 // get put on the stack so they'll be scanned
2179 __builtin_unwind_init();
2186 uint eax,ecx,edx,ebx,ebp,esi,edi;
2199 else version (X86_64)
2201 ulong rax,rbx,rcx,rdx,rbp,rsi,rdi,rsp,r8,r9,r10,r11,r12,r13,r14,r15;
2204 movq rax[RBP], RAX ;
2205 movq rbx[RBP], RBX ;
2206 movq rcx[RBP], RCX ;
2207 movq rdx[RBP], RDX ;
2208 movq rbp[RBP], RBP ;
2209 movq rsi[RBP], RSI ;
2210 movq rdi[RBP], RDI ;
2211 movq rsp[RBP], RSP ;
2214 movq r10[RBP], R10 ;
2215 movq r11[RBP], R11 ;
2216 movq r12[RBP], R12 ;
2217 movq r13[RBP], R13 ;
2218 movq r14[RBP], R14 ;
2219 movq r15[RBP], R15 ;
2224 static assert( false, "Architecture not supported." );
2235 result = fullcollect(sp);
2258 size_t fullcollect(void *stackTop)
2263 debug(COLLECT_PRINTF) printf("Gcx.fullcollect()\n");
2265 thread_suspendAll();
2271 for (n = 0; n < npools; n++)
2273 pool = pooltable[n];
2276 pool.freebits.zero();
2279 // Mark each free entry, so it doesn't get scanned
2280 for (n = 0; n < B_PAGE; n++)
2282 for (List *list = bucket[n]; list; list = list.next)
2284 pool = findPool(list);
2286 pool.freebits.set(cast(size_t)(cast(byte*)list - pool.baseAddr) / 16);
2290 for (n = 0; n < npools; n++)
2292 pool = pooltable[n];
2293 pool.mark.copy(&pool.freebits);
2296 rt_scanStaticData( &mark );
2298 version (MULTI_THREADED)
2302 // Scan stacks and registers for each paused thread
2303 thread_scanAll( &mark, stackTop );
2310 // Scan stack for main thread
2311 debug(PRINTF) printf(" scan stack bot = %x, top = %x\n", stackTop, stackBottom);
2312 version (STACKGROWSDOWN)
2313 mark(stackTop, stackBottom);
2315 mark(stackBottom, stackTop);
2320 debug(COLLECT_PRINTF) printf("scan roots[]\n");
2321 mark(roots, roots + nroots);
2324 debug(COLLECT_PRINTF) printf("scan ranges[]\n");
2326 for (n = 0; n < nranges; n++)
2328 debug(COLLECT_PRINTF) printf("\t%x .. %x\n", ranges[n].pbot, ranges[n].ptop);
2329 mark(ranges[n].pbot, ranges[n].ptop);
2333 debug(COLLECT_PRINTF) printf("\tscan heap\n");
2337 for (n = 0; n < npools; n++)
2343 pool = pooltable[n];
2345 bbase = pool.scan.base();
2346 btop = bbase + pool.scan.nwords;
2347 for (b = bbase; b < btop;)
2361 o = pool.baseAddr + (b - bbase) * 32 * 16;
2362 if (!(bitm & 0xFFFF))
2367 for (; bitm; o += 16, bitm >>= 1)
2372 pn = cast(size_t)(o - pool.baseAddr) / PAGESIZE;
2373 bin = cast(Bins)pool.pagetable[pn];
2376 mark(o, o + binsize[bin]);
2378 else if (bin == B_PAGE || bin == B_PAGEPLUS)
2380 if (bin == B_PAGEPLUS)
2382 while (pool.pagetable[pn - 1] != B_PAGE)
2386 while (pn + u < pool.ncommitted && pool.pagetable[pn + u] == B_PAGEPLUS)
2388 mark(o, o + u * PAGESIZE);
2397 // Free up everything not marked
2398 debug(COLLECT_PRINTF) printf("\tfree'ing\n");
2399 size_t freedpages = 0;
2401 for (n = 0; n < npools; n++)
2406 pool = pooltable[n];
2407 bbase = pool.mark.base();
2408 ncommitted = pool.ncommitted;
2409 for (pn = 0; pn < ncommitted; pn++, bbase += PAGESIZE / (32 * 16))
2411 Bins bin = cast(Bins)pool.pagetable[pn];
2418 auto size = binsize[bin];
2420 p = pool.baseAddr + pn * PAGESIZE;
2421 ptop = p + PAGESIZE;
2422 biti = pn * (PAGESIZE/16);
2423 bitstride = size / 16;
2425 version(none) // BUG: doesn't work because freebits() must also be cleared
2427 // If free'd entire page
2428 if (bbase[0] == 0 && bbase[1] == 0 && bbase[2] == 0 && bbase[3] == 0 &&
2429 bbase[4] == 0 && bbase[5] == 0 && bbase[6] == 0 && bbase[7] == 0)
2431 for (; p < ptop; p += size, biti += bitstride)
2433 if (pool.finals.nbits && pool.finals.testClear(biti))
2434 rt_finalize(cast(List *)sentinel_add(p), false/*noStack > 0*/);
2435 gcx.clrBits(pool, biti, BlkAttr.ALL_BITS);
2437 List *list = cast(List *)p;
2438 //debug(PRINTF) printf("\tcollecting %x\n", list);
2439 log_free(sentinel_add(list));
2441 debug (MEMSTOMP) cstring.memset(p, 0xF3, size);
2443 pool.pagetable[pn] = B_FREE;
2445 //debug(PRINTF) printf("freeing entire page %d\n", pn);
2449 for (; p < ptop; p += size, biti += bitstride)
2451 if (!pool.mark.test(biti))
2453 sentinel_Invariant(sentinel_add(p));
2455 pool.freebits.set(biti);
2456 if (pool.finals.nbits && pool.finals.testClear(biti))
2457 rt_finalize(cast(List *)sentinel_add(p), false/*noStack > 0*/);
2458 clrBits(pool, biti, BlkAttr.ALL_BITS);
2460 List *list = cast(List *)p;
2461 debug(PRINTF) printf("\tcollecting %x\n", list);
2462 log_free(sentinel_add(list));
2464 debug (MEMSTOMP) cstring.memset(p, 0xF3, size);
2470 else if (bin == B_PAGE)
2471 { size_t biti = pn * (PAGESIZE / 16);
2473 if (!pool.mark.test(biti))
2474 { byte *p = pool.baseAddr + pn * PAGESIZE;
2476 sentinel_Invariant(sentinel_add(p));
2477 if (pool.finals.nbits && pool.finals.testClear(biti))
2478 rt_finalize(sentinel_add(p), false/*noStack > 0*/);
2479 clrBits(pool, biti, BlkAttr.ALL_BITS);
2481 debug(COLLECT_PRINTF) printf("\tcollecting big %x\n", p);
2482 log_free(sentinel_add(p));
2483 pool.pagetable[pn] = B_FREE;
2485 debug (MEMSTOMP) cstring.memset(p, 0xF3, PAGESIZE);
2486 while (pn + 1 < ncommitted && pool.pagetable[pn + 1] == B_PAGEPLUS)
2489 pool.pagetable[pn] = B_FREE;
2494 cstring.memset(p, 0xF3, PAGESIZE);
2505 // Free complete pages, rebuild free list
2506 debug(COLLECT_PRINTF) printf("\tfree complete pages\n");
2507 size_t recoveredpages = 0;
2508 for (n = 0; n < npools; n++)
2512 pool = pooltable[n];
2513 ncommitted = pool.ncommitted;
2514 for (pn = 0; pn < ncommitted; pn++)
2516 Bins bin = cast(Bins)pool.pagetable[pn];
2522 size_t size = binsize[bin];
2523 size_t bitstride = size / 16;
2524 size_t bitbase = pn * (PAGESIZE / 16);
2525 size_t bittop = bitbase + (PAGESIZE / 16);
2529 for (biti = bitbase; biti < bittop; biti += bitstride)
2530 { if (!pool.freebits.test(biti))
2533 pool.pagetable[pn] = B_FREE;
2538 p = pool.baseAddr + pn * PAGESIZE;
2539 for (u = 0; u < PAGESIZE; u += size)
2540 { biti = bitbase + u / 16;
2541 if (pool.freebits.test(biti))
2544 list = cast(List *)(p + u);
2545 if (list.next != bucket[bin]) // avoid unnecessary writes
2546 list.next = bucket[bin];
2554 debug(COLLECT_PRINTF) printf("recovered pages = %d\n", recoveredpages);
2555 debug(COLLECT_PRINTF) printf("\tfree'd %u bytes, %u pages from %u pools\n", freed, freedpages, npools);
2557 return freedpages + recoveredpages;
2564 uint getBits(Pool* pool, size_t biti)
2573 if (pool.finals.nbits &&
2574 pool.finals.test(biti))
2575 bits |= BlkAttr.FINALIZE;
2576 if (pool.noscan.test(biti))
2577 bits |= BlkAttr.NO_SCAN;
2578 // if (pool.nomove.nbits &&
2579 // pool.nomove.test(biti))
2580 // bits |= BlkAttr.NO_MOVE;
2588 void setBits(Pool* pool, size_t biti, uint mask)
2595 if (mask & BlkAttr.FINALIZE)
2597 if (!pool.finals.nbits)
2598 pool.finals.alloc(pool.mark.nbits);
2599 pool.finals.set(biti);
2601 if (mask & BlkAttr.NO_SCAN)
2603 pool.noscan.set(biti);
2605 // if (mask & BlkAttr.NO_MOVE)
2607 // if (!pool.nomove.nbits)
2608 // pool.nomove.alloc(pool.mark.nbits);
2609 // pool.nomove.set(biti);
2617 void clrBits(Pool* pool, size_t biti, uint mask)
2624 if (mask & BlkAttr.FINALIZE && pool.finals.nbits)
2625 pool.finals.clear(biti);
2626 if (mask & BlkAttr.NO_SCAN)
2627 pool.noscan.clear(biti);
2628 // if (mask & BlkAttr.NO_MOVE && pool.nomove.nbits)
2629 // pool.nomove.clear(biti);
2633 /***** Leak Detector ******/
2644 //debug(PRINTF) printf("+log_init()\n");
2645 current.reserve(1000);
2647 //debug(PRINTF) printf("-log_init()\n");
2651 void log_malloc(void *p, size_t size)
2653 //debug(PRINTF) printf("+log_malloc(p = %x, size = %d)\n", p, size);
2666 //debug(PRINTF) printf("-log_malloc()\n");
2670 void log_free(void *p)
2672 //debug(PRINTF) printf("+log_free(%x)\n", p);
2675 i = current.find(p);
2678 debug(PRINTF) printf("free'ing unallocated memory %x\n", p);
2682 //debug(PRINTF) printf("-log_free()\n");
2688 //debug(PRINTF) printf("+log_collect()\n");
2689 // Print everything in current that is not in prev
2691 debug(PRINTF) printf("New pointers this cycle: --------------------------------\n");
2693 for (size_t i = 0; i < current.dim; i++)
2697 j = prev.find(current.data[i].p);
2699 current.data[i].print();
2704 debug(PRINTF) printf("All roots this cycle: --------------------------------\n");
2705 for (size_t i = 0; i < current.dim; i++)
2710 p = current.data[i].p;
2711 if (!findPool(current.data[i].parent))
2713 j = prev.find(current.data[i].p);
2715 debug(PRINTF) printf("N");
2717 debug(PRINTF) printf(" ");;
2718 current.data[i].print();
2722 debug(PRINTF) printf("Used = %d-------------------------------------------------\n", used);
2723 prev.copy(¤t);
2725 debug(PRINTF) printf("-log_collect()\n");
2729 void log_parent(void *p, void *parent)
2731 //debug(PRINTF) printf("+log_parent()\n");
2734 i = current.find(p);
2737 debug(PRINTF) printf("parent'ing unallocated memory %x, parent = %x\n", p, parent);
2741 size_t offset = cast(size_t)(p - pool.baseAddr);
2743 size_t pn = offset / PAGESIZE;
2744 Bins bin = cast(Bins)pool.pagetable[pn];
2745 biti = (offset & notbinsize[bin]);
2746 debug(PRINTF) printf("\tbin = %d, offset = x%x, biti = x%x\n", bin, offset, biti);
2750 current.data[i].parent = parent;
2752 //debug(PRINTF) printf("-log_parent()\n");
2759 void log_malloc(void *p, size_t size) { }
2760 void log_free(void *p) { }
2761 void log_collect() { }
2762 void log_parent(void *p, void *parent) { }
2767 /* ============================ Pool =============================== */
2774 GCBits mark; // entries already scanned, or should not be scanned
2775 GCBits scan; // entries that need to be scanned
2776 GCBits freebits; // entries that are on the free list
2777 GCBits finals; // entries that need finalizer run on them
2778 GCBits noscan; // entries that should not be scanned
2781 size_t ncommitted; // ncommitted <= npages
2785 void initialize(size_t npages)
2789 //debug(PRINTF) printf("Pool::Pool(%u)\n", npages);
2790 poolsize = npages * PAGESIZE;
2791 assert(poolsize >= POOLSIZE);
2792 baseAddr = cast(byte *)os_mem_map(poolsize);
2794 // Some of the code depends on page alignment of memory pools
2795 assert((cast(size_t)baseAddr & (PAGESIZE - 1)) == 0);
2799 //debug(PRINTF) printf("GC fail: poolsize = x%x, errno = %d\n", poolsize, errno);
2800 //debug(PRINTF) printf("message = '%s'\n", sys_errlist[errno]);
2806 topAddr = baseAddr + poolsize;
2808 mark.alloc(cast(size_t)poolsize / 16);
2809 scan.alloc(cast(size_t)poolsize / 16);
2810 freebits.alloc(cast(size_t)poolsize / 16);
2811 noscan.alloc(cast(size_t)poolsize / 16);
2813 pagetable = cast(ubyte*)cstdlib.malloc(npages);
2815 onOutOfMemoryError();
2816 cstring.memset(pagetable, B_UNCOMMITTED, npages);
2818 this.npages = npages;
2831 result = os_mem_decommit(baseAddr, 0, ncommitted * PAGESIZE);
2832 assert(result == 0);
2838 result = os_mem_unmap(baseAddr, npages * PAGESIZE);
2839 assert(result == 0);
2847 cstdlib.free(pagetable);
2857 void Invariant() { }
2864 //freebits.Invariant();
2865 //finals.Invariant();
2866 //noscan.Invariant();
2870 //if (baseAddr + npages * PAGESIZE != topAddr)
2871 //printf("baseAddr = %p, npages = %d, topAddr = %p\n", baseAddr, npages, topAddr);
2872 assert(baseAddr + npages * PAGESIZE == topAddr);
2873 assert(ncommitted <= npages);
2876 for (size_t i = 0; i < npages; i++)
2877 { Bins bin = cast(Bins)pagetable[i];
2879 assert(bin < B_MAX);
2885 * Allocate n pages from Pool.
2886 * Returns OPFAIL on failure.
2888 size_t allocPages(size_t n)
2893 //debug(PRINTF) printf("Pool::allocPages(n = %d)\n", n);
2895 for (i = 0; i < ncommitted; i++)
2897 if (pagetable[i] == B_FREE)
2900 { //debug(PRINTF) printf("\texisting pn = %d\n", i - n + 1);
2907 return extendPages(n);
2911 * Extend Pool by n pages.
2912 * Returns OPFAIL on failure.
2914 size_t extendPages(size_t n)
2916 //debug(PRINTF) printf("Pool::extendPages(n = %d)\n", n);
2917 if (ncommitted + n <= npages)
2921 tocommit = (n + (COMMITSIZE/PAGESIZE) - 1) & ~(COMMITSIZE/PAGESIZE - 1);
2922 if (ncommitted + tocommit > npages)
2923 tocommit = npages - ncommitted;
2924 //debug(PRINTF) printf("\tlooking to commit %d more pages\n", tocommit);
2926 if (os_mem_commit(baseAddr, ncommitted * PAGESIZE, tocommit * PAGESIZE) == 0)
2928 cstring.memset(pagetable + ncommitted, B_FREE, tocommit);
2929 auto i = ncommitted;
2930 ncommitted += tocommit;
2932 while (i && pagetable[i - 1] == B_FREE)
2937 //debug(PRINTF) printf("\tfailed to commit %d pages\n", tocommit);
2945 * Free npages pages starting with pagenum.
2947 void freePages(size_t pagenum, size_t npages)
2949 cstring.memset(&pagetable[pagenum], B_FREE, npages);
2954 * Used for sorting pooltable[]
2958 if (baseAddr < p2.baseAddr)
2961 return cast(int)(baseAddr > p2.baseAddr);
2966 /* ============================ SENTINEL =============================== */
2971 const size_t SENTINEL_PRE = cast(size_t) 0xF4F4F4F4F4F4F4F4UL; // 32 or 64 bits
2972 const ubyte SENTINEL_POST = 0xF5; // 8 bits
2973 const uint SENTINEL_EXTRA = 2 * size_t.sizeof + 1;
2976 size_t* sentinel_size(void *p) { return &(cast(size_t *)p)[-2]; }
2977 size_t* sentinel_pre(void *p) { return &(cast(size_t *)p)[-1]; }
2978 ubyte* sentinel_post(void *p) { return &(cast(ubyte *)p)[*sentinel_size(p)]; }
2981 void sentinel_init(void *p, size_t size)
2983 *sentinel_size(p) = size;
2984 *sentinel_pre(p) = SENTINEL_PRE;
2985 *sentinel_post(p) = SENTINEL_POST;
2989 void sentinel_Invariant(void *p)
2991 assert(*sentinel_pre(p) == SENTINEL_PRE);
2992 assert(*sentinel_post(p) == SENTINEL_POST);
2996 void *sentinel_add(void *p)
2998 return p + 2 * size_t.sizeof;
3002 void *sentinel_sub(void *p)
3004 return p - 2 * size_t.sizeof;
3009 const uint SENTINEL_EXTRA = 0;
3012 void sentinel_init(void *p, size_t size)
3017 void sentinel_Invariant(void *p)
3022 void *sentinel_add(void *p)
3028 void *sentinel_sub(void *p)