3 * - By John Hodge (thePowersGang)
6 * - Dynamic memory allocation
12 #define WARNINGS 1 // Warn and dump on heap errors
13 #define DEBUG_TRACE 0 // Enable tracing of allocations
14 #define VERBOSE_DUMP 0 // Set to 1 to enable a verbose dump when heap errors are encountered
17 #define HEAP_INIT_SIZE 0x8000 // 32 KiB
18 #define MIN_SIZE (sizeof(void*))*8 // 8 Machine Words
20 #define COMPACT_HEAP 0 // Use 4 byte header?
23 //#define MAGIC_FOOT 0x2ACE5505
24 //#define MAGIC_FREE 0xACE55000
25 //#define MAGIC_USED 0x862B0505 // MAGIC_FOOT ^ MAGIC_FREE
26 #define MAGIC_FOOT 0x544F4F46 // 'FOOT'
27 #define MAGIC_FREE 0x45455246 // 'FREE'
28 #define MAGIC_USED 0x44455355 // 'USED'
31 void Heap_Install(void);
32 void *Heap_Extend(size_t Bytes);
33 void *Heap_Merge(tHeapHead *Head);
34 //void *Heap_Allocate(const char *File, int Line, size_t Bytes);
35 //void *Heap_AllocateZero(const char *File, int Line, size_t Bytes);
36 //void *Heap_Reallocate(const char *File, int Line, void *Ptr, size_t Bytes);
37 //void Heap_Deallocate(void *Ptr);
38 void Heap_Dump(int bVerbose);
39 void Heap_Stats(void);
43 tHeapHead *gHeapStart;
47 void Heap_Install(void)
49 gHeapStart = (void*)MM_KHEAP_BASE;
50 gHeapEnd = gHeapStart;
51 Heap_Extend(HEAP_INIT_SIZE);
55 * \brief Extend the size of the heap
57 void *Heap_Extend(size_t Bytes)
59 tHeapHead *head = gHeapEnd;
63 if( gHeapEnd == (tHeapHead*)MM_KHEAP_MAX )
67 Log_Warning("Heap", "Heap_Extend called with Bytes=%i", Bytes);
71 const Uint pages = (Bytes + 0xFFF) >> 12;
72 tHeapHead *new_end = (void*)( (tVAddr)gHeapEnd + (pages << 12) );
74 if( new_end > (tHeapHead*)MM_KHEAP_MAX )
76 // TODO: Clip allocation to avaliable space, and have caller check returned block
80 // Heap expands in pages
81 for( Uint i = 0; i < pages; i ++ )
83 if( !MM_Allocate( (tVAddr)gHeapEnd+(i<<12) ) )
85 Warning("OOM - Heap_Extend");
95 head->Size = (Bytes+0xFFF)&~0xFFF;
96 head->Magic = MAGIC_FREE;
97 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
99 foot->Magic = MAGIC_FOOT;
101 return Heap_Merge(head); // Merge with previous block
105 * \brief Merges two ajacent heap blocks
107 void *Heap_Merge(tHeapHead *Head)
113 //Log("Heap_Merge: (Head=%p)", Head);
115 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
116 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
119 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
120 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
121 && foot->Head->Magic == MAGIC_FREE) {
122 foot->Head->Size += Head->Size; // Increase size
123 thisFoot->Head = foot->Head; // Change backlink
124 Head->Magic = 0; // Clear old head
126 Head = foot->Head; // Save new head address
127 foot->Head = NULL; // Clear central footer
131 // Merge Right (Upwards)
132 head = (void*)( (Uint)Head + Head->Size );
133 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
135 Head->Size += head->Size;
136 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
137 foot->Head = Head; // Update Backlink
138 thisFoot->Head = NULL; // Clear old footer
140 head->Size = 0; // Clear old header
144 // Return new address
149 * \param File Allocating source file
150 * \param Line Source line
151 * \param __Bytes Size of region to allocate
153 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
155 tHeapHead *head, *newhead;
156 tHeapFoot *foot, *newfoot;
157 tHeapHead *best = NULL;
158 Uint bestSize = 0; // Speed hack
162 return NULL; // TODO: Return a known un-mapped range.
168 Bytes = __Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
169 Bytes = 1UUL << LOG2(__Bytes);
171 Bytes = (__Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
175 Mutex_Acquire(&glHeap);
178 for( head = gHeapStart; head < gHeapEnd; head = (void*)((Uint)head + head->Size) )
182 if( head->Size != 1UUL << LOG2(head->Size) ) {
184 if( head->Size & (MIN_SIZE-1) ) {
186 Mutex_Release(&glHeap); // Release spinlock
188 Log_Warning("Heap", "Size of heap address %p is invalid - not aligned (0x%x) [at paddr 0x%x]",
189 head, head->Size, MM_GetPhysAddr(&head->Size));
190 Heap_Dump(VERBOSE_DUMP);
194 if( head->Size < MIN_SIZE ) {
195 Mutex_Release(&glHeap);
196 Log_Warning("Heap", "Size of heap address %p is invalid - Too small (0x%x) [at paddr 0x%x]",
197 head, head->Size, MM_GetPhysAddr(&head->Size));
198 Heap_Dump(VERBOSE_DUMP);
201 if( head->Size > (2<<30) ) {
202 Mutex_Release(&glHeap);
203 Log_Warning("Heap", "Size of heap address %p is invalid - Over 2GiB (0x%x) [at paddr 0x%x]",
204 head, head->Size, MM_GetPhysAddr(&head->Size));
205 Heap_Dump(VERBOSE_DUMP);
209 // Check if allocated
210 if(head->Magic == MAGIC_USED) continue;
212 if(head->Magic != MAGIC_FREE) {
213 Mutex_Release(&glHeap); // Release spinlock
215 Log_Warning("Heap", "Magic of heap address %p is invalid (%p = 0x%x)",
216 head, &head->Magic, head->Magic);
217 Heap_Dump(VERBOSE_DUMP);
223 if(head->Size < Bytes) continue;
226 if(head->Size == Bytes) {
227 head->Magic = MAGIC_USED;
230 head->ValidSize = __Bytes;
231 head->AllocateTime = now();
232 Mutex_Release(&glHeap); // Release spinlock
234 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %p",
235 head->Data, head->Size, __builtin_return_address(0));
243 bestSize = head->Size;
246 // or check if the block is the best size
247 if(bestSize > head->Size) {
249 bestSize = head->Size;
254 // If no block large enough is found, create one
257 best = Heap_Extend( Bytes );
260 Mutex_Release(&glHeap); // Release spinlock
264 if(best->Size == Bytes) {
265 best->Magic = MAGIC_USED; // Mark block as used
268 best->ValidSize = __Bytes;
269 best->AllocateTime = now();
270 Mutex_Release(&glHeap); // Release spinlock
272 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %s:%i", best->Data, best->Size, File, Line);
279 newhead = (void*)( (Uint)best + Bytes );
280 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
281 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
283 newfoot->Head = best; // Create new footer
284 newfoot->Magic = MAGIC_FOOT;
285 newhead->Size = best->Size - Bytes; // Create new header
286 newhead->Magic = MAGIC_FREE;
287 foot->Head = newhead; // Update backlink in old footer
288 best->Size = Bytes; // Update size in old header
289 best->ValidSize = __Bytes;
290 best->Magic = MAGIC_USED; // Mark block as used
293 best->AllocateTime = now();
295 Mutex_Release(&glHeap); // Release spinlock
297 Debug("[Heap ] Malloc'd %p (0x%x bytes), returning to %s:%i",
298 best->Data, best->Size, File, Line);
304 * \brief Free an allocated memory block
306 void Heap_Deallocate(void *Ptr)
308 tHeapHead *head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
311 // INVLPTR is returned from Heap_Allocate when the allocation
313 if( Ptr == INVLPTR ) return;
316 Debug("[Heap ] free: %p freed by %p (%i old)", Ptr, __builtin_return_address(0), now()-head->AllocateTime);
320 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
321 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
326 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
328 Log_Warning("Heap", "free - Passed a non-heap address by %p (%p < %p < %p)",
329 __builtin_return_address(0), gHeapStart, Ptr, gHeapEnd);
333 // Check memory block - Header
334 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
335 if(head->Magic == MAGIC_FREE) {
336 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
339 if(head->Magic != MAGIC_USED) {
340 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
341 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
345 // Check memory block - Footer
346 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
347 if(foot->Head != head) {
348 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
349 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
352 if(foot->Magic != MAGIC_FOOT) {
353 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
354 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
359 Mutex_Acquire( &glHeap );
362 head->Magic = MAGIC_FREE;
370 Mutex_Release( &glHeap );
374 * \brief Increase/Decrease the size of an allocation
375 * \param File Calling File
376 * \param Line Calling Line
377 * \param __ptr Old memory
378 * \param __size New Size
380 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
382 tHeapHead *head = (void*)( (Uint)__ptr-sizeof(tHeapHead) );
385 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
387 // Check for reallocating NULL
388 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
390 // Check if resize is needed
391 if(newSize <= head->Size) return __ptr;
393 // Check if next block is free
394 nextHead = (void*)( (Uint)head + head->Size );
396 // Extend into next block
397 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
399 Uint size = nextHead->Size + head->Size;
400 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
402 if(size == newSize) {
403 head->Size = newSize;
404 head->ValidSize = __size;
412 // Create a new heap block
413 nextHead = (void*)( (Uint)head + newSize );
414 nextHead->Size = size - newSize;
415 nextHead->Magic = MAGIC_FREE;
416 foot->Head = nextHead; // Edit 2nd footer
417 head->Size = newSize; // Edit first header
420 head->ValidSize = __size;
422 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
424 foot->Magic = MAGIC_FOOT;
429 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
430 nextHead = foot->Head;
431 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
433 Uint size = nextHead->Size + head->Size;
434 // Inexact fit, split things up
438 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
445 // Set 1st (new/lower) header
446 nextHead->Magic = MAGIC_USED;
447 nextHead->Size = newSize;
448 nextHead->File = File;
449 nextHead->Line = Line;
450 nextHead->ValidSize = __size;
451 // Get 2nd (old) footer
452 foot = (void*)( (Uint)nextHead + newSize );
453 foot->Head = nextHead;
454 // Save old data size
455 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
460 memcpy(nextHead->Data, __ptr, oldDataSize);
462 return nextHead->Data;
464 // On to the expensive then
468 nextHead = Heap_Allocate( File, Line, __size );
469 if(!nextHead) return NULL;
471 nextHead->File = File;
472 nextHead->Line = Line;
473 nextHead->ValidSize = __size;
478 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
483 return nextHead->Data;
487 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
488 * \brief Allocate and Zero a buffer in memory
489 * \param File Allocating file
490 * \param Line Line of allocation
491 * \param Bytes Size of the allocation
493 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
495 void *ret = Heap_Allocate(File, Line, Bytes);
496 if(ret == NULL) return NULL;
498 memset( ret, 0, Bytes );
504 * \fn int Heap_IsHeapAddr(void *Ptr)
505 * \brief Checks if an address is a heap pointer
507 int Heap_IsHeapAddr(void *Ptr)
510 if((Uint)Ptr < (Uint)gHeapStart) return 0;
511 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
512 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
514 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
515 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
523 void Heap_Validate(void)
525 // Call dump non-verbosely.
526 // - If a heap error is detected, it'll print
530 void Heap_Dump(int bVerbose)
532 tHeapHead *head, *badHead;
533 tHeapFoot *foot = NULL;
534 static int in_heap_dump;
536 if( in_heap_dump ) return;
541 while( (Uint)head < (Uint)gHeapEnd )
543 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
547 Log_Log("Heap", "%p (0x%P): 0x%08x (%i) %4C",
548 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
549 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
551 Log_Log("Heap", "%sowned by %s:%i",
552 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
556 // Sanity Check Header
557 if(head->Size == 0) {
558 Log_Warning("Heap", "HALTED - Size is zero");
561 if(head->Size & (MIN_SIZE-1)) {
562 Log_Warning("Heap", "HALTED - Size is malaligned");
565 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
566 Log_Warning("Heap", "HALTED - Head Magic is Bad");
571 if(foot->Magic != MAGIC_FOOT) {
572 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
575 if(head != foot->Head) {
576 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
585 // All OK? Go to next
586 head = foot->NextHead;
589 // If the heap is valid, ok!
590 if( (tVAddr)head == (tVAddr)gHeapEnd ) {
595 // Check for a bad return
596 if( (tVAddr)head >= (tVAddr)gHeapEnd ) {
601 // If not verbose, we need to dump the failing block
604 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
605 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
607 Log_Log("Heap", "Foot %p = {Head:%p,Magic:%4C}", foot, foot->Head, &foot->Magic);
609 Log_Log("Heap", "%sowned by %s:%i",
610 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
619 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
620 Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
622 while( (tVAddr)head >= (tVAddr)badHead )
624 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
625 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
626 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
628 Log_Log("Heap", "%sowned by %s:%i",
629 (head->Magic!=MAGIC_USED?"was ":""),
630 head->File, head->Line);
633 // Sanity Check Header
634 if(head->Size == 0) {
635 Log_Warning("Heap", "HALTED - Size is zero");
638 if(head->Size & (MIN_SIZE-1)) {
639 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
642 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
643 Log_Warning("Heap", "HALTED - Head Magic is Bad");
648 if(foot->Magic != MAGIC_FOOT) {
649 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
652 if(head != foot->Head) {
653 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
657 if(head == badHead) break;
659 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
661 Log_Debug("Heap", "head=%p", head);
664 Panic("Heap_Dump - Heap is corrupted, kernel panic!");
667 void Heap_Stats(void)
673 int maxAlloc=0, minAlloc=-1;
674 int avgAlloc, frag, overhead;
676 for(tHeapHead *head = gHeapStart; head < gHeapEnd; head = (void*)( (tVAddr)head + head->Size ) )
679 totalBytes += head->Size;
680 if( head->Magic == MAGIC_FREE )
683 freeBytes += head->Size;
685 else if( head->Magic == MAGIC_USED) {
686 if(maxAlloc < head->Size) maxAlloc = head->Size;
687 if(minAlloc == -1 || minAlloc > head->Size)
688 minAlloc = head->Size;
691 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
695 // Print the block info?
697 if( head->Magic == MAGIC_FREE )
698 Log_Debug("Heap", "%p (%P) - 0x%x free",
699 head->Data, MM_GetPhysAddr(&head->Data), head->Size);
701 Log_Debug("Heap", "%p (%P) - 0x%x (%i) Owned by %s:%i (%lli ms old)",
702 head->Data, MM_GetPhysAddr(&head->Data), head->Size,
703 head->ValidSize, head->File, head->Line,
704 now() - head->AllocateTime
709 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
710 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
712 frag = (nFree-1)*10000/nBlocks;
715 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
719 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
721 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
724 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
725 avgAlloc, overhead/100, overhead%100
727 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
730 // Scan and get distribution
737 } sizeCounts[nBlocks];
740 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
742 for(tHeapHead *head = gHeapStart; head < gHeapEnd; head = (void*)( (tVAddr)head + head->Size ) )
744 for( i = 0; i < nBlocks; i ++ ) {
745 if( sizeCounts[i].Size == 0 )
747 if( sizeCounts[i].Size == head->Size )
750 // Should never reach this part (in a non-concurrent case)
751 if( i == nBlocks ) continue;
752 sizeCounts[i].Size = head->Size;
753 sizeCounts[i].Count ++;
755 Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
756 head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
758 Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
759 sizeCounts[i].Size, sizeCounts[i].Count);
763 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
765 Log("Heap_Stats: 0x%x - %i blocks",
766 sizeCounts[i].Size, sizeCounts[i].Count
774 EXPORT(Heap_Allocate);
775 EXPORT(Heap_AllocateZero);
776 EXPORT(Heap_Reallocate);
777 EXPORT(Heap_Deallocate);
778 EXPORT(Heap_IsHeapAddr);