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 ++ )
74 if( !MM_Allocate( (tVAddr)gHeapEnd+(i<<12) ) )
76 Warning("OOM - Heap_Extend");
82 gHeapEnd = (Uint8*)gHeapEnd + (i << 12);
85 head->Size = (Bytes+0xFFF)&~0xFFF;
86 head->Magic = MAGIC_FREE;
87 foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
89 foot->Magic = MAGIC_FOOT;
91 return Heap_Merge(head); // Merge with previous block
95 * \fn void *Heap_Merge(tHeapHead *Head)
96 * \brief Merges two ajacent heap blocks
98 void *Heap_Merge(tHeapHead *Head)
104 //Log("Heap_Merge: (Head=%p)", Head);
106 thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
107 if((Uint)thisFoot > (Uint)gHeapEnd) return NULL;
110 foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
111 if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > (Uint)gHeapStart)
112 && foot->Head->Magic == MAGIC_FREE) {
113 foot->Head->Size += Head->Size; // Increase size
114 thisFoot->Head = foot->Head; // Change backlink
115 Head->Magic = 0; // Clear old head
117 Head = foot->Head; // Save new head address
118 foot->Head = NULL; // Clear central footer
122 // Merge Right (Upwards)
123 head = (void*)( (Uint)Head + Head->Size );
124 if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
126 Head->Size += head->Size;
127 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
128 foot->Head = Head; // Update Backlink
129 thisFoot->Head = NULL; // Clear old footer
131 head->Size = 0; // Clear old header
135 // Return new address
140 * \brief Allocate memory from the heap
141 * \param File Allocating source file
142 * \param Line Source line
143 * \param Bytes Size of region to allocate
145 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
147 tHeapHead *head, *newhead;
148 tHeapFoot *foot, *newfoot;
149 tHeapHead *best = NULL;
150 Uint bestSize = 0; // Speed hack
154 //return NULL; // TODO: Return a known un-mapped range.
160 Bytes = __Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot);
161 Bytes = 1UUL << LOG2(__Bytes);
163 Bytes = (__Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
167 Mutex_Acquire(&glHeap);
170 for( head = gHeapStart;
171 (Uint)head < (Uint)gHeapEnd;
172 head = (void*)((Uint)head + head->Size)
177 if( head->Size != 1UUL << LOG2(head->Size) ) {
179 if( head->Size & (MIN_SIZE-1) ) {
181 Mutex_Release(&glHeap); // Release spinlock
183 Log_Warning("Heap", "Size of heap address %p is invalid not aligned (0x%x)", head, head->Size);
189 // Check if allocated
190 if(head->Magic == MAGIC_USED) continue;
192 if(head->Magic != MAGIC_FREE) {
193 Mutex_Release(&glHeap); // Release spinlock
195 Log_Warning("Heap", "Magic of heap address %p is invalid (0x%x)", head, head->Magic);
202 if(head->Size < Bytes) continue;
205 if(head->Size == Bytes) {
206 head->Magic = MAGIC_USED;
209 Mutex_Release(&glHeap); // Release spinlock
211 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", head->Data, head->Size, __builtin_return_address(0));
219 bestSize = head->Size;
222 // or check if the block is the best size
223 if(bestSize > head->Size) {
225 bestSize = head->Size;
230 // If no block large enough is found, create one
233 best = Heap_Extend( Bytes );
236 Mutex_Release(&glHeap); // Release spinlock
240 if(best->Size == Bytes) {
241 best->Magic = MAGIC_USED; // Mark block as used
244 Mutex_Release(&glHeap); // Release spinlock
246 Log("[Heap ] Malloc'd %p (%i bytes), returning to %p", best->Data, best->Size, __builtin_return_address(0));
253 newhead = (void*)( (Uint)best + Bytes );
254 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
255 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
257 newfoot->Head = best; // Create new footer
258 newfoot->Magic = MAGIC_FOOT;
259 newhead->Size = best->Size - Bytes; // Create new header
260 newhead->Magic = MAGIC_FREE;
261 foot->Head = newhead; // Update backlink in old footer
262 best->Size = Bytes; // Update size in old header
263 best->ValidSize = __Bytes;
264 best->Magic = MAGIC_USED; // Mark block as used
268 Mutex_Release(&glHeap); // Release spinlock
270 Log_Debug("Heap", "newhead(%p)->Size = 0x%x", newhead, newhead->Size);
271 Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
272 best->Data, best->Size, File, Line);
278 * \fn void Heap_Deallocate(void *Ptr)
279 * \brief Free an allocated memory block
281 void Heap_Deallocate(void *Ptr)
287 Log_Log("Heap", "free: Ptr = %p", Ptr);
288 Log_Log("Heap", "free: Returns to %p", __builtin_return_address(0));
291 // INVLPTR is returned from Heap_Allocate when the allocation
293 if( Ptr == INVLPTR ) return;
296 if( (Uint)Ptr & (sizeof(Uint)-1) ) {
297 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
302 if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
304 Log_Warning("Heap", "free - Passed a non-heap address (%p < %p < %p)\n",
305 gHeapStart, Ptr, gHeapEnd);
309 // Check memory block - Header
310 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
311 if(head->Magic == MAGIC_FREE) {
312 Log_Warning("Heap", "free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
315 if(head->Magic != MAGIC_USED) {
316 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
317 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
321 // Check memory block - Footer
322 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
323 if(foot->Head != head) {
324 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
325 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
328 if(foot->Magic != MAGIC_FOOT) {
329 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)", head, &foot->Magic, foot->Magic);
330 Log_Notice("Heap", "Allocated %s:%i", head->File, head->Line);
335 Mutex_Acquire( &glHeap );
338 head->Magic = MAGIC_FREE;
346 Mutex_Release( &glHeap );
350 * \brief Increase/Decrease the size of an allocation
351 * \param File Calling File
352 * \param Line Calling Line
353 * \param __ptr Old memory
354 * \param __size New Size
356 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
358 tHeapHead *head = (void*)( (Uint)__ptr-sizeof(tHeapHead) );
361 Uint newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+MIN_SIZE-1)&~(MIN_SIZE-1);
363 // Check for reallocating NULL
364 if(__ptr == NULL) return Heap_Allocate(File, Line, __size);
366 // Check if resize is needed
367 if(newSize <= head->Size) return __ptr;
369 // Check if next block is free
370 nextHead = (void*)( (Uint)head + head->Size );
372 // Extend into next block
373 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
375 Uint size = nextHead->Size + head->Size;
376 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
378 if(size == newSize) {
379 head->Size = newSize;
380 head->ValidSize = __size;
388 // Create a new heap block
389 nextHead = (void*)( (Uint)head + newSize );
390 nextHead->Size = size - newSize;
391 nextHead->Magic = MAGIC_FREE;
392 foot->Head = nextHead; // Edit 2nd footer
393 head->Size = newSize; // Edit first header
396 head->ValidSize = __size;
398 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
400 foot->Magic = MAGIC_FOOT;
405 foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
406 nextHead = foot->Head;
407 if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
409 Uint size = nextHead->Size + head->Size;
410 // Inexact fit, split things up
414 Warning("[Heap ] TODO: Space efficient realloc when new size is smaller");
421 // Set 1st (new/lower) header
422 nextHead->Magic = MAGIC_USED;
423 nextHead->Size = newSize;
424 nextHead->File = File;
425 nextHead->Line = Line;
426 nextHead->ValidSize = __size;
427 // Get 2nd (old) footer
428 foot = (void*)( (Uint)nextHead + newSize );
429 foot->Head = nextHead;
430 // Save old data size
431 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
436 memcpy(nextHead->Data, __ptr, oldDataSize);
438 return nextHead->Data;
440 // On to the expensive then
444 nextHead = Heap_Allocate( File, Line, __size );
446 nextHead->File = File;
447 nextHead->Line = Line;
448 nextHead->ValidSize = __size;
453 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
458 return nextHead->Data;
462 * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
463 * \brief Allocate and Zero a buffer in memory
464 * \param File Allocating file
465 * \param Line Line of allocation
466 * \param Bytes Size of the allocation
468 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
470 void *ret = Heap_Allocate(File, Line, Bytes);
471 if(ret == NULL) return NULL;
473 memset( ret, 0, Bytes );
479 * \fn int Heap_IsHeapAddr(void *Ptr)
480 * \brief Checks if an address is a heap pointer
482 int Heap_IsHeapAddr(void *Ptr)
485 if((Uint)Ptr < (Uint)gHeapStart) return 0;
486 if((Uint)Ptr > (Uint)gHeapEnd) return 0;
487 if((Uint)Ptr & (sizeof(Uint)-1)) return 0;
489 head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
490 if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
498 void Heap_Validate(void)
506 tHeapHead *head, *badHead;
507 tHeapFoot *foot = NULL;
510 while( (Uint)head < (Uint)gHeapEnd )
512 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
514 Log_Log("Heap", "%p (0x%llx): 0x%08lx (%i) %4C",
515 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
516 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
518 Log_Log("Heap", "%sowned by %s:%i",
519 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
523 // Sanity Check Header
524 if(head->Size == 0) {
525 Log_Warning("Heap", "HALTED - Size is zero");
528 if(head->Size & (MIN_SIZE-1)) {
529 Log_Warning("Heap", "HALTED - Size is malaligned");
532 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
533 Log_Warning("Heap", "HALTED - Head Magic is Bad");
538 if(foot->Magic != MAGIC_FOOT) {
539 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
542 if(head != foot->Head) {
543 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
551 // All OK? Go to next
552 head = foot->NextHead;
555 // If the heap is valid, ok!
556 if( (tVAddr)head == (tVAddr)gHeapEnd )
559 // Check for a bad return
560 if( (tVAddr)head >= (tVAddr)gHeapEnd )
564 Log_Log("Heap", "%p (0x%llx): 0x%08lx (%i) %4C",
565 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
566 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
568 Log_Log("Heap", "%sowned by %s:%i",
569 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
578 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
579 Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
581 while( (tVAddr)head >= (tVAddr)badHead )
583 Log_Log("Heap", "%p (0x%llx): 0x%08lx %i %4C",
584 head, MM_GetPhysAddr((Uint)head), head->Size, head->ValidSize, &head->Magic);
585 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
587 Log_Log("Heap", "%sowned by %s:%i",
588 (head->Magic!=MAGIC_USED?"was ":""),
589 head->File, head->Line);
592 // Sanity Check Header
593 if(head->Size == 0) {
594 Log_Warning("Heap", "HALTED - Size is zero");
597 if(head->Size & (MIN_SIZE-1)) {
598 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
601 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
602 Log_Warning("Heap", "HALTED - Head Magic is Bad");
607 if(foot->Magic != MAGIC_FOOT) {
608 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
611 if(head != foot->Head) {
612 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
616 if(head == badHead) break;
618 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
620 Log_Debug("Heap", "head=%p", head);
623 Panic("Heap_Dump - Heap is corrupted, kernel panic!");
628 void Heap_Stats(void)
635 int maxAlloc=0, minAlloc=-1;
636 int avgAlloc, frag, overhead;
638 for(head = gHeapStart;
639 (Uint)head < (Uint)gHeapEnd;
640 head = (void*)( (Uint)head + head->Size )
644 totalBytes += head->Size;
645 if( head->Magic == MAGIC_FREE )
648 freeBytes += head->Size;
650 else if( head->Magic == MAGIC_USED) {
651 if(maxAlloc < head->Size) maxAlloc = head->Size;
652 if(minAlloc == -1 || minAlloc > head->Size)
653 minAlloc = head->Size;
656 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
660 // Print the block info?
662 Log_Debug("Heap", "%p - 0x%x (%i) Owned by %s:%i",
663 head, head->Size, head->ValidSize, head->File, head->Line);
667 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
668 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
669 frag = (nFree-1)*10000/nBlocks;
670 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
671 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
672 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
673 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
674 avgAlloc, overhead/100, overhead%100
676 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
679 // Scan and get distribution
685 } sizeCounts[nBlocks];
688 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
690 for(head = gHeapStart;
691 (Uint)head < (Uint)gHeapEnd;
692 head = (void*)( (Uint)head + head->Size )
695 for( i = 0; i < nBlocks; i ++ ) {
696 if( sizeCounts[i].Size == 0 )
698 if( sizeCounts[i].Size == head->Size )
701 // Should never reach this part (in a non-concurrent case)
702 if( i == nBlocks ) continue;
703 sizeCounts[i].Size = head->Size;
704 sizeCounts[i].Count ++;
706 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
707 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
709 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
710 // sizeCounts[i].Size, sizeCounts[i].Count);
714 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
716 Log("Heap_Stats: 0x%x - %i blocks",
717 sizeCounts[i].Size, sizeCounts[i].Count
726 EXPORT(Heap_Allocate);
727 EXPORT(Heap_AllocateZero);
728 EXPORT(Heap_Reallocate);
729 EXPORT(Heap_Deallocate);
730 EXPORT(Heap_IsHeapAddr);