Turned on debug in syscalls and added return address to free's warning
[tpg/acess2.git] / Kernel / heap.c
1 /*
2  * AcessOS Microkernel Version
3  * heap.c
4  */
5 #include <common.h>
6 #include <mm_virt.h>
7 #include <heap.h>
8
9 #define WARNINGS        1
10 #define DEBUG_TRACE     0
11
12 // === CONSTANTS ===
13 #define HEAP_BASE       0xE0800000
14 #define HEAP_MAX        0xF0000000      // 120MiB, Plenty
15 #define HEAP_INIT_SIZE  0x8000  // 32 KiB
16 #define BLOCK_SIZE      (sizeof(void*)) // 8 Machine Words
17 #define COMPACT_HEAP    0       // Use 4 byte header?
18 #define FIRST_FIT       0
19
20 #define MAGIC_FOOT      0x2ACE5505
21 #define MAGIC_FREE      0xACE55000
22 #define MAGIC_USED      0x862B0505      // MAGIC_FOOT ^ MAGIC_FREE
23
24 // === PROTOTYPES ===
25 void    Heap_Install();
26 void    *Heap_Extend(int Bytes);
27 void    *Heap_Merge(tHeapHead *Head);
28 void    *malloc(size_t Bytes);
29 void    free(void *Ptr);
30 void    Heap_Dump();
31
32 // === GLOBALS ===
33  int    giHeapSpinlock;
34 void    *gHeapStart;
35 void    *gHeapEnd;
36
37 // === CODE ===
38 void Heap_Install()
39 {
40         gHeapStart      = (void*)MM_KHEAP_BASE;
41         gHeapEnd        = (void*)MM_KHEAP_BASE;
42         Heap_Extend(HEAP_INIT_SIZE);
43 }
44
45 /**
46  * \fn void *Heap_Extend(int Bytes)
47  * \brief Extend the size of the heap
48  */
49 void *Heap_Extend(int Bytes)
50 {
51         Uint    i;
52         tHeapHead       *head = gHeapEnd;
53         tHeapFoot       *foot;
54         
55         // Bounds Check
56         if( (Uint)gHeapEnd == MM_KHEAP_MAX )
57                 return NULL;
58         
59         // Bounds Check
60         if( (Uint)gHeapEnd + ((Bytes+0xFFF)&~0xFFF) > MM_KHEAP_MAX ) {
61                 Bytes = MM_KHEAP_MAX - (Uint)gHeapEnd;
62                 return NULL;
63         }
64         
65         // Heap expands in pages
66         for(i=0;i<(Bytes+0xFFF)>>12;i++)
67                 MM_Allocate( (Uint)gHeapEnd+(i<<12) );
68         
69         // Increas heap end
70         gHeapEnd += i << 12;
71         
72         // Create Block
73         head->Size = (Bytes+0xFFF)&~0xFFF;
74         head->Magic = MAGIC_FREE;
75         foot = (void*)( (Uint)gHeapEnd - sizeof(tHeapFoot) );
76         foot->Head = head;
77         foot->Magic = MAGIC_FOOT;
78         
79         //Log(" Heap_Extend: head = %p", head);
80         return Heap_Merge(head);        // Merge with previous block
81 }
82
83 /**
84  * \fn void *Heap_Merge(tHeapHead *Head)
85  * \brief Merges two ajacent heap blocks
86  */
87 void *Heap_Merge(tHeapHead *Head)
88 {
89         tHeapFoot       *foot;
90         tHeapFoot       *thisFoot;
91         tHeapHead       *head;
92         
93         //Log("Heap_Merge: (Head=%p)", Head);
94         
95         thisFoot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
96         if((Uint)thisFoot > (Uint)gHeapEnd)     return NULL;
97         
98         // Merge Left (Down)
99         foot = (void*)( (Uint)Head - sizeof(tHeapFoot) );
100         if( ((Uint)foot < (Uint)gHeapEnd && (Uint)foot > HEAP_BASE)
101         && foot->Head->Magic == MAGIC_FREE) {
102                 foot->Head->Size += Head->Size; // Increase size
103                 thisFoot->Head = foot->Head;    // Change backlink
104                 Head->Magic = 0;        // Clear old head
105                 Head->Size = 0;
106                 Head = foot->Head;      // Save new head address
107                 foot->Head = NULL;      // Clear central footer
108                 foot->Magic = 0;
109         }
110         
111         // Merge Right (Upwards)
112         head = (void*)( (Uint)Head + Head->Size );
113         if((Uint)head < (Uint)gHeapEnd && head->Magic == MAGIC_FREE)
114         {
115                 Head->Size += head->Size;
116                 foot = (void*)( (Uint)Head + Head->Size - sizeof(tHeapFoot) );
117                 foot->Head = Head;      // Update Backlink
118                 thisFoot->Head = NULL;  // Clear old footer
119                 thisFoot->Magic = 0;
120                 head->Size = 0;         // Clear old header
121                 head->Magic = 0;
122         }
123         
124         // Return new address
125         return Head;
126 }
127
128 /**
129  * \fn void *malloc(size_t Bytes)
130  * \brief Allocate memory from the heap
131  */
132 void *malloc(size_t Bytes)
133 {
134         tHeapHead       *head, *newhead;
135         tHeapFoot       *foot, *newfoot;
136         tHeapHead       *best = NULL;
137         Uint    bestSize = 0;   // Speed hack
138         
139         // Get required size
140         Bytes = (Bytes + sizeof(tHeapHead) + sizeof(tHeapFoot) + BLOCK_SIZE-1) & ~(BLOCK_SIZE-1);
141         
142         // Lock Heap
143         LOCK(&giHeapSpinlock);
144         
145         // Traverse Heap
146         for( head = gHeapStart;
147                 (Uint)head < (Uint)gHeapEnd;
148                 head = (void*)((Uint)head + head->Size)
149                 )
150         {
151                 // Alignment Check
152                 if( head->Size & (BLOCK_SIZE-1) ) {
153                         #if WARNINGS
154                         Warning("Size of heap address %p is invalid not aligned (0x%x)", head, head->Size);
155                         Heap_Dump();
156                         #endif
157                         return NULL;
158                 }
159                 
160                 // Check if allocated
161                 if(head->Magic == MAGIC_USED)   continue;
162                 // Error check
163                 if(head->Magic != MAGIC_FREE)   {
164                         #if WARNINGS
165                         Warning("Magic of heap address %p is invalid (0x%x)", head, head->Magic);
166                         Heap_Dump();
167                         #endif
168                         RELEASE(&giHeapSpinlock);       // Release spinlock
169                         return NULL;
170                 }
171                 
172                 // Size check
173                 if(head->Size < Bytes)  continue;
174                 
175                 // Perfect fit
176                 if(head->Size == Bytes) {
177                         head->Magic = MAGIC_USED;
178                         RELEASE(&giHeapSpinlock);       // Release spinlock
179                         #if DEBUG_TRACE
180                         LOG("RETURN %p, to %p", best->Data, __builtin_return_address(0));
181                         #endif
182                         return best->Data;
183                 }
184                 
185                 // Break out of loop
186                 #if FIRST_FIT
187                 best = head;
188                 bestSize = head->Size;
189                 break;
190                 #else
191                 // or check if the block is the best size
192                 if(bestSize > head->Size) {
193                         best = head;
194                         bestSize = head->Size;
195                 }
196                 #endif
197         }
198         
199         // If no block large enough is found, create one
200         if(!best)
201         {
202                 best = Heap_Extend( Bytes );
203                 // Check for errors
204                 if(!best) {
205                         RELEASE(&giHeapSpinlock);       // Release spinlock
206                         return NULL;
207                 }
208                 // Check size
209                 if(best->Size == Bytes) {
210                         RELEASE(&giHeapSpinlock);       // Release spinlock
211                         #if DEBUG_TRACE
212                         LOG("RETURN %p, to %p", best->Data, __builtin_return_address(0));
213                         #endif
214                         return best->Data;
215                 }
216         }
217         
218         // Split Block
219         newhead = (void*)( (Uint)best + Bytes );
220         newfoot = (void*)( (Uint)best + Bytes - sizeof(tHeapFoot) );
221         foot = (void*)( (Uint)best + best->Size - sizeof(tHeapFoot) );
222         
223         newfoot->Head = best;   // Create new footer
224         newfoot->Magic = MAGIC_FOOT;
225         newhead->Size = best->Size - Bytes;     // Create new header
226         newhead->Magic = MAGIC_FREE;
227         foot->Head = newhead;   // Update backlink in old footer
228         best->Size = Bytes;             // Update size in old header
229         best->Magic = MAGIC_USED;       // Mark block as used
230         
231         RELEASE(&giHeapSpinlock);       // Release spinlock
232         #if DEBUG_TRACE
233         LOG("RETURN %p, to %p", best->Data, __builtin_return_address(0));
234         #endif
235         return best->Data;
236 }
237
238 /**
239  * \fn void free(void *Ptr)
240  * \brief Free an allocated memory block
241  */
242 void free(void *Ptr)
243 {
244         tHeapHead       *head;
245         tHeapFoot       *foot;
246         
247         #if DEBUG_TRACE
248         LOG("Ptr = %p", Ptr);
249         LOG("Returns to %p", __builtin_return_address(0));
250         #endif
251         
252         // Alignment Check
253         if( (Uint)Ptr & (sizeof(Uint)-1) ) {
254                 Warning("free - Passed a non-aligned address (%p)", Ptr);
255                 return;
256         }
257         
258         // Sanity check
259         if((Uint)Ptr < (Uint)gHeapStart || (Uint)Ptr > (Uint)gHeapEnd)
260         {
261                 Warning("free - Passed a non-heap address (%p)\n", Ptr);
262                 return;
263         }
264         
265         // Check memory block - Header
266         head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
267         if(head->Magic == MAGIC_FREE) {
268                 Warning("free - Passed a freed block (%p) by %p", head, __builtin_return_address(0));
269                 return;
270         }
271         if(head->Magic != MAGIC_USED) {
272                 Warning("free - Magic value is invalid (%p, 0x%x)\n", head, head->Magic);
273                 return;
274         }
275         
276         // Check memory block - Footer
277         foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
278         if(foot->Head != head) {
279                 Warning("free - Footer backlink is incorrect (%p, 0x%x)\n", head, foot->Head);
280                 return;
281         }
282         if(foot->Magic != MAGIC_FOOT) {
283                 Warning("free - Footer magic is invalid (%p, 0x%x)\n", head, foot->Magic);
284                 return;
285         }
286         
287         // Lock
288         LOCK( &giHeapSpinlock );
289         
290         // Mark as free
291         head->Magic = MAGIC_FREE;
292         // Merge blocks
293         Heap_Merge( head );
294         
295         // Release
296         RELEASE( &giHeapSpinlock );
297 }
298
299 /**
300  */
301 void *realloc(void *__ptr, size_t __size)
302 {
303         tHeapHead       *head = (void*)( (Uint)__ptr-8 );
304         tHeapHead       *nextHead;
305         tHeapFoot       *foot;
306         Uint    newSize = (__size + sizeof(tHeapFoot)+sizeof(tHeapHead)+BLOCK_SIZE-1)&~(BLOCK_SIZE-1);
307         
308         // Check for reallocating NULL
309         if(__ptr == NULL)       return malloc(__size);
310         
311         // Check if resize is needed
312         if(newSize <= head->Size)       return __ptr;
313         
314         // Check if next block is free
315         nextHead = (void*)( (Uint)head + head->Size );
316         
317         // Extend into next block
318         if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
319         {
320                 Uint    size = nextHead->Size + head->Size;
321                 foot = (void*)( (Uint)nextHead + nextHead->Size - sizeof(tHeapFoot) );
322                 // Exact Fit
323                 if(size == newSize) {
324                         head->Size = newSize;
325                         foot->Head = head;
326                         nextHead->Magic = 0;
327                         nextHead->Size = 0;
328                         return __ptr;
329                 }
330                 // Create a new heap block
331                 nextHead = (void*)( (Uint)head + newSize );
332                 nextHead->Size = size - newSize;
333                 nextHead->Magic = MAGIC_FREE;
334                 foot->Head = nextHead;  // Edit 2nd footer
335                 head->Size = newSize;   // Edit first header
336                 // Create new footer
337                 foot = (void*)( (Uint)head + newSize - sizeof(tHeapFoot) );
338                 foot->Head = head;
339                 foot->Magic = MAGIC_FOOT;
340                 return __ptr;
341         }
342         
343         // Extend downwards?
344         foot = (void*)( (Uint)head - sizeof(tHeapFoot) );
345         nextHead = foot->Head;
346         if(nextHead->Magic == MAGIC_FREE && nextHead->Size+head->Size >= newSize)
347         {
348                 Uint    size = nextHead->Size + head->Size;
349                 // Exact fit
350                 if(size == newSize)
351                 {
352                         Uint    oldDataSize;
353                         // Set 1st (new/lower) header
354                         nextHead->Magic = MAGIC_USED;
355                         nextHead->Size = newSize;
356                         // Get 2nd (old) footer
357                         foot = (void*)( (Uint)nextHead + newSize );
358                         foot->Head = nextHead;
359                         // Save old data size
360                         oldDataSize = head->Size - sizeof(tHeapFoot) - sizeof(tHeapHead);
361                         // Clear old header
362                         head->Size = 0;
363                         head->Magic = 0;
364                         memcpy(nextHead->Data, __ptr, oldDataSize);
365                 }
366         }
367         
368         return NULL;
369 }
370
371 /**
372  * \fn int IsHeap(void *Ptr)
373  * \brief Checks if an address is a heap address
374  */
375 int IsHeap(void *Ptr)
376 {
377         tHeapHead       *head;
378         if((Uint)Ptr < (Uint)gHeapStart)        return 0;
379         if((Uint)Ptr > (Uint)gHeapEnd)  return 0;
380         
381         head = (void*)( (Uint)Ptr - sizeof(tHeapHead) );
382         if(head->Magic != MAGIC_USED && head->Magic != MAGIC_FREE)
383                 return 0;
384         
385         return 1;
386 }
387
388 #if WARNINGS
389 void Heap_Dump()
390 {
391         tHeapHead       *head;
392         tHeapFoot       *foot;
393         
394         head = gHeapStart;
395         while( (Uint)head < (Uint)gHeapEnd )
396         {               
397                 foot = (void*)( (Uint)head + head->Size - sizeof(tHeapFoot) );
398                 Log("%p (0x%x): 0x%08lx 0x%lx", head, MM_GetPhysAddr((Uint)head), head->Size, head->Magic);
399                 Log("%p 0x%lx", foot->Head, foot->Magic);
400                 Log("");
401                 
402                 // Sanity Check Header
403                 if(head->Size == 0) {
404                         Log("HALTED - Size is zero");
405                         break;
406                 }
407                 if(head->Size & (BLOCK_SIZE-1)) {
408                         Log("HALTED - Size is malaligned");
409                         break;
410                 }
411                 if(head->Magic != MAGIC_FREE && head->Magic != MAGIC_USED) {
412                         Log("HALTED - Head Magic is Bad");
413                         break;
414                 }
415                 
416                 // Check footer
417                 if(foot->Magic != MAGIC_FOOT) {
418                         Log("HALTED - Foot Magic is Bad");
419                         break;
420                 }
421                 if(head != foot->Head) {
422                         Log("HALTED - Footer backlink is invalid");
423                         break;
424                 }
425                 
426                 // All OK? Go to next
427                 head = foot->NextHead;
428         }
429 }
430 #endif

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