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 if( (tVAddr)gHeapEnd + ((Bytes+0xFFF)&~0xFFF) > MM_KHEAP_MAX ) {
67 Bytes = MM_KHEAP_MAX - (tVAddr)gHeapEnd;
71 // Heap expands in pages
72 for(i=0;i<(Bytes+0xFFF)>>12;i++)
73 MM_Allocate( (tVAddr)gHeapEnd+(i<<12) );
79 head->Size = (Bytes+0xFFF)&~0xFFF;
80 head->Magic = MAGIC_FREE;
81 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
83 foot->Magic = MAGIC_FOOT;
85 return Heap_Merge(head); // Merge with previous block
89 * \fn void *Heap_Merge(tHeapHead *Head)
90 * \brief Merges two ajacent heap blocks
92 void *Heap_Merge(tHeapHead *Head)
98 //Log("Heap_Merge: (Head=%p)", Head);
100 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
101 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
104 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
105 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
106 && foot->Head->Magic == MAGIC_FREE) {
107 foot->Head->Size += Head->Size; // Increase size
108 thisFoot->Head = foot->Head; // Change backlink
109 Head->Magic = 0; // Clear old head
111 Head = foot->Head; // Save new head address
112 foot->Head = NULL; // Clear central footer
116 // Merge Right (Upwards)
117 head = (void*)( (Uint)Head + Head->Size );
118 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
120 Head->Size += head->Size;
121 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
122 foot->Head = Head; // Update Backlink
123 thisFoot->Head = NULL; // Clear old footer
125 head->Size = 0; // Clear old header
129 // Return new address
134 * \brief Allocate memory from the heap
135 * \param File Allocating source file
136 * \param Line Source line
137 * \param Bytes Size of region to allocate
139 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
141 tHeapHead *head, *newhead;
142 tHeapFoot *foot, *newfoot;
143 tHeapHead *best = NULL;
144 Uint bestSize = 0; // Speed hack
148 //return NULL; // TODO: Return a known un-mapped range.
154 Bytes = __Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
155 Bytes = 1UUL << LOG2(__Bytes);
157 Bytes = (__Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
161 Mutex_Acquire(&glHeap);
164 for( head = gHeapStart;
165 (Uint)head < (Uint)gHeapEnd;
166 head = (void*)((Uint)head + head->Size)
171 if( head->Size != 1UUL << LOG2(head->Size) ) {
173 if( head->Size & (MIN_SIZE-1) ) {
175 Mutex_Release(&glHeap); // Release spinlock
177 Log_Warning("Heap", "Size of heap address %p is invalid not aligned (0x%x)", head, head->Size);
183 // Check if allocated
184 if(head->Magic == MAGIC_USED) continue;
186 if(head->Magic != MAGIC_FREE) {
187 Mutex_Release(&glHeap); // Release spinlock
189 Log_Warning("Heap", "Magic of heap address %p is invalid (0x%x)", head, head->Magic);
196 if(head->Size < Bytes) continue;
199 if(head->Size == Bytes) {
200 head->Magic = MAGIC_USED;
203 Mutex_Release(&glHeap); // Release spinlock
205 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", head->Data, head->Size, __builtin_return_address(0));
213 bestSize = head->Size;
216 // or check if the block is the best size
217 if(bestSize > head->Size) {
219 bestSize = head->Size;
224 // If no block large enough is found, create one
227 best = Heap_Extend( Bytes );
230 Mutex_Release(&glHeap); // Release spinlock
234 if(best->Size == Bytes) {
235 best->Magic = MAGIC_USED; // Mark block as used
238 Mutex_Release(&glHeap); // Release spinlock
240 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", best->Data, best->Size, __builtin_return_address(0));
247 newhead = (void*)( (Uint)best + Bytes );
248 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
249 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
251 newfoot->Head = best; // Create new footer
252 newfoot->Magic = MAGIC_FOOT;
253 newhead->Size = best->Size - Bytes; // Create new header
254 newhead->Magic = MAGIC_FREE;
255 foot->Head = newhead; // Update backlink in old footer
256 best->Size = Bytes; // Update size in old header
257 best->ValidSize = __Bytes;
258 best->Magic = MAGIC_USED; // Mark block as used
262 Mutex_Release(&glHeap); // Release spinlock
264 Log_Debug("Heap", "newhead(%p)->Size = 0x%x", newhead, newhead->Size);
265 Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
266 best->Data, best->Size, File, Line);
272 * \fn void Heap_Deallocate(void *Ptr)
273 * \brief Free an allocated memory block
275 void Heap_Deallocate(void *Ptr)
281 Log_Log("Heap", "free: Ptr = %p", Ptr);
282 Log_Log("Heap", "free: Returns to %p", __builtin_return_address(0));
285 // INVLPTR is returned from Heap_Allocate when the allocation
287 if( Ptr == INVLPTR ) return;
290 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
291 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
296 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
298 Log_Warning("Heap", "free - Passed a non-heap address (%p < %p < %p)\n",
299 gHeapStart, Ptr, gHeapEnd);
303 // Check memory block - Header
304 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
305 if(head->Magic == MAGIC_FREE) {
306 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
309 if(head->Magic != MAGIC_USED) {
310 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
311 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
315 // Check memory block - Footer
316 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
317 if(foot->Head != head) {
318 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
319 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
322 if(foot->Magic != MAGIC_FOOT) {
323 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
324 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
329 Mutex_Acquire( &glHeap );
332 head->Magic = MAGIC_FREE;
340 Mutex_Release( &glHeap );
344 * \brief Increase/Decrease the size of an allocation
345 * \param File Calling File
346 * \param Line Calling Line
347 * \param __ptr Old memory
348 * \param __size New Size
350 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
352 tHeapHead *head = (void*)( (Uint)__ptr-sizeof(tHeapHead) );
355 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
357 // Check for reallocating NULL
358 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
360 // Check if resize is needed
361 if(newSize <= head->Size) return __ptr;
363 // Check if next block is free
364 nextHead = (void*)( (Uint)head + head->Size );
366 // Extend into next block
367 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
369 Uint size = nextHead->Size + head->Size;
370 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
372 if(size == newSize) {
373 head->Size = newSize;
374 head->ValidSize = __size;
382 // Create a new heap block
383 nextHead = (void*)( (Uint)head + newSize );
384 nextHead->Size = size - newSize;
385 nextHead->Magic = MAGIC_FREE;
386 foot->Head = nextHead; // Edit 2nd footer
387 head->Size = newSize; // Edit first header
390 head->ValidSize = __size;
392 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
394 foot->Magic = MAGIC_FOOT;
399 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
400 nextHead = foot->Head;
401 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
403 Uint size = nextHead->Size + head->Size;
404 // Inexact fit, split things up
408 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
415 // Set 1st (new/lower) header
416 nextHead->Magic = MAGIC_USED;
417 nextHead->Size = newSize;
418 nextHead->File = File;
419 nextHead->Line = Line;
420 nextHead->ValidSize = __size;
421 // Get 2nd (old) footer
422 foot = (void*)( (Uint)nextHead + newSize );
423 foot->Head = nextHead;
424 // Save old data size
425 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
430 memcpy(nextHead->Data, __ptr, oldDataSize);
432 return nextHead->Data;
434 // On to the expensive then
438 nextHead = Heap_Allocate( File, Line, __size );
440 nextHead->File = File;
441 nextHead->Line = Line;
442 nextHead->ValidSize = __size;
447 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
452 return nextHead->Data;
456 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
457 * \brief Allocate and Zero a buffer in memory
458 * \param File Allocating file
459 * \param Line Line of allocation
460 * \param Bytes Size of the allocation
462 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
464 void *ret = Heap_Allocate(File, Line, Bytes);
465 if(ret == NULL) return NULL;
467 memset( ret, 0, Bytes );
473 * \fn int Heap_IsHeapAddr(void *Ptr)
474 * \brief Checks if an address is a heap pointer
476 int Heap_IsHeapAddr(void *Ptr)
479 if((Uint)Ptr < (Uint)gHeapStart) return 0;
480 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
481 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
483 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
484 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
492 void Heap_Validate(void)
500 tHeapHead *head, *badHead;
501 tHeapFoot *foot = NULL;
504 while( (Uint)head < (Uint)gHeapEnd )
506 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
508 Log_Log("Heap", "%p (0x%llx): 0x%08lx (%i) %4C",
509 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
510 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
512 Log_Log("Heap", "%sowned by %s:%i",
513 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
517 // Sanity Check Header
518 if(head->Size == 0) {
519 Log_Warning("Heap", "HALTED - Size is zero");
522 if(head->Size & (MIN_SIZE-1)) {
523 Log_Warning("Heap", "HALTED - Size is malaligned");
526 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
527 Log_Warning("Heap", "HALTED - Head Magic is Bad");
532 if(foot->Magic != MAGIC_FOOT) {
533 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
536 if(head != foot->Head) {
537 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
545 // All OK? Go to next
546 head = foot->NextHead;
549 // If the heap is valid, ok!
550 if( (tVAddr)head == (tVAddr)gHeapEnd )
553 // Check for a bad return
554 if( (tVAddr)head >= (tVAddr)gHeapEnd )
558 Log_Log("Heap", "%p (0x%llx): 0x%08lx (%i) %4C",
559 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
560 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
562 Log_Log("Heap", "%sowned by %s:%i",
563 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
572 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
573 Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
575 while( (tVAddr)head >= (tVAddr)badHead )
577 Log_Log("Heap", "%p (0x%llx): 0x%08lx %i %4C",
578 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
579 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
581 Log_Log("Heap", "%sowned by %s:%i",
582 (head->Magic!=MAGIC_USED?"was ":""),
583 head->File, head->Line);
586 // Sanity Check Header
587 if(head->Size == 0) {
588 Log_Warning("Heap", "HALTED - Size is zero");
591 if(head->Size & (MIN_SIZE-1)) {
592 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
595 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
596 Log_Warning("Heap", "HALTED - Head Magic is Bad");
601 if(foot->Magic != MAGIC_FOOT) {
602 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
605 if(head != foot->Head) {
606 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
610 if(head == badHead) break;
612 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
614 Log_Debug("Heap", "head=%p", head);
617 Panic("Heap_Dump - Heap is corrupted, kernel panic!");
622 void Heap_Stats(void)
629 int maxAlloc=0, minAlloc=-1;
630 int avgAlloc, frag, overhead;
632 for(head = gHeapStart;
633 (Uint)head < (Uint)gHeapEnd;
634 head = (void*)( (Uint)head + head->Size )
638 totalBytes += head->Size;
639 if( head->Magic == MAGIC_FREE )
642 freeBytes += head->Size;
644 else if( head->Magic == MAGIC_USED) {
645 if(maxAlloc < head->Size) maxAlloc = head->Size;
646 if(minAlloc == -1 || minAlloc > head->Size)
647 minAlloc = head->Size;
650 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
654 // Print the block info?
656 Log_Debug("Heap", "%p - 0x%x (%i) Owned by %s:%i",
657 head, head->Size, head->ValidSize, head->File, head->Line);
661 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
662 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
663 frag = (nFree-1)*10000/nBlocks;
664 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
665 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
666 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
667 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
668 avgAlloc, overhead/100, overhead%100
670 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
673 // Scan and get distribution
679 } sizeCounts[nBlocks];
682 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
684 for(head = gHeapStart;
685 (Uint)head < (Uint)gHeapEnd;
686 head = (void*)( (Uint)head + head->Size )
689 for( i = 0; i < nBlocks; i ++ ) {
690 if( sizeCounts[i].Size == 0 )
692 if( sizeCounts[i].Size == head->Size )
695 // Should never reach this part (in a non-concurrent case)
696 if( i == nBlocks ) continue;
697 sizeCounts[i].Size = head->Size;
698 sizeCounts[i].Count ++;
700 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
701 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
703 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
704 // sizeCounts[i].Size, sizeCounts[i].Count);
708 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
710 Log("Heap_Stats: 0x%x - %i blocks",
711 sizeCounts[i].Size, sizeCounts[i].Count
720 EXPORT(Heap_Allocate);
721 EXPORT(Heap_AllocateZero);
722 EXPORT(Heap_Reallocate);
723 EXPORT(Heap_Deallocate);
724 EXPORT(Heap_IsHeapAddr);