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 * \brief Extend the size of the heap
54 void *Heap_Extend(int Bytes)
57 tHeapHead *head = gHeapEnd;
61 if( (tVAddr)gHeapEnd == MM_KHEAP_MAX )
65 Log_Warning("Heap", "Heap_Extend called with Bytes=%i", Bytes);
70 if( (tVAddr)gHeapEnd + ((Bytes+0xFFF)&~0xFFF) > MM_KHEAP_MAX ) {
71 // Bytes = MM_KHEAP_MAX - (tVAddr)gHeapEnd;
75 // Heap expands in pages
76 for( i = 0; i < (Bytes+0xFFF) >> 12; i ++ )
78 if( !MM_Allocate( (tVAddr)gHeapEnd+(i<<12) ) )
80 Warning("OOM - Heap_Extend");
86 gHeapEnd = (Uint8*)gHeapEnd + (i << 12);
89 head->Size = (Bytes+0xFFF)&~0xFFF;
90 head->Magic = MAGIC_FREE;
91 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
93 foot->Magic = MAGIC_FOOT;
95 return Heap_Merge(head); // Merge with previous block
99 * \brief Merges two ajacent heap blocks
101 void *Heap_Merge(tHeapHead *Head)
107 //Log("Heap_Merge: (Head=%p)", Head);
109 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
110 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
113 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
114 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
115 && foot->Head->Magic == MAGIC_FREE) {
116 foot->Head->Size += Head->Size; // Increase size
117 thisFoot->Head = foot->Head; // Change backlink
118 Head->Magic = 0; // Clear old head
120 Head = foot->Head; // Save new head address
121 foot->Head = NULL; // Clear central footer
125 // Merge Right (Upwards)
126 head = (void*)( (Uint)Head + Head->Size );
127 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
129 Head->Size += head->Size;
130 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
131 foot->Head = Head; // Update Backlink
132 thisFoot->Head = NULL; // Clear old footer
134 head->Size = 0; // Clear old header
138 // Return new address
143 * \param File Allocating source file
144 * \param Line Source line
145 * \param __Bytes Size of region to allocate
147 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
149 tHeapHead *head, *newhead;
150 tHeapFoot *foot, *newfoot;
151 tHeapHead *best = NULL;
152 Uint bestSize = 0; // Speed hack
156 //return NULL; // TODO: Return a known un-mapped range.
162 Bytes = __Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
163 Bytes = 1UUL << LOG2(__Bytes);
165 Bytes = (__Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
169 Mutex_Acquire(&glHeap);
172 for( head = gHeapStart;
173 (Uint)head < (Uint)gHeapEnd;
174 head = (void*)((Uint)head + head->Size)
179 if( head->Size != 1UUL << LOG2(head->Size) ) {
181 if( head->Size & (MIN_SIZE-1) ) {
183 Mutex_Release(&glHeap); // Release spinlock
185 Log_Warning("Heap", "Size of heap address %p is invalid not aligned (0x%x)", head, head->Size);
191 // Check if allocated
192 if(head->Magic == MAGIC_USED) continue;
194 if(head->Magic != MAGIC_FREE) {
195 Mutex_Release(&glHeap); // Release spinlock
197 Log_Warning("Heap", "Magic of heap address %p is invalid (%p = 0x%x)",
198 head, &head->Magic, head->Magic);
205 if(head->Size < Bytes) continue;
208 if(head->Size == Bytes) {
209 head->Magic = MAGIC_USED;
212 head->ValidSize = __Bytes;
213 head->AllocateTime = now();
214 Mutex_Release(&glHeap); // Release spinlock
216 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %p",
217 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 best->ValidSize = __Bytes;
251 best->AllocateTime = now();
252 Mutex_Release(&glHeap); // Release spinlock
254 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %s:%i", best->Data, best->Size, File, Line);
261 newhead = (void*)( (Uint)best + Bytes );
262 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
263 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
265 newfoot->Head = best; // Create new footer
266 newfoot->Magic = MAGIC_FOOT;
267 newhead->Size = best->Size - Bytes; // Create new header
268 newhead->Magic = MAGIC_FREE;
269 foot->Head = newhead; // Update backlink in old footer
270 best->Size = Bytes; // Update size in old header
271 best->ValidSize = __Bytes;
272 best->Magic = MAGIC_USED; // Mark block as used
275 best->AllocateTime = now();
277 Mutex_Release(&glHeap); // Release spinlock
279 Debug("[Heap ] Malloc'd %p (0x%x bytes), returning to %s:%i",
280 best->Data, best->Size, File, Line);
286 * \brief Free an allocated memory block
288 void Heap_Deallocate(void *Ptr)
290 tHeapHead *head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
293 // INVLPTR is returned from Heap_Allocate when the allocation
295 if( Ptr == INVLPTR ) return;
298 Debug("[Heap ] free: %p freed by %p (%i old)", Ptr, __builtin_return_address(0), now()-head->AllocateTime);
302 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
303 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
308 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
310 Log_Warning("Heap", "free - Passed a non-heap address by %p (%p < %p < %p)\n",
311 __builtin_return_address(0), gHeapStart, Ptr, gHeapEnd);
315 // Check memory block - Header
316 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
317 if(head->Magic == MAGIC_FREE) {
318 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
321 if(head->Magic != MAGIC_USED) {
322 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
323 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
327 // Check memory block - Footer
328 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
329 if(foot->Head != head) {
330 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
331 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
334 if(foot->Magic != MAGIC_FOOT) {
335 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
336 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
341 Mutex_Acquire( &glHeap );
344 head->Magic = MAGIC_FREE;
352 Mutex_Release( &glHeap );
356 * \brief Increase/Decrease the size of an allocation
357 * \param File Calling File
358 * \param Line Calling Line
359 * \param __ptr Old memory
360 * \param __size New Size
362 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
364 tHeapHead *head = (void*)( (Uint)__ptr-sizeof(tHeapHead) );
367 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
369 // Check for reallocating NULL
370 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
372 // Check if resize is needed
373 if(newSize <= head->Size) return __ptr;
375 // Check if next block is free
376 nextHead = (void*)( (Uint)head + head->Size );
378 // Extend into next block
379 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
381 Uint size = nextHead->Size + head->Size;
382 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
384 if(size == newSize) {
385 head->Size = newSize;
386 head->ValidSize = __size;
394 // Create a new heap block
395 nextHead = (void*)( (Uint)head + newSize );
396 nextHead->Size = size - newSize;
397 nextHead->Magic = MAGIC_FREE;
398 foot->Head = nextHead; // Edit 2nd footer
399 head->Size = newSize; // Edit first header
402 head->ValidSize = __size;
404 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
406 foot->Magic = MAGIC_FOOT;
411 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
412 nextHead = foot->Head;
413 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
415 Uint size = nextHead->Size + head->Size;
416 // Inexact fit, split things up
420 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
427 // Set 1st (new/lower) header
428 nextHead->Magic = MAGIC_USED;
429 nextHead->Size = newSize;
430 nextHead->File = File;
431 nextHead->Line = Line;
432 nextHead->ValidSize = __size;
433 // Get 2nd (old) footer
434 foot = (void*)( (Uint)nextHead + newSize );
435 foot->Head = nextHead;
436 // Save old data size
437 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
442 memcpy(nextHead->Data, __ptr, oldDataSize);
444 return nextHead->Data;
446 // On to the expensive then
450 nextHead = Heap_Allocate( File, Line, __size );
452 nextHead->File = File;
453 nextHead->Line = Line;
454 nextHead->ValidSize = __size;
459 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
464 return nextHead->Data;
468 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
469 * \brief Allocate and Zero a buffer in memory
470 * \param File Allocating file
471 * \param Line Line of allocation
472 * \param Bytes Size of the allocation
474 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
476 void *ret = Heap_Allocate(File, Line, Bytes);
477 if(ret == NULL) return NULL;
479 memset( ret, 0, Bytes );
485 * \fn int Heap_IsHeapAddr(void *Ptr)
486 * \brief Checks if an address is a heap pointer
488 int Heap_IsHeapAddr(void *Ptr)
491 if((Uint)Ptr < (Uint)gHeapStart) return 0;
492 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
493 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
495 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
496 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
504 void Heap_Validate(void)
512 tHeapHead *head, *badHead;
513 tHeapFoot *foot = NULL;
516 while( (Uint)head < (Uint)gHeapEnd )
518 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
520 Log_Log("Heap", "%p (0x%P): 0x%08x (%i) %4C",
521 head, MM_GetPhysAddr((tVAddr)head), head->Size, head->ValidSize, &head->Magic);
522 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
524 Log_Log("Heap", "%sowned by %s:%i",
525 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
529 // Sanity Check Header
530 if(head->Size == 0) {
531 Log_Warning("Heap", "HALTED - Size is zero");
534 if(head->Size & (MIN_SIZE-1)) {
535 Log_Warning("Heap", "HALTED - Size is malaligned");
538 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
539 Log_Warning("Heap", "HALTED - Head Magic is Bad");
544 if(foot->Magic != MAGIC_FOOT) {
545 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
548 if(head != foot->Head) {
549 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
557 // All OK? Go to next
558 head = foot->NextHead;
561 // If the heap is valid, ok!
562 if( (tVAddr)head == (tVAddr)gHeapEnd )
565 // Check for a bad return
566 if( (tVAddr)head >= (tVAddr)gHeapEnd )
570 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
571 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
573 Log_Log("Heap", "Foot %p = {Head:%p,Magic:%4C}", foot, 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 (%P): 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 (%P) - 0x%x free",
671 head->Data, MM_GetPhysAddr((tVAddr)&head->Data), head->Size);
673 Log_Debug("Heap", "%p (%P) - 0x%x (%i) Owned by %s:%i (%lli ms old)",
674 head->Data, MM_GetPhysAddr((tVAddr)&head->Data), head->Size, head->ValidSize, head->File, head->Line,
675 now() - head->AllocateTime
680 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
681 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
683 frag = (nFree-1)*10000/nBlocks;
686 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
690 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
692 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
695 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
696 avgAlloc, overhead/100, overhead%100
698 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
701 // Scan and get distribution
708 } sizeCounts[nBlocks];
711 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
713 for(head = gHeapStart;
714 (Uint)head < (Uint)gHeapEnd;
715 head = (void*)( (Uint)head + head->Size )
718 for( i = 0; i < nBlocks; i ++ ) {
719 if( sizeCounts[i].Size == 0 )
721 if( sizeCounts[i].Size == head->Size )
724 // Should never reach this part (in a non-concurrent case)
725 if( i == nBlocks ) continue;
726 sizeCounts[i].Size = head->Size;
727 sizeCounts[i].Count ++;
729 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
730 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
732 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
733 // sizeCounts[i].Size, sizeCounts[i].Count);
737 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
739 Log("Heap_Stats: 0x%x - %i blocks",
740 sizeCounts[i].Size, sizeCounts[i].Count
749 EXPORT(Heap_Allocate);
750 EXPORT(Heap_AllocateZero);
751 EXPORT(Heap_Reallocate);
752 EXPORT(Heap_Deallocate);
753 EXPORT(Heap_IsHeapAddr);