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) [at paddr 0x%x]",
186 head, head->Size, MM_GetPhysAddr(&head->Size));
192 // Check if allocated
193 if(head->Magic == MAGIC_USED) continue;
195 if(head->Magic != MAGIC_FREE) {
196 Mutex_Release(&glHeap); // Release spinlock
198 Log_Warning("Heap", "Magic of heap address %p is invalid (%p = 0x%x)",
199 head, &head->Magic, head->Magic);
206 if(head->Size < Bytes) continue;
209 if(head->Size == Bytes) {
210 head->Magic = MAGIC_USED;
213 head->ValidSize = __Bytes;
214 head->AllocateTime = now();
215 Mutex_Release(&glHeap); // Release spinlock
217 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %p",
218 head->Data, head->Size, __builtin_return_address(0));
226 bestSize = head->Size;
229 // or check if the block is the best size
230 if(bestSize > head->Size) {
232 bestSize = head->Size;
237 // If no block large enough is found, create one
240 best = Heap_Extend( Bytes );
243 Mutex_Release(&glHeap); // Release spinlock
247 if(best->Size == Bytes) {
248 best->Magic = MAGIC_USED; // Mark block as used
251 best->ValidSize = __Bytes;
252 best->AllocateTime = now();
253 Mutex_Release(&glHeap); // Release spinlock
255 Debug("[Heap ] Malloc'd %p (%i bytes), returning to %s:%i", best->Data, best->Size, File, Line);
262 newhead = (void*)( (Uint)best + Bytes );
263 newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
264 foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
266 newfoot->Head = best; // Create new footer
267 newfoot->Magic = MAGIC_FOOT;
268 newhead->Size = best->Size - Bytes; // Create new header
269 newhead->Magic = MAGIC_FREE;
270 foot->Head = newhead; // Update backlink in old footer
271 best->Size = Bytes; // Update size in old header
272 best->ValidSize = __Bytes;
273 best->Magic = MAGIC_USED; // Mark block as used
276 best->AllocateTime = now();
278 Mutex_Release(&glHeap); // Release spinlock
280 Debug("[Heap ] Malloc'd %p (0x%x bytes), returning to %s:%i",
281 best->Data, best->Size, File, Line);
287 * \brief Free an allocated memory block
289 void Heap_Deallocate(void *Ptr)
291 tHeapHead *head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
294 // INVLPTR is returned from Heap_Allocate when the allocation
296 if( Ptr == INVLPTR ) return;
299 Debug("[Heap ] free: %p freed by %p (%i old)", Ptr, __builtin_return_address(0), now()-head->AllocateTime);
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 by %p (%p < %p < %p)",
312 __builtin_return_address(0), 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;
515 static int in_heap_dump;
517 if( in_heap_dump ) return;
522 while( (Uint)head < (Uint)gHeapEnd )
524 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
526 Log_Log("Heap", "%p (0x%P): 0x%08x (%i) %4C",
527 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
528 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
530 Log_Log("Heap", "%sowned by %s:%i",
531 (head->Magic==MAGIC_FREE?"was ":""), 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", "HALTED - Size is malaligned");
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");
563 // All OK? Go to next
564 head = foot->NextHead;
567 // If the heap is valid, ok!
568 if( (tVAddr)head == (tVAddr)gHeapEnd ) {
573 // Check for a bad return
574 if( (tVAddr)head >= (tVAddr)gHeapEnd ) {
580 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
581 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
583 Log_Log("Heap", "Foot %p = {Head:%p,Magic:%4C}", foot, foot->Head, &foot->Magic);
585 Log_Log("Heap", "%sowned by %s:%i",
586 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
595 foot = (void*)( (tVAddr)gHeapEnd - sizeof(tHeapFoot) );
596 Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
598 while( (tVAddr)head >= (tVAddr)badHead )
600 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
601 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
602 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
604 Log_Log("Heap", "%sowned by %s:%i",
605 (head->Magic!=MAGIC_USED?"was ":""),
606 head->File, head->Line);
609 // Sanity Check Header
610 if(head->Size == 0) {
611 Log_Warning("Heap", "HALTED - Size is zero");
614 if(head->Size & (MIN_SIZE-1)) {
615 Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
618 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
619 Log_Warning("Heap", "HALTED - Head Magic is Bad");
624 if(foot->Magic != MAGIC_FOOT) {
625 Log_Warning("Heap", "HALTED - Foot Magic is Bad");
628 if(head != foot->Head) {
629 Log_Warning("Heap", "HALTED - Footer backlink is invalid");
633 if(head == badHead) break;
635 foot = (void*)( (tVAddr)head - sizeof(tHeapFoot) );
637 Log_Debug("Heap", "head=%p", head);
640 Panic("Heap_Dump - Heap is corrupted, kernel panic!");
645 void Heap_Stats(void)
652 int maxAlloc=0, minAlloc=-1;
653 int avgAlloc, frag, overhead;
655 for(head = gHeapStart;
656 (Uint)head < (Uint)gHeapEnd;
657 head = (void*)( (Uint)head + head->Size )
661 totalBytes += head->Size;
662 if( head->Magic == MAGIC_FREE )
665 freeBytes += head->Size;
667 else if( head->Magic == MAGIC_USED) {
668 if(maxAlloc < head->Size) maxAlloc = head->Size;
669 if(minAlloc == -1 || minAlloc > head->Size)
670 minAlloc = head->Size;
673 Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
677 // Print the block info?
679 if( head->Magic == MAGIC_FREE )
680 Log_Debug("Heap", "%p (%P) - 0x%x free",
681 head->Data, MM_GetPhysAddr(&head->Data), head->Size);
683 Log_Debug("Heap", "%p (%P) - 0x%x (%i) Owned by %s:%i (%lli ms old)",
684 head->Data, MM_GetPhysAddr(&head->Data), head->Size, head->ValidSize, head->File, head->Line,
685 now() - head->AllocateTime
690 Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
691 Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
693 frag = (nFree-1)*10000/nBlocks;
696 Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
700 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
702 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
705 Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
706 avgAlloc, overhead/100, overhead%100
708 Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes",
711 // Scan and get distribution
718 } sizeCounts[nBlocks];
721 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
723 for(head = gHeapStart;
724 (Uint)head < (Uint)gHeapEnd;
725 head = (void*)( (Uint)head + head->Size )
728 for( i = 0; i < nBlocks; i ++ ) {
729 if( sizeCounts[i].Size == 0 )
731 if( sizeCounts[i].Size == head->Size )
734 // Should never reach this part (in a non-concurrent case)
735 if( i == nBlocks ) continue;
736 sizeCounts[i].Size = head->Size;
737 sizeCounts[i].Count ++;
739 //Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
740 // head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
742 //Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
743 // sizeCounts[i].Size, sizeCounts[i].Count);
747 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
749 Log("Heap_Stats: 0x%x - %i blocks",
750 sizeCounts[i].Size, sizeCounts[i].Count
759 EXPORT(Heap_Allocate);
760 EXPORT(Heap_AllocateZero);
761 EXPORT(Heap_Reallocate);
762 EXPORT(Heap_Deallocate);
763 EXPORT(Heap_IsHeapAddr);