2 * AcessOS Microkernel Version
11 #define VERBOSE_DUMP 0
14 #define HEAP_INIT_SIZE 0x8000 // 32 KiB
15 #define MIN_SIZE (sizeof(void*))*8 // 8 Machine Words
17 #define COMPACT_HEAP 0 // Use 4 byte header?
20 //#define MAGIC_FOOT 0x2ACE5505
21 //#define MAGIC_FREE 0xACE55000
22 //#define MAGIC_USED 0x862B0505 // MAGIC_FOOT ^ MAGIC_FREE
23 #define MAGIC_FOOT 0x544F4F46 // 'FOOT'
24 #define MAGIC_FREE 0x45455246 // 'FREE'
25 #define MAGIC_USED 0x44455355 // 'USED'
28 void Heap_Install(void);
29 void *Heap_Extend(int Bytes);
30 void *Heap_Merge(tHeapHead *Head);
31 //void *Heap_Allocate(const char *File, int Line, size_t Bytes);
32 //void *Heap_AllocateZero(const char *File, int Line, size_t Bytes);
33 //void *Heap_Reallocate(const char *File, int Line, void *Ptr, size_t Bytes);
34 //void Heap_Deallocate(void *Ptr);
36 void Heap_Stats(void);
44 void Heap_Install(void)
46 gHeapStart = (void*)MM_KHEAP_BASE;
47 gHeapEnd = (void*)MM_KHEAP_BASE;
48 Heap_Extend(HEAP_INIT_SIZE);
52 * \fn void *Heap_Extend(int Bytes)
53 * \brief Extend the size of the heap
55 void *Heap_Extend(int Bytes)
58 tHeapHead *head = gHeapEnd;
62 if( (tVAddr)gHeapEnd == MM_KHEAP_MAX )
66 Log_Warning("Heap", "Heap_Extend called with Bytes=%i", Bytes);
71 if( (tVAddr)gHeapEnd + ((Bytes+0xFFF)&~0xFFF) > MM_KHEAP_MAX ) {
72 Bytes = MM_KHEAP_MAX - (tVAddr)gHeapEnd;
76 // Heap expands in pages
77 for( i = 0; i < (Bytes+0xFFF) >> 12; i ++ )
79 if( !MM_Allocate( (tVAddr)gHeapEnd+(i<<12) ) )
81 Warning("OOM - Heap_Extend");
87 gHeapEnd = (Uint8*)gHeapEnd + (i << 12);
90 head->Size = (Bytes+0xFFF)&~0xFFF;
91 head->Magic = MAGIC_FREE;
92 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
94 foot->Magic = MAGIC_FOOT;
96 return Heap_Merge(head); // Merge with previous block
100 * \fn void *Heap_Merge(tHeapHead *Head)
101 * \brief Merges two ajacent heap blocks
103 void *Heap_Merge(tHeapHead *Head)
109 //Log("Heap_Merge: (Head=%p)", Head);
111 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
112 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
115 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
116 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
117 && foot->Head->Magic == MAGIC_FREE) {
118 foot->Head->Size += Head->Size; // Increase size
119 thisFoot->Head = foot->Head; // Change backlink
120 Head->Magic = 0; // Clear old head
122 Head = foot->Head; // Save new head address
123 foot->Head = NULL; // Clear central footer
127 // Merge Right (Upwards)
128 head = (void*)( (Uint)Head + Head->Size );
129 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
131 Head->Size += head->Size;
132 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
133 foot->Head = Head; // Update Backlink
134 thisFoot->Head = NULL; // Clear old footer
136 head->Size = 0; // Clear old header
140 // Return new address
145 * \brief Allocate memory from the heap
146 * \param File Allocating source file
147 * \param Line Source line
148 * \param Bytes Size of region to allocate
150 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
152 tHeapHead *head, *newhead;
153 tHeapFoot *foot, *newfoot;
154 tHeapHead *best = NULL;
155 Uint bestSize = 0; // Speed hack
159 //return NULL; // TODO: Return a known un-mapped range.
165 Bytes = __Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
166 Bytes = 1UUL << LOG2(__Bytes);
168 Bytes = (__Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
172 Mutex_Acquire(&glHeap);
175 for( head = gHeapStart;
176 (Uint)head < (Uint)gHeapEnd;
177 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)", head, head->Size);
194 // Check if allocated
195 if(head->Magic == MAGIC_USED) continue;
197 if(head->Magic != MAGIC_FREE) {
198 Mutex_Release(&glHeap); // Release spinlock
200 Log_Warning("Heap", "Magic of heap address %p is invalid (0x%x)", head, head->Magic);
207 if(head->Size < Bytes) continue;
210 if(head->Size == Bytes) {
211 head->Magic = MAGIC_USED;
214 head->ValidSize = __Bytes;
215 Mutex_Release(&glHeap); // Release spinlock
217 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", head->Data, head->Size, __builtin_return_address(0));
225 bestSize = head->Size;
228 // or check if the block is the best size
229 if(bestSize > head->Size) {
231 bestSize = head->Size;
236 // If no block large enough is found, create one
239 best = Heap_Extend( Bytes );
242 Mutex_Release(&glHeap); // Release spinlock
246 if(best->Size == Bytes) {
247 best->Magic = MAGIC_USED; // Mark block as used
250 head->ValidSize = __Bytes;
251 Mutex_Release(&glHeap); // Release spinlock
253 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", best->Data, best->Size, __builtin_return_address(0));
260 newhead = (void*)( (Uint)best + Bytes );
261 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
262 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
264 newfoot->Head = best; // Create new footer
265 newfoot->Magic = MAGIC_FOOT;
266 newhead->Size = best->Size - Bytes; // Create new header
267 newhead->Magic = MAGIC_FREE;
268 foot->Head = newhead; // Update backlink in old footer
269 best->Size = Bytes; // Update size in old header
270 best->ValidSize = __Bytes;
271 best->Magic = MAGIC_USED; // Mark block as used
275 Mutex_Release(&glHeap); // Release spinlock
277 Log_Debug("Heap", "newhead(%p)->Size = 0x%x", newhead, newhead->Size);
278 Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
279 best->Data, best->Size, File, Line);
285 * \fn void Heap_Deallocate(void *Ptr)
286 * \brief Free an allocated memory block
288 void Heap_Deallocate(void *Ptr)
294 Log_Log("Heap", "free: Ptr = %p", Ptr);
295 Log_Log("Heap", "free: Returns to %p", __builtin_return_address(0));
298 // INVLPTR is returned from Heap_Allocate when the allocation
300 if( Ptr == INVLPTR ) return;
303 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
304 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
309 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
311 Log_Warning("Heap", "free - Passed a non-heap address (%p < %p < %p)\n",
312 gHeapStart, Ptr, gHeapEnd);
316 // Check memory block - Header
317 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
318 if(head->Magic == MAGIC_FREE) {
319 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
322 if(head->Magic != MAGIC_USED) {
323 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
324 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
328 // Check memory block - Footer
329 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
330 if(foot->Head != head) {
331 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
332 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
335 if(foot->Magic != MAGIC_FOOT) {
336 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
337 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
342 Mutex_Acquire( &glHeap );
345 head->Magic = MAGIC_FREE;
353 Mutex_Release( &glHeap );
357 * \brief Increase/Decrease the size of an allocation
358 * \param File Calling File
359 * \param Line Calling Line
360 * \param __ptr Old memory
361 * \param __size New Size
363 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
365 tHeapHead *head = (void*)( (Uint)__ptr-sizeof(tHeapHead) );
368 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
370 // Check for reallocating NULL
371 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
373 // Check if resize is needed
374 if(newSize <= head->Size) return __ptr;
376 // Check if next block is free
377 nextHead = (void*)( (Uint)head + head->Size );
379 // Extend into next block
380 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
382 Uint size = nextHead->Size + head->Size;
383 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
385 if(size == newSize) {
386 head->Size = newSize;
387 head->ValidSize = __size;
395 // Create a new heap block
396 nextHead = (void*)( (Uint)head + newSize );
397 nextHead->Size = size - newSize;
398 nextHead->Magic = MAGIC_FREE;
399 foot->Head = nextHead; // Edit 2nd footer
400 head->Size = newSize; // Edit first header
403 head->ValidSize = __size;
405 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
407 foot->Magic = MAGIC_FOOT;
412 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
413 nextHead = foot->Head;
414 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
416 Uint size = nextHead->Size + head->Size;
417 // Inexact fit, split things up
421 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
428 // Set 1st (new/lower) header
429 nextHead->Magic = MAGIC_USED;
430 nextHead->Size = newSize;
431 nextHead->File = File;
432 nextHead->Line = Line;
433 nextHead->ValidSize = __size;
434 // Get 2nd (old) footer
435 foot = (void*)( (Uint)nextHead + newSize );
436 foot->Head = nextHead;
437 // Save old data size
438 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
443 memcpy(nextHead->Data, __ptr, oldDataSize);
445 return nextHead->Data;
447 // On to the expensive then
451 nextHead = Heap_Allocate( File, Line, __size );
453 nextHead->File = File;
454 nextHead->Line = Line;
455 nextHead->ValidSize = __size;
460 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
465 return nextHead->Data;
469 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
470 * \brief Allocate and Zero a buffer in memory
471 * \param File Allocating file
472 * \param Line Line of allocation
473 * \param Bytes Size of the allocation
475 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
477 void *ret = Heap_Allocate(File, Line, Bytes);
478 if(ret == NULL) return NULL;
480 memset( ret, 0, Bytes );
486 * \fn int Heap_IsHeapAddr(void *Ptr)
487 * \brief Checks if an address is a heap pointer
489 int Heap_IsHeapAddr(void *Ptr)
492 if((Uint)Ptr < (Uint)gHeapStart) return 0;
493 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
494 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
496 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
497 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
505 void Heap_Validate(void)
513 tHeapHead *head, *badHead;
514 tHeapFoot *foot = NULL;
517 while( (Uint)head < (Uint)gHeapEnd )
519 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
521 Log_Log("Heap", "%p (0x%llx): 0x%08lx (%i) %4C",
522 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
523 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
525 Log_Log("Heap", "%sowned by %s:%i",
526 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
530 // Sanity Check Header
531 if(head->Size == 0) {
532 Log_Warning("Heap", "HALTED - Size is zero");
535 if(head->Size & (MIN_SIZE-1)) {
536 Log_Warning("Heap", "HALTED - Size is malaligned");
539 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
540 Log_Warning("Heap", "HALTED - Head Magic is Bad");
545 if(foot->Magic != MAGIC_FOOT) {
546 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
549 if(head != foot->Head) {
550 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
558 // All OK? Go to next
559 head = foot->NextHead;
562 // If the heap is valid, ok!
563 if( (tVAddr)head == (tVAddr)gHeapEnd )
566 // Check for a bad return
567 if( (tVAddr)head >= (tVAddr)gHeapEnd )
571 Log_Log("Heap", "%p (0x%llx): 0x%08lx %i %4C",
572 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
573 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
575 Log_Log("Heap", "%sowned by %s:%i",
576 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
585 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
586 Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
588 while( (tVAddr)head >= (tVAddr)badHead )
590 Log_Log("Heap", "%p (0x%llx): 0x%08lx %i %4C",
591 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
592 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
594 Log_Log("Heap", "%sowned by %s:%i",
595 (head->Magic!=MAGIC_USED?"was ":""),
596 head->File, head->Line);
599 // Sanity Check Header
600 if(head->Size == 0) {
601 Log_Warning("Heap", "HALTED - Size is zero");
604 if(head->Size & (MIN_SIZE-1)) {
605 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
608 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
609 Log_Warning("Heap", "HALTED - Head Magic is Bad");
614 if(foot->Magic != MAGIC_FOOT) {
615 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
618 if(head != foot->Head) {
619 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
623 if(head == badHead) break;
625 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
627 Log_Debug("Heap", "head=%p", head);
630 Panic("Heap_Dump - Heap is corrupted, kernel panic!");
635 void Heap_Stats(void)
642 int maxAlloc=0, minAlloc=-1;
643 int avgAlloc, frag, overhead;
645 for(head = gHeapStart;
646 (Uint)head < (Uint)gHeapEnd;
647 head = (void*)( (Uint)head + head->Size )
651 totalBytes += head->Size;
652 if( head->Magic == MAGIC_FREE )
655 freeBytes += head->Size;
657 else if( head->Magic == MAGIC_USED) {
658 if(maxAlloc < head->Size) maxAlloc = head->Size;
659 if(minAlloc == -1 || minAlloc > head->Size)
660 minAlloc = head->Size;
663 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
667 // Print the block info?
669 if( head->Magic == MAGIC_FREE )
670 Log_Debug("Heap", "%p (0x%llx) - 0x%x free",
671 head->Data, MM_GetPhysAddr((tVAddr)&head->Data), head->Size);
673 Log_Debug("Heap", "%p (0x%llx) - 0x%x (%i) Owned by %s:%i",
674 head->Data, MM_GetPhysAddr((tVAddr)&head->Data), head->Size, head->ValidSize, head->File, head->Line);
678 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
679 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
680 frag = (nFree-1)*10000/nBlocks;
681 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
682 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
683 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
684 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
685 avgAlloc, overhead/100, overhead%100
687 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
690 // Scan and get distribution
696 } sizeCounts[nBlocks];
699 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
701 for(head = gHeapStart;
702 (Uint)head < (Uint)gHeapEnd;
703 head = (void*)( (Uint)head + head->Size )
706 for( i = 0; i < nBlocks; i ++ ) {
707 if( sizeCounts[i].Size == 0 )
709 if( sizeCounts[i].Size == head->Size )
712 // Should never reach this part (in a non-concurrent case)
713 if( i == nBlocks ) continue;
714 sizeCounts[i].Size = head->Size;
715 sizeCounts[i].Count ++;
717 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
718 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
720 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
721 // sizeCounts[i].Size, sizeCounts[i].Count);
725 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
727 Log("Heap_Stats: 0x%x - %i blocks",
728 sizeCounts[i].Size, sizeCounts[i].Count
737 EXPORT(Heap_Allocate);
738 EXPORT(Heap_AllocateZero);
739 EXPORT(Heap_Reallocate);
740 EXPORT(Heap_Deallocate);
741 EXPORT(Heap_IsHeapAddr);