2 * AcessOS Microkernel Version
13 #define HEAP_INIT_SIZE 0x8000 // 32 KiB
14 #define MIN_SIZE (sizeof(void*))*8 // 8 Machine Words
16 #define COMPACT_HEAP 0 // Use 4 byte header?
19 //#define MAGIC_FOOT 0x2ACE5505
20 //#define MAGIC_FREE 0xACE55000
21 //#define MAGIC_USED 0x862B0505 // MAGIC_FOOT ^ MAGIC_FREE
22 #define MAGIC_FOOT 0x544F4F46 // 'FOOT'
23 #define MAGIC_FREE 0x45455246 // 'FREE'
24 #define MAGIC_USED 0x44455355 // 'USED'
27 void Heap_Install(void);
28 void *Heap_Extend(int Bytes);
29 void *Heap_Merge(tHeapHead *Head);
30 void *Heap_Allocate(const char *File, int Line, size_t Bytes);
31 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes);
32 void *Heap_Reallocate(const char *File, int Line, void *Ptr, size_t Bytes);
33 void Heap_Deallocate(void *Ptr);
35 void Heap_Stats(void);
43 void Heap_Install(void)
45 gHeapStart = (void*)MM_KHEAP_BASE;
46 gHeapEnd = (void*)MM_KHEAP_BASE;
47 Heap_Extend(HEAP_INIT_SIZE);
51 * \fn void *Heap_Extend(int Bytes)
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 if( (tVAddr)gHeapEnd + ((Bytes+0xFFF)&~0xFFF) > MM_KHEAP_MAX ) {
66 Bytes = MM_KHEAP_MAX - (tVAddr)gHeapEnd;
70 // Heap expands in pages
71 for(i=0;i<(Bytes+0xFFF)>>12;i++)
72 MM_Allocate( (tVAddr)gHeapEnd+(i<<12) );
78 head->Size = (Bytes+0xFFF)&~0xFFF;
79 head->Magic = MAGIC_FREE;
80 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
82 foot->Magic = MAGIC_FOOT;
84 return Heap_Merge(head); // Merge with previous block
88 * \fn void *Heap_Merge(tHeapHead *Head)
89 * \brief Merges two ajacent heap blocks
91 void *Heap_Merge(tHeapHead *Head)
97 //Log("Heap_Merge: (Head=%p)", Head);
99 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
100 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
103 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
104 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
105 && foot->Head->Magic == MAGIC_FREE) {
106 foot->Head->Size += Head->Size; // Increase size
107 thisFoot->Head = foot->Head; // Change backlink
108 Head->Magic = 0; // Clear old head
110 Head = foot->Head; // Save new head address
111 foot->Head = NULL; // Clear central footer
115 // Merge Right (Upwards)
116 head = (void*)( (Uint)Head + Head->Size );
117 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
119 Head->Size += head->Size;
120 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
121 foot->Head = Head; // Update Backlink
122 thisFoot->Head = NULL; // Clear old footer
124 head->Size = 0; // Clear old header
128 // Return new address
133 * \brief Allocate memory from the heap
134 * \param File Allocating source file
135 * \param Line Source line
136 * \param Bytes Size of region to allocate
138 void *Heap_Allocate(const char *File, int Line, size_t Bytes)
140 tHeapHead *head, *newhead;
141 tHeapFoot *foot, *newfoot;
142 tHeapHead *best = NULL;
143 Uint bestSize = 0; // Speed hack
147 Bytes = Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
148 Bytes = 1UUL << LOG2(Bytes);
150 Bytes = (Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
157 for( head = gHeapStart;
158 (Uint)head < (Uint)gHeapEnd;
159 head = (void*)((Uint)head + head->Size)
164 if( head->Size != 1UUL << LOG2(head->Size) ) {
166 if( head->Size & (MIN_SIZE-1) ) {
168 RELEASE(&glHeap); // Release spinlock
170 Log_Warning("Heap", "Size of heap address %p is invalid not aligned (0x%x)", head, head->Size);
176 // Check if allocated
177 if(head->Magic == MAGIC_USED) continue;
179 if(head->Magic != MAGIC_FREE) {
180 RELEASE(&glHeap); // Release spinlock
182 Log_Warning("Heap", "Magic of heap address %p is invalid (0x%x)", head, head->Magic);
189 if(head->Size < Bytes) continue;
192 if(head->Size == Bytes) {
193 head->Magic = MAGIC_USED;
196 RELEASE(&glHeap); // Release spinlock
198 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", head->Data, head->Size, __builtin_return_address(0));
206 bestSize = head->Size;
209 // or check if the block is the best size
210 if(bestSize > head->Size) {
212 bestSize = head->Size;
217 // If no block large enough is found, create one
220 best = Heap_Extend( Bytes );
223 RELEASE(&glHeap); // Release spinlock
227 if(best->Size == Bytes) {
228 best->Magic = MAGIC_USED; // Mark block as used
231 RELEASE(&glHeap); // Release spinlock
233 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", best->Data, best->Size, __builtin_return_address(0));
240 newhead = (void*)( (Uint)best + Bytes );
241 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
242 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
244 newfoot->Head = best; // Create new footer
245 newfoot->Magic = MAGIC_FOOT;
246 newhead->Size = best->Size - Bytes; // Create new header
247 newhead->Magic = MAGIC_FREE;
248 foot->Head = newhead; // Update backlink in old footer
249 best->Size = Bytes; // Update size in old header
250 best->Magic = MAGIC_USED; // Mark block as used
254 RELEASE(&glHeap); // Release spinlock
256 Log_Debug("Heap", "newhead(%p)->Size = 0x%x", newhead, newhead->Size);
257 Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
258 best->Data, best->Size, File, Line);
264 * \fn void Heap_Deallocate(void *Ptr)
265 * \brief Free an allocated memory block
267 void Heap_Deallocate(void *Ptr)
273 Log_Log("Heap", "free: Ptr = %p", Ptr);
274 Log_Log("Heap", "free: Returns to %p", __builtin_return_address(0));
278 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
279 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
284 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
286 Log_Warning("Heap", "free - Passed a non-heap address (%p < %p < %p)\n",
287 gHeapStart, Ptr, gHeapEnd);
291 // Check memory block - Header
292 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
293 if(head->Magic == MAGIC_FREE) {
294 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
297 if(head->Magic != MAGIC_USED) {
298 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
299 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
303 // Check memory block - Footer
304 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
305 if(foot->Head != head) {
306 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
307 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
310 if(foot->Magic != MAGIC_FOOT) {
311 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
312 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
320 head->Magic = MAGIC_FREE;
330 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
332 tHeapHead *head = (void*)( (Uint)__ptr-8 );
335 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
337 // Check for reallocating NULL
338 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
340 // Check if resize is needed
341 if(newSize <= head->Size) return __ptr;
343 // Check if next block is free
344 nextHead = (void*)( (Uint)head + head->Size );
346 // Extend into next block
347 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
349 Uint size = nextHead->Size + head->Size;
350 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
352 if(size == newSize) {
353 head->Size = newSize;
361 // Create a new heap block
362 nextHead = (void*)( (Uint)head + newSize );
363 nextHead->Size = size - newSize;
364 nextHead->Magic = MAGIC_FREE;
365 foot->Head = nextHead; // Edit 2nd footer
366 head->Size = newSize; // Edit first header
370 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
372 foot->Magic = MAGIC_FOOT;
377 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
378 nextHead = foot->Head;
379 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
381 Uint size = nextHead->Size + head->Size;
382 // Inexact fit, split things up
386 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
393 // Set 1st (new/lower) header
394 nextHead->Magic = MAGIC_USED;
395 nextHead->Size = newSize;
396 nextHead->File = File;
397 nextHead->Line = Line;
398 // Get 2nd (old) footer
399 foot = (void*)( (Uint)nextHead + newSize );
400 foot->Head = nextHead;
401 // Save old data size
402 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
407 memcpy(nextHead->Data, __ptr, oldDataSize);
409 return nextHead->Data;
411 // On to the expensive then
415 nextHead = Heap_Allocate( File, Line, __size );
417 nextHead->File = File;
418 nextHead->Line = Line;
423 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
428 return nextHead->Data;
432 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t size)
433 * \brief Allocate and Zero a buffer in memory
434 * \param File Allocating file
435 * \param Line Line of allocation
436 * \param size Size of the allocation
438 void *Heap_AllocateZero(const char *File, int Line, size_t size)
440 void *ret = Heap_Allocate(File, Line, size);
441 if(ret == NULL) return NULL;
443 memset( ret, 0, size );
449 * \fn int Heap_IsHeapAddr(void *Ptr)
450 * \brief Checks if an address is a heap pointer
452 int Heap_IsHeapAddr(void *Ptr)
455 if((Uint)Ptr < (Uint)gHeapStart) return 0;
456 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
457 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
459 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
460 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
469 tHeapHead *head, *badHead;
473 while( (Uint)head < (Uint)gHeapEnd )
475 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
476 Log_Log("Heap", "%p (0x%llx): 0x%08lx %4C",
477 head, MM_GetPhysAddr((Uint)head), head->Size, &head->Magic);
478 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
480 Log_Log("Heap", "%sowned by %s:%i",
481 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
485 // Sanity Check Header
486 if(head->Size == 0) {
487 Log_Warning("Heap", "HALTED - Size is zero");
490 if(head->Size & (MIN_SIZE-1)) {
491 Log_Warning("Heap", "HALTED - Size is malaligned");
494 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
495 Log_Warning("Heap", "HALTED - Head Magic is Bad");
500 if(foot->Magic != MAGIC_FOOT) {
501 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
504 if(head != foot->Head) {
505 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
509 // All OK? Go to next
510 head = foot->NextHead;
513 // Check for a bad return
514 if( (tVAddr)head >= (tVAddr)gHeapEnd )
519 Log_Log("Heap", "==== Going Backwards ==== (from %p)", badHead);
522 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
524 while( (tVAddr)head >= (tVAddr)badHead )
526 Log_Log("Heap", "%p (0x%llx): 0x%08lx %4C",
527 head, MM_GetPhysAddr((Uint)head), head->Size, &head->Magic);
528 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
530 Log_Log("Heap", "%sowned by %s:%i",
531 (head->Magic!=MAGIC_USED?"was ":""),
532 head->File, head->Line);
535 // Sanity Check Header
536 if(head->Size == 0) {
537 Log_Warning("Heap", "HALTED - Size is zero");
540 if(head->Size & (MIN_SIZE-1)) {
541 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
544 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
545 Log_Warning("Heap", "HALTED - Head Magic is Bad");
550 if(foot->Magic != MAGIC_FOOT) {
551 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
554 if(head != foot->Head) {
555 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
559 if(head == badHead) break;
561 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
563 Log_Debug("Heap", "head=%p", head);
569 void Heap_Stats(void)
576 int maxAlloc=0, minAlloc=-1;
577 int avgAlloc, frag, overhead;
579 for(head = gHeapStart;
580 (Uint)head < (Uint)gHeapEnd;
581 head = (void*)( (Uint)head + head->Size )
585 totalBytes += head->Size;
586 if( head->Magic == MAGIC_FREE )
589 freeBytes += head->Size;
591 else if( head->Magic == MAGIC_USED) {
592 if(maxAlloc < head->Size) maxAlloc = head->Size;
593 if(minAlloc == -1 || minAlloc > head->Size)
594 minAlloc = head->Size;
597 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
601 // Print the block info?
603 Log_Debug("Heap", "%p - 0x%x Owned by %s:%i",
604 head, head->Size, head->File, head->Line);
608 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
609 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
610 frag = (nFree-1)*10000/nBlocks;
611 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
612 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
613 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
614 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
615 avgAlloc, overhead/100, overhead%100
617 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
620 // Scan and get distribution
626 } sizeCounts[nBlocks];
629 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
631 for(head = gHeapStart;
632 (Uint)head < (Uint)gHeapEnd;
633 head = (void*)( (Uint)head + head->Size )
636 for( i = 0; i < nBlocks; i ++ ) {
637 if( sizeCounts[i].Size == 0 )
639 if( sizeCounts[i].Size == head->Size )
642 // Should never reach this part (in a non-concurrent case)
643 if( i == nBlocks ) continue;
644 sizeCounts[i].Size = head->Size;
645 sizeCounts[i].Count ++;
647 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
648 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
650 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
651 // sizeCounts[i].Size, sizeCounts[i].Count);
655 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
657 Log("Heap_Stats: 0x%x - %i blocks",
658 sizeCounts[i].Size, sizeCounts[i].Count
667 EXPORT(Heap_Allocate);
668 EXPORT(Heap_AllocateZero);
669 EXPORT(Heap_Reallocate);
670 EXPORT(Heap_Deallocate);
671 EXPORT(Heap_IsHeapAddr);