Kernel/heap - Clean up a little, fix corruption in realloc, add hacky watchpoints
[tpg/acess2.git] / KernelLand / Kernel / heap.c
1 /*
2  * Acess2 Kernel
3  * - By John Hodge (thePowersGang)
4  *
5  * heap.c
6  * - Dynamic memory allocation
7  */
8 #include <acess.h>
9 #include <mm_virt.h>
10 #include <heap_int.h>
11 #include <limits.h>
12 #include <debug_hooks.h>
13
14 #define WARNINGS        1       // Warn and dump on heap errors
15 #define DEBUG_TRACE     0       // Enable tracing of allocations
16 #define VERBOSE_DUMP    0       // Set to 1 to enable a verbose dump when heap errors are encountered
17 #define VALIDATE_ON_ALLOC       1       // Set to 1 to enable validation of the heap on all malloc() calls
18
19 // === CONSTANTS ===
20 #define HEAP_INIT_SIZE  0x8000  // 32 KiB
21 #define MIN_SIZE        (sizeof(void*))*8       // 8 Machine Words
22 #define POW2_SIZES      0
23 #define COMPACT_HEAP    0       // Use 4 byte header?
24 #define FIRST_FIT       0
25
26 //#define       MAGIC_FOOT      0x2ACE5505
27 //#define       MAGIC_FREE      0xACE55000
28 //#define       MAGIC_USED      0x862B0505      // MAGIC_FOOT ^ MAGIC_FREE
29 #define MAGIC_FOOT      0x544F4F46      // 'FOOT'
30 #define MAGIC_FREE      0x45455246      // 'FREE'
31 #define MAGIC_USED      0x44455355      // 'USED'
32
33 // === PROTOTYPES ===
34 void    Heap_Install(void);
35 void    *Heap_Extend(size_t Bytes);
36 void    *Heap_Merge(tHeapHead *Head);
37 static const size_t     Heap_int_GetBlockSize(size_t AllocSize);
38 //void  *Heap_Allocate(const char *File, int Line, size_t Bytes);
39 //void  *Heap_AllocateZero(const char *File, int Line, size_t Bytes);
40 //void  *Heap_Reallocate(const char *File, int Line, void *Ptr, size_t Bytes);
41 //void  Heap_Deallocate(const char *File, int Line, void *Ptr);
42  int    Heap_int_ApplyWatchpont(void *Addr, bool Enabled);
43 void    Heap_int_WatchBlock(tHeapHead *Head, bool Enabled);
44 //void  Heap_Dump(void);
45 void    Heap_ValidateDump(int bVerbose);
46 //void  Heap_Stats(void);
47
48 // === GLOBALS ===
49 tMutex  glHeap;
50 tHeapHead       *gHeapStart;
51 tHeapHead       *gHeapEnd;
52
53 // === CODE ===
54 void Heap_Install(void)
55 {
56         gHeapStart = (void*)MM_KHEAP_BASE;
57         gHeapEnd   = gHeapStart;
58         Heap_Extend(HEAP_INIT_SIZE);
59 }
60
61 static inline tHeapHead *Heap_NextHead(tHeapHead *Head) {
62         return (void*)( (char*)Head + Head->Size );
63 }
64 static inline tHeapFoot *Heap_ThisFoot(tHeapHead *Head) {
65         return (void*)( (char*)Head + Head->Size - sizeof(tHeapFoot) );
66 }
67 static inline tHeapFoot *Heap_PrevFoot(tHeapHead *Head) {
68         //ASSERT(Head != gHeapStart);
69         return (void*)( (char*)Head - sizeof(tHeapFoot) );
70 }
71
72 /**
73  * \brief Extend the size of the heap
74  */
75 void *Heap_Extend(size_t Bytes)
76 {
77         //Debug("Heap_Extend(0x%x)", Bytes);
78         
79         // Bounds Check
80         if( gHeapEnd == (tHeapHead*)MM_KHEAP_MAX ) {
81                 Log_Error("Heap", "Heap limit reached (%p)", (void*)MM_KHEAP_MAX);
82                 return NULL;
83         }
84         
85         if( Bytes == 0 ) {
86                 Log_Warning("Heap", "Heap_Extend called with Bytes=%i", Bytes);
87                 return NULL;
88         }
89         
90         const Uint      pages = (Bytes + 0xFFF) >> 12;
91         tHeapHead       *new_end = (void*)( (tVAddr)gHeapEnd + (pages << 12) );
92         // Bounds Check
93         if( new_end > (tHeapHead*)MM_KHEAP_MAX )
94         {
95                 Log_Error("Heap", "Heap limit exceeded (%p)", (void*)new_end);
96                 // TODO: Clip allocation to available space, and have caller check returned block
97                 return NULL;
98         }
99         
100         // Heap expands in pages
101         for( Uint i = 0; i < pages; i ++ )
102         {
103                 if( !MM_Allocate( (tPage*)gHeapEnd + i ) )
104                 {
105                         Warning("OOM - Heap_Extend (%i bytes)");
106                         Heap_Dump();
107                         return NULL;
108                 }
109         }
110         
111         // Increase heap end
112         tHeapHead       *head = gHeapEnd;
113         gHeapEnd = new_end;
114         
115         // Create Block
116         head->Size = (Bytes+0xFFF)&~0xFFF;
117         head->Magic = MAGIC_FREE;
118         tHeapFoot *foot = Heap_ThisFoot(head);
119         foot->Head = head;
120         foot->Magic = MAGIC_FOOT;
121         
122         return Heap_Merge(head);        // Merge with previous block
123 }
124
125 /**
126  * \brief Merges two adjacent heap blocks
127  */
128 void *Heap_Merge(tHeapHead *Head)
129 {
130         //Log("Heap_Merge: (Head=%p)", Head);
131         tHeapFoot *thisFoot = Heap_ThisFoot(Head);
132         
133         ASSERT( Heap_NextHead(Head) <= gHeapEnd );
134         
135         // Merge Left (Down)
136         tHeapFoot *foot = Heap_PrevFoot(Head);
137         if( Head > gHeapStart && foot->Head->Magic == MAGIC_FREE)
138         {
139                 foot->Head->Size += Head->Size; // Increase size
140                 thisFoot->Head = foot->Head;    // Change backlink
141                 Head->Magic = 0;        // Clear old head
142                 Head->Size = 0;
143                 Head = foot->Head;      // Save new head address
144                 foot->Head = NULL;      // Clear central footer
145                 foot->Magic = 0;
146         }
147         
148         // Merge Right (Upwards)
149         tHeapHead *nexthead = Heap_NextHead(Head);
150         if(nexthead < gHeapEnd && nexthead->Magic == MAGIC_FREE)
151         {
152                 Head->Size += nexthead->Size;
153                 foot = Heap_ThisFoot(Head);
154                 foot->Head = Head;      // Update Backlink
155                 thisFoot->Head = NULL;  // Clear old footer
156                 thisFoot->Magic = 0;
157                 nexthead->Size = 0;             // Clear old header
158                 nexthead->Magic = 0;
159         }
160         
161         // Return new address
162         return Head;
163 }
164
165 static const size_t Heap_int_GetBlockSize(size_t AllocSize)
166 {
167         size_t Bytes;
168         #if POW2_SIZES
169         Bytes = AllocSize + sizeof(tHeapHead) + sizeof(tHeapFoot);
170         Bytes = 1UUL << LOG2(Bytes);
171         #else
172         Bytes = (AllocSize + sizeof(tHeapHead) + sizeof(tHeapFoot) + MIN_SIZE-1) & ~(MIN_SIZE-1);
173         #endif
174         return Bytes;
175 }
176
177 /**
178  * \param File  Allocating source file
179  * \param Line  Source line
180  * \param __Bytes       Size of region to allocate
181  */
182 void *Heap_Allocate(const char *File, int Line, size_t __Bytes)
183 {
184         tHeapHead       *newhead;
185         tHeapFoot       *foot, *newfoot;
186         tHeapHead       *best = NULL;
187         Uint    bestSize = UINT_MAX;    // Speed hack
188         size_t  Bytes;
189
190         if( __Bytes == 0 ) {
191                 return NULL;    // TODO: Return a known un-mapped range.
192 //              return INVLPTR;
193         }
194
195         #if VALIDATE_ON_ALLOC
196         Heap_Validate();
197         #endif
198         
199         // Get required size
200         Bytes = Heap_int_GetBlockSize(__Bytes);
201         
202         // Lock Heap
203         Mutex_Acquire(&glHeap);
204         
205         // Traverse Heap
206         for( tHeapHead *head = gHeapStart; head < gHeapEnd; head = Heap_NextHead(head) )
207         {
208                 // Alignment Check
209                 #if POW2_SIZES
210                 if( head->Size != 1UUL << LOG2(head->Size) ) {
211                 #else
212                 if( head->Size & (MIN_SIZE-1) ) {
213                 #endif
214                         Mutex_Release(&glHeap); // Release spinlock
215                         #if WARNINGS
216                         Log_Warning("Heap", "Size of heap address %p is invalid"
217                                 " - not aligned (0x%x) [at paddr 0x%x]",
218                                 head, head->Size, MM_GetPhysAddr(&head->Size));
219                         Heap_ValidateDump(VERBOSE_DUMP);
220                         #endif
221                         return NULL;
222                 }
223                 if( head->Size < MIN_SIZE ) {
224                         Mutex_Release(&glHeap);
225                         #if WARNINGS
226                         Log_Warning("Heap", "Size of heap address %p is invalid"
227                                 " - Too small (0x%x) [at paddr 0x%x]",
228                                 head, head->Size, MM_GetPhysAddr(&head->Size));
229                         Heap_ValidateDump(VERBOSE_DUMP);
230                         #endif
231                         return NULL;
232                 }
233                 if( head->Size > (2<<30) ) {
234                         Mutex_Release(&glHeap);
235                         #if WARNINGS
236                         Log_Warning("Heap", "Size of heap address %p is invalid"
237                                 " - Over 2GiB (0x%x) [at paddr 0x%x]",
238                                 head, head->Size, MM_GetPhysAddr(&head->Size));
239                         Heap_ValidateDump(VERBOSE_DUMP);
240                         #endif
241                         return NULL;
242                 }
243                 
244                 // Check if allocated
245                 if(head->Magic == MAGIC_USED)   continue;
246                 // Error check
247                 if(head->Magic != MAGIC_FREE)   {
248                         Mutex_Release(&glHeap); // Release spinlock
249                         #if WARNINGS
250                         Log_Warning("Heap", "Magic of heap address %p is invalid (%p = 0x%x)",
251                                 head, &head->Magic, head->Magic);
252                         Heap_ValidateDump(VERBOSE_DUMP);
253                         #endif
254                         return NULL;
255                 }
256                 
257                 // Size check
258                 if(head->Size < Bytes)  continue;
259                 
260                 // Perfect fit
261                 if(head->Size == Bytes) {
262                         head->Magic = MAGIC_USED;
263                         head->File = File;
264                         head->Line = Line;
265                         head->ValidSize = __Bytes;
266                         head->AllocateTime = now();
267                         Mutex_Release(&glHeap); // Release spinlock
268                         #if DEBUG_TRACE
269                         Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
270                                 head->Data, head->Size, File, Line);
271                         #endif
272                         return head->Data;
273                 }
274                 
275                 // Break out of loop
276                 #if FIRST_FIT
277                 best = head;
278                 bestSize = head->Size;
279                 break;
280                 #else
281                 // or check if the block is the best size
282                 if(bestSize > head->Size) {
283                         best = head;
284                         bestSize = head->Size;
285                 }
286                 #endif
287         }
288         
289         // If no block large enough is found, create one
290         if(!best)
291         {
292                 best = Heap_Extend( Bytes );
293                 // Check for errors
294                 if(!best) {
295                         Warning("OOM when allocating 0x%x bytes", Bytes);
296                         Mutex_Release(&glHeap); // Release spinlock
297                         return NULL;
298                 }
299                 // Check size
300                 if(best->Size == Bytes) {
301                         best->Magic = MAGIC_USED;       // Mark block as used
302                         best->File = File;
303                         best->Line = Line;
304                         best->ValidSize = __Bytes;
305                         best->AllocateTime = now();
306                         Mutex_Release(&glHeap); // Release spinlock
307                         #if DEBUG_TRACE
308                         Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
309                                 best->Data, best->Size, File, Line);
310                         #endif
311                         return best->Data;
312                 }
313         }
314         
315         // Split Block
316         // - Save size for new block
317         size_t  newsize = best->Size - Bytes;
318         // - Allocate beginning of old block
319         best->Size = Bytes;             // Update size in old header
320         best->ValidSize = __Bytes;
321         best->Magic = MAGIC_USED;       // Mark block as used
322         best->File = File;
323         best->Line = Line;
324         best->AllocateTime = now();
325         // - Create a new foot on old block
326         newfoot = Heap_ThisFoot(best);
327         newfoot->Head = best;   // Create new footer
328         newfoot->Magic = MAGIC_FOOT;
329         // - Create a new header after resized old
330         newhead = Heap_NextHead(best);
331         newhead->Size = newsize;
332         newhead->Magic = MAGIC_FREE;
333         newhead->ValidSize = 0;
334         newhead->File = NULL;
335         newhead->Line = 0;
336         // - Update footer
337         foot = Heap_ThisFoot(newhead);
338         foot->Head = newhead;
339         
340         Mutex_Release(&glHeap); // Release spinlock
341         #if DEBUG_TRACE
342         Log_Debug("Heap", "Malloc'd %p (0x%x bytes), returning to %s:%i",
343                 best->Data, best->Size, File, Line);
344         #endif
345         return best->Data;
346 }
347
348 /**
349  * \brief Free an allocated memory block
350  */
351 void Heap_Deallocate(const char *File, int Line, void *Ptr)
352 {
353         // INVLPTR is returned from Heap_Allocate when the allocation
354         // size is zero.
355         if( Ptr == INVLPTR )    return;
356         
357         // Alignment Check
358         if( (tVAddr)Ptr % sizeof(void*) != 0 ) {
359                 Log_Warning("Heap", "free - Passed a non-aligned address (%p)", Ptr);
360                 return;
361         }
362         
363         // Sanity check
364         if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
365         {
366                 Log_Warning("Heap", "free - Passed a non-heap address by %p (%p < %p < %p)",
367                         __builtin_return_address(0), gHeapStart, Ptr, gHeapEnd);
368                 return;
369         }
370         
371         // Check memory block - Header
372         tHeapHead *head = (tHeapHead*)Ptr - 1;
373         if(head->Magic == MAGIC_FREE) {
374                 Log_Warning("Heap", "free - Passed a freed block (%p) by %s:%i (was freed by %s:%i)",
375                         head, File, Line,
376                         head->File, head->Line);
377                 Proc_PrintBacktrace();
378                 return;
379         }
380         if(head->Magic != MAGIC_USED) {
381                 Log_Warning("Heap", "free - Magic value is invalid (%p, 0x%x)", head, head->Magic);
382                 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
383                 return;
384         }
385         
386         // Check memory block - Footer
387         tHeapFoot *foot = Heap_ThisFoot(head);
388         if(foot->Head != head) {
389                 Log_Warning("Heap", "free - Footer backlink is incorrect (%p, 0x%x)", head, foot->Head);
390                 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
391                 return;
392         }
393         if(foot->Magic != MAGIC_FOOT) {
394                 Log_Warning("Heap", "free - Footer magic is invalid (%p, %p = 0x%x)",
395                         head, &foot->Magic, foot->Magic);
396                 Log_Notice("Heap", "Allocated by %s:%i", head->File, head->Line);
397                 return;
398         }
399         
400         #if DEBUG_TRACE
401         Log_Debug("Heap", "free: %p freed by %s:%i (%i old)",
402                 Ptr, File, Line, now()-head->AllocateTime);
403         #endif
404         
405         // Lock
406         Mutex_Acquire( &glHeap );
407
408         Heap_int_WatchBlock(head, false);
409
410         // Mark as free
411         head->Magic = MAGIC_FREE;
412         head->File = File;
413         head->Line = Line;
414         head->ValidSize = 0;
415         // Merge blocks
416         Heap_Merge( head );
417         
418         // Release
419         Mutex_Release( &glHeap );
420 }
421
422 /**
423  * \brief Increase/Decrease the size of an allocation
424  * \param File  Calling File
425  * \param Line  Calling Line
426  * \param __ptr Old memory
427  * \param __size        New Size
428  */
429 void *Heap_Reallocate(const char *File, int Line, void *__ptr, size_t __size)
430 {
431         tHeapHead       *head = (tHeapHead*)__ptr - 1;
432         tHeapHead       *nextHead;
433         tHeapFoot       *foot;
434         Uint    newSize = Heap_int_GetBlockSize(__size);
435         
436         // Check for reallocating NULL
437         if(__ptr == NULL)
438                 return Heap_Allocate(File, Line, __size);
439         
440         if( !Heap_IsHeapAddr(__ptr)) {
441                 Log_Error("Heap", "%s:%i passed non-heap address %p when reallocating to %zi",
442                         File, Line, __ptr, __size);
443                 return NULL;
444         }
445         
446         // Check if resize is needed
447         // TODO: Reduce size of block if needed
448         if(newSize <= head->Size) {
449                 #if DEBUG_TRACE
450                 Log_Debug("Heap", "realloc maintain %p (0x%x >= 0x%x), returning to %s:%i",
451                         head->Data, head->Size, newSize, File, Line);
452                 #endif
453                 return __ptr;
454         }
455
456         #if VALIDATE_ON_ALLOC
457         Heap_Validate();
458         #endif
459         
460         Heap_int_WatchBlock(head, false);
461         
462         // Check if next block is free
463         nextHead = Heap_NextHead(head);
464         
465         // Extend into next block
466         if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
467         {
468                 #if DEBUG_TRACE
469                 Log_Debug("Heap", "realloc expand %p (0x%x to 0x%x), returning to %s:%i",
470                         head->Data, head->Size, newSize, File, Line);
471                 #endif
472                 Uint    size = nextHead->Size + head->Size;
473                 foot = Heap_ThisFoot(nextHead);
474                 // Exact Fit
475                 if(size == newSize) {
476                         head->Size = newSize;
477                         head->ValidSize = __size;
478                         head->File = File;
479                         head->Line = Line;
480                         foot->Head = head;
481                         nextHead->Magic = 0;
482                         nextHead->Size = 0;
483                         return __ptr;
484                 }
485                 // Create a new heap block
486                 // - Update old with new information
487                 head->Size = newSize;
488                 head->File = File;      // Kinda counts as a new allocation
489                 head->Line = Line;
490                 head->ValidSize = __size;
491                 // - Create new footer
492                 foot = Heap_ThisFoot(head);
493                 foot->Head = head;
494                 foot->Magic = MAGIC_FOOT;
495                 // - Create new header
496                 nextHead = Heap_NextHead(head);
497                 nextHead->Size = size - newSize;
498                 nextHead->Magic = MAGIC_FREE;
499                 // - Update old footer
500                 Heap_ThisFoot(nextHead)->Head = nextHead;
501                 return __ptr;
502         }
503         
504         // Extend downwards?
505         foot = Heap_PrevFoot(head);
506         nextHead = foot->Head;
507         if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
508         {
509                 Uint    size = nextHead->Size + head->Size;
510                 // Inexact fit, split things up
511                 if(size > newSize)
512                 {
513                         // TODO: Handle splitting of downwards blocks
514                         Warning("[Heap   ] TODO: Space efficient realloc when new size is smaller");
515                 }
516                 
517                 #if DEBUG_TRACE
518                 Log_Debug("Heap", "realloc expand down %p (0x%x to 0x%x), returning to %s:%i",
519                         head->Data, head->Size, newSize, File, Line);
520                 #endif
521                 
522                 // Exact fit
523                 Uint    oldDataSize;
524                 // Set 1st (new/lower) header
525                 nextHead->Magic = MAGIC_USED;
526                 nextHead->Size = newSize;
527                 nextHead->File = File;
528                 nextHead->Line = Line;
529                 nextHead->ValidSize = __size;
530                 // Get 2nd (old) footer
531                 foot = Heap_ThisFoot(nextHead);
532                 foot->Head = nextHead;
533                 // Save old data size
534                 oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
535                 // Clear old header
536                 head->Size = 0;
537                 head->Magic = 0;
538                 // Copy data
539                 memmove(nextHead->Data, __ptr, oldDataSize);
540                 // Return
541                 return nextHead->Data;
542         }
543         
544         // Well, darn
545         nextHead = Heap_Allocate( File, Line, __size );
546         if(!nextHead)   return NULL;
547         nextHead -= 1;
548         nextHead->File = File;
549         nextHead->Line = Line;
550         nextHead->ValidSize = __size;
551         
552         ASSERTC(head->Size, <, nextHead->Size);
553         ASSERTC(__ptr, ==, head->Data);
554         memcpy(
555                 nextHead->Data,
556                 __ptr,
557                 head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead)
558                 );
559         
560         free(__ptr);
561         Heap_Validate();
562
563         return nextHead->Data;
564 }
565
566 /**
567  * \fn void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
568  * \brief Allocate and Zero a buffer in memory
569  * \param File  Allocating file
570  * \param Line  Line of allocation
571  * \param Bytes Size of the allocation
572  */
573 void *Heap_AllocateZero(const char *File, int Line, size_t Bytes)
574 {
575         void    *ret = Heap_Allocate(File, Line, Bytes);
576         if(ret == NULL) return NULL;
577         
578         memset( ret, 0, Bytes );
579         
580         return ret;
581 }
582
583 /**
584  * \fn int Heap_IsHeapAddr(void *Ptr)
585  * \brief Checks if an address is a heap pointer
586  */
587 int Heap_IsHeapAddr(void *Ptr)
588 {
589         tHeapHead       *head;
590         if((Uint)Ptr < (Uint)gHeapStart)        return 0;
591         if((Uint)Ptr > (Uint)gHeapEnd)  return 0;
592         if((Uint)Ptr & (sizeof(Uint)-1))        return 0;
593         
594         head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
595         if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
596                 return 0;
597         
598         return 1;
599 }
600
601 int Heap_int_ApplyWatchpont(void *Word, bool enabled)
602 {
603         #if ARCHDIR_IS_x86
604         static void     *active_wps[4];
605         unsigned int    dr;
606         for( dr = 2; dr < 4; dr ++ )
607         {
608                 if( (enabled && active_wps[dr] == NULL) || active_wps[dr] == Word)
609                         break;
610         }
611         if(dr == 4) {
612                 return 1;
613         }
614         if( enabled )
615         {
616                 active_wps[dr] = Word;
617                 switch(dr)
618                 {
619                 //case 0:       ASM("mov %0, %%dr0" : : "r" (Word));    break;
620                 //case 1:       ASM("mov %0, %%dr1" : : "r" (Word));    break;
621                 case 2: ASM("mov %0, %%dr2" : : "r" (Word));    break;
622                 case 3: ASM("mov %0, %%dr3" : : "r" (Word));    break;
623                 default:        ASSERTC(dr,<,4);        return 1;
624                 }
625         }
626         else
627         {
628                 active_wps[dr] = NULL;
629         }
630         Uint32  dr7flag;
631         ASM("MOV %%dr7, %0" : "=r" (dr7flag));
632         dr7flag &= ~(0x2 << (dr*2));
633         dr7flag &= ~(0xF000 << (dr*4));
634         if( enabled ) {
635                 dr7flag |= 0x2 << (dr*2);
636                 dr7flag |= 0xD000 << (dr*4);    // 4 bytes, write
637                 Debug("Heap_int_ApplyWatchpont: Watchpoint #%i %p ENABLED", dr, Word);
638         }
639         else {
640                 Debug("Heap_int_ApplyWatchpont: Watchpoint #%i %p disabled", dr, Word);
641         }
642         ASM("MOV %0, %%dr7" : : "r" (dr7flag));
643         return 0;
644         #else
645         return 1;
646         #endif
647 }
648
649 void Heap_int_WatchBlock(tHeapHead *Head, bool Enabled)
650 {
651         int rv;
652         rv = Heap_int_ApplyWatchpont( &Head->Size, Enabled );
653         //rv = Heap_int_ApplyWatchpont( &Head->Magic, Enabled );
654         rv = rv + Heap_int_ApplyWatchpont( &Heap_ThisFoot(Head)->Head, Enabled );
655         if(rv && Enabled) {
656                 Warning("Can't apply watch on %p", Head);
657         }
658 }
659
660 int Heap_WatchBlock(void *Ptr)
661 {
662         //Heap_int_ApplyWatchpont();
663         tHeapHead       *head;
664         if((Uint)Ptr < (Uint)gHeapStart)        return 0;
665         if((Uint)Ptr > (Uint)gHeapEnd)  return 0;
666         if((Uint)Ptr & (sizeof(Uint)-1))        return 0;
667         
668         head = (tHeapHead*)Ptr - 1;
669         
670         Heap_int_WatchBlock( head, true );
671         
672         return 0;
673 }
674
675 /**
676  */
677 void Heap_Validate(void)
678 {
679         // Call dump non-verbosely.
680         // - If a heap error is detected, it'll print
681         Heap_ValidateDump(0);
682 }
683
684 void Heap_Dump(void)
685 {
686         Heap_ValidateDump(1);
687 }
688
689 void Heap_ValidateDump(int bVerbose)
690 {
691         tHeapHead       *head, *badHead;
692         tHeapFoot       *foot = NULL;
693         static int      in_heap_dump;
694         
695         if( in_heap_dump )      return;
696
697         in_heap_dump = 1;
698
699         head = gHeapStart;
700         while( (Uint)head < (Uint)gHeapEnd )
701         {               
702                 foot = Heap_ThisFoot(head);
703                 
704                 if( bVerbose )
705                 {
706                         Log_Log("Heap", "%p (%P): 0x%08x (%i) %4C",
707                                 head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
708                         Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
709                         if(head->File) {
710                                 Log_Log("Heap", "%sowned by %s:%i",
711                                         (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
712                         }
713                 }
714                 
715                 // Sanity Check Header
716                 if(head->Size == 0) {
717                         Log_Warning("Heap", "HALTED - Size is zero");
718                         break;
719                 }
720                 if(head->Size & (MIN_SIZE-1)) {
721                         Log_Warning("Heap", "HALTED - Size is malaligned");
722                         break;
723                 }
724                 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
725                         Log_Warning("Heap", "HALTED - Head Magic is Bad");
726                         break;
727                 }
728                 
729                 // Check footer
730                 if(foot->Magic != MAGIC_FOOT) {
731                         Log_Warning("Heap", "HALTED - Foot Magic is Bad");
732                         break;
733                 }
734                 if(head != foot->Head) {
735                         Log_Warning("Heap", "HALTED - Footer backlink is invalid");
736                         break;
737                 }
738                 
739                 if( bVerbose )
740                 {
741                         Log_Log("Heap", "");
742                 }
743                 
744                 // All OK? Go to next
745                 head = foot->NextHead;
746         }
747         
748         // If the heap is valid, ok!
749         if( (tVAddr)head == (tVAddr)gHeapEnd ) {
750                 in_heap_dump = 0;
751                 return ;
752         }
753         
754         // Check for a bad return
755         if( (tVAddr)head >= (tVAddr)gHeapEnd ) {
756                 in_heap_dump = 0;
757                 return ;
758         }
759         
760         // If not verbose, we need to dump the failing block
761         if( !bVerbose )
762         {
763                 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
764                         head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
765                 if(foot)
766                         Log_Log("Heap", "Foot %p = {Head:%p,Magic:%4C}", foot, foot->Head, &foot->Magic);
767                 if(head->File) {
768                         Log_Log("Heap", "%sowned by %s:%i",
769                                 (head->Magic==MAGIC_FREE?"was ":""), head->File, head->Line);
770                 }
771                 Log_Log("Heap", "");
772         }
773                 
774         badHead = head;
775         
776         // Work backwards
777         foot = Heap_PrevFoot(gHeapEnd);
778         Log_Log("Heap", "==== Going Backwards ==== (from %p)", foot);
779         head = foot->Head;
780         while( (tVAddr)head >= (tVAddr)badHead )
781         {
782                 Log_Log("Heap", "%p (%P): 0x%08lx %i %4C",
783                         head, MM_GetPhysAddr(head), head->Size, head->ValidSize, &head->Magic);
784                 Log_Log("Heap", "%p %4C", foot->Head, &foot->Magic);
785                 if(head->File)
786                         Log_Log("Heap", "%sowned by %s:%i",
787                                 (head->Magic!=MAGIC_USED?"was ":""),
788                                 head->File, head->Line);
789                 Log_Log("Heap", "");
790                 
791                 // Sanity Check Header
792                 if(head->Size == 0) {
793                         Log_Warning("Heap", "HALTED - Size is zero");
794                         break;
795                 }
796                 if(head->Size & (MIN_SIZE-1)) {
797                         Log_Warning("Heap", " - Size is malaligned (&0x%x)", ~(MIN_SIZE-1));
798                         break ;
799                 }
800                 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
801                         Log_Warning("Heap", "HALTED - Head Magic is Bad");
802                         break;
803                 }
804                 
805                 // Check footer
806                 if(foot->Magic != MAGIC_FOOT) {
807                         Log_Warning("Heap", "HALTED - Foot Magic is Bad");
808                         break;
809                 }
810                 if(head != foot->Head) {
811                         Log_Warning("Heap", "HALTED - Footer backlink is invalid");
812                         break;
813                 }
814                 
815                 if(head == badHead)     break;
816                 
817                 foot = Heap_PrevFoot(head);
818                 head = foot->Head;
819                 Log_Debug("Heap", "head=%p", head);
820         }
821         
822         Panic("Heap_Dump - Heap is corrupted, kernel panic! (%p)", badHead);
823 }
824
825 void Heap_Stats(void)
826 {
827          int    nBlocks = 0;
828          int    nFree = 0;
829          int    totalBytes = 0;
830          int    freeBytes = 0;
831          int    maxAlloc=0, minAlloc=-1;
832          int    avgAlloc, frag, overhead;
833         
834         for( tHeapHead *head = gHeapStart; head < gHeapEnd; head = Heap_NextHead(head) )
835         {       
836                 nBlocks ++;
837                 totalBytes += head->Size;
838                 if( head->Magic == MAGIC_FREE )
839                 {
840                         nFree ++;
841                         freeBytes += head->Size;
842                 }
843                 else if( head->Magic == MAGIC_USED) {
844                         if(maxAlloc < head->Size)       maxAlloc = head->Size;
845                         if(minAlloc == -1 || minAlloc > head->Size)
846                                 minAlloc = head->Size;
847                 }
848                 else {
849                         Log_Warning("Heap", "Magic on %p invalid, skipping remainder of heap", head);
850                         break;
851                 }
852                 
853                 // Print the block info?
854                 #if 1
855                 if( head->Magic == MAGIC_FREE )
856                         Log_Debug("Heap", "%p (%P) - 0x%x free",
857                                 head->Data, MM_GetPhysAddr(&head->Data), head->Size);
858                 else
859                         Log_Debug("Heap", "%p (%P) - 0x%x (%i) Owned by %s:%i (%lli ms old)",
860                                 head->Data, MM_GetPhysAddr(&head->Data), head->Size,
861                                 head->ValidSize, head->File, head->Line,
862                                 now() - head->AllocateTime
863                                 );
864                 #endif
865         }
866
867         Log_Log("Heap", "%i blocks (0x%x bytes)", nBlocks, totalBytes);
868         Log_Log("Heap", "%i free blocks (0x%x bytes)", nFree, freeBytes);
869         if(nBlocks != 0)
870                 frag = (nFree-1)*10000/nBlocks;
871         else
872                 frag = 0;
873         Log_Log("Heap", "%i.%02i%% Heap Fragmentation", frag/100, frag%100);
874         if(nBlocks <= nFree)
875                 avgAlloc = 0;
876         else
877                 avgAlloc = (totalBytes-freeBytes)/(nBlocks-nFree);
878         if(avgAlloc != 0)
879                 overhead = (sizeof(tHeapFoot)+sizeof(tHeapHead))*10000/avgAlloc;
880         else
881                 overhead = 0;
882         Log_Log("Heap", "Average allocation: %i bytes, Average Overhead: %i.%02i%%",
883                 avgAlloc, overhead/100, overhead%100
884                 );
885         Log_Log("Heap", "Smallest Block: %i bytes, Largest: %i bytes", 
886                 minAlloc, maxAlloc);
887         
888         // Scan and get distribution
889         #if 1
890         if(nBlocks > 0)
891         {
892                 struct {
893                         Uint    Size;
894                         Uint    Count;
895                 }       sizeCounts[nBlocks];
896                  int    i;
897                 
898                 memset(sizeCounts, 0, nBlocks*sizeof(sizeCounts[0]));
899                 
900                 for(tHeapHead *head = gHeapStart; head < gHeapEnd; head = (void*)( (tVAddr)head + head->Size ) )
901                 {
902                         for( i = 0; i < nBlocks; i ++ ) {
903                                 if( sizeCounts[i].Size == 0 )
904                                         break;
905                                 if( sizeCounts[i].Size == head->Size )
906                                         break;
907                         }
908                         // Should never reach this part (in a non-concurrent case)
909                         if( i == nBlocks )      continue;
910                         sizeCounts[i].Size = head->Size;
911                         sizeCounts[i].Count ++;
912                         #if 0
913                         Log("Heap_Stats: %i %p - 0x%x bytes (%s) (%i)", nBlocks, head,
914                                 head->Size, (head->Magic==MAGIC_FREE?"FREE":"used"), i
915                                 );
916                         Log("Heap_Stats: sizeCounts[%i] = {Size:0x%x, Count: %i}", i,
917                                 sizeCounts[i].Size, sizeCounts[i].Count);
918                         #endif
919                 }
920                 
921                 for( i = 0; i < nBlocks && sizeCounts[i].Count; i ++ )
922                 {
923                         Log("Heap_Stats: 0x%x - %i blocks",
924                                 sizeCounts[i].Size, sizeCounts[i].Count
925                                 );
926                 }
927         }
928         #endif
929 }
930
931 // === EXPORTS ===
932 EXPORT(Heap_Allocate);
933 EXPORT(Heap_AllocateZero);
934 EXPORT(Heap_Reallocate);
935 EXPORT(Heap_Deallocate);
936 EXPORT(Heap_IsHeapAddr);

UCC git Repository :: git.ucc.asn.au