This change adds PPC support to libpayload, and hooks it up in the build
[coreboot.git] / payloads / libpayload / libc / malloc.c
1 /*
2  * This file is part of the libpayload project.
3  *
4  * Copyright (C) 2008 Advanced Micro Devices, Inc.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  * 3. The name of the author may not be used to endorse or promote products
15  *    derived from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  */
29
30 /*
31  * This is a classically weak malloc() implementation. We have a relatively
32  * small and static heap, so we take the easy route with an O(N) loop
33  * through the tree for every malloc() and free(). Obviously, this doesn't
34  * scale past a few hundred KB (if that).
35  *
36  * We're also susceptible to the usual buffer overrun poisoning, though the
37  * risk is within acceptable ranges for this implementation (don't overrun
38  * your buffers, kids!).
39  */
40
41 #include <libpayload.h>
42
43 extern char _heap, _eheap;      /* Defined in the ldscript. */
44
45 static void *hstart = (void *)&_heap;
46 static void *hend = (void *)&_eheap;
47
48 typedef unsigned int hdrtype_t;
49
50 #define MAGIC     (0x2a << 26)
51 #define FLAG_FREE (1 << 25)
52 #define FLAG_USED (1 << 24)
53
54 #define SIZE(_h) ((_h) & 0xFFFFFF)
55
56 #define _HEADER(_s, _f) ((hdrtype_t) (MAGIC | (_f) | ((_s) & 0xFFFFFF)))
57
58 #define FREE_BLOCK(_s) _HEADER(_s, FLAG_FREE)
59 #define USED_BLOCK(_s) _HEADER(_s, FLAG_USED)
60
61 #define HDRSIZE (sizeof(hdrtype_t))
62
63 #define IS_FREE(_h) (((_h) & (MAGIC | FLAG_FREE)) == (MAGIC | FLAG_FREE))
64 #define HAS_MAGIC(_h) (((_h) & MAGIC) == MAGIC)
65
66 static int free_aligned(void* addr);
67 void print_malloc_map(void);
68
69 static void setup(void)
70 {
71         int size = (unsigned int)(&_eheap - &_heap) - HDRSIZE;
72
73         *((hdrtype_t *) hstart) = FREE_BLOCK(size);
74 }
75
76 static void *alloc(int len)
77 {
78         hdrtype_t header;
79         void *ptr = hstart;
80
81         /* Align the size. */
82         len = (len + 3) & ~3;
83
84         if (!len || len > 0xffffff)
85                 return (void *)NULL;
86
87         /* Make sure the region is setup correctly. */
88         if (!HAS_MAGIC(*((hdrtype_t *) ptr)))
89                 setup();
90
91         /* Find some free space. */
92         do {
93                 header = *((hdrtype_t *) ptr);
94                 int size = SIZE(header);
95
96                 if (!HAS_MAGIC(header) || size == 0) {
97                         printf("memory allocator panic.\n");
98                         halt();
99                 }
100
101                 if (header & FLAG_FREE) {
102                         if (len <= size) {
103                                 void *nptr = ptr + (HDRSIZE + len);
104                                 int nsize = size - (HDRSIZE + len);
105
106                                 /* If there is still room in this block,
107                                  * then mark it as such otherwise account
108                                  * the whole space for that block.
109                                  */
110
111                                 if (nsize > 0) {
112                                         /* Mark the block as used. */
113                                         *((hdrtype_t *) ptr) = USED_BLOCK(len);
114
115                                         /* Create a new free block. */
116                                         *((hdrtype_t *) nptr) =
117                                             FREE_BLOCK(nsize);
118                                 } else {
119                                         /* Mark the block as used. */
120                                         *((hdrtype_t *) ptr) = USED_BLOCK(size);
121                                 }
122
123                                 return (void *)(ptr + HDRSIZE);
124                         }
125                 }
126
127                 ptr += HDRSIZE + size;
128
129         } while (ptr < hend);
130
131         /* Nothing available. */
132         return (void *)NULL;
133 }
134
135 static void _consolidate(void)
136 {
137         void *ptr = hstart;
138
139         while (ptr < hend) {
140                 void *nptr;
141                 hdrtype_t hdr = *((hdrtype_t *) ptr);
142                 unsigned int size = 0;
143
144                 if (!IS_FREE(hdr)) {
145                         ptr += HDRSIZE + SIZE(hdr);
146                         continue;
147                 }
148
149                 size = SIZE(hdr);
150                 nptr = ptr + HDRSIZE + SIZE(hdr);
151
152                 while (nptr < hend) {
153                         hdrtype_t nhdr = *((hdrtype_t *) nptr);
154
155                         if (!(IS_FREE(nhdr)))
156                                 break;
157
158                         size += SIZE(nhdr) + HDRSIZE;
159
160                         *((hdrtype_t *) nptr) = 0;
161
162                         nptr += (HDRSIZE + SIZE(nhdr));
163                 }
164
165                 *((hdrtype_t *) ptr) = FREE_BLOCK(size);
166                 ptr = nptr;
167         }
168 }
169
170 void free(void *ptr)
171 {
172         hdrtype_t hdr;
173
174         if (free_aligned(ptr)) return;
175
176         ptr -= HDRSIZE;
177
178         /* Sanity check. */
179         if (ptr < hstart || ptr >= hend)
180                 return;
181
182         hdr = *((hdrtype_t *) ptr);
183
184         /* Not our header (we're probably poisoned). */
185         if (!HAS_MAGIC(hdr))
186                 return;
187
188         /* Double free. */
189         if (hdr & FLAG_FREE)
190                 return;
191
192         *((hdrtype_t *) ptr) = FREE_BLOCK(SIZE(hdr));
193         _consolidate();
194 }
195
196 void *malloc(size_t size)
197 {
198         return alloc(size);
199 }
200
201 void *calloc(size_t nmemb, size_t size)
202 {
203         size_t total = nmemb * size;
204         void *ptr = alloc(total);
205
206         if (ptr)
207                 memset(ptr, 0, total);
208
209         return ptr;
210 }
211
212 void *realloc(void *ptr, size_t size)
213 {
214         void *ret, *pptr;
215         unsigned int osize;
216
217         if (ptr == NULL)
218                 return alloc(size);
219
220         pptr = ptr - HDRSIZE;
221
222         if (!HAS_MAGIC(*((hdrtype_t *) pptr)))
223                 return NULL;
224
225         /* Get the original size of the block. */
226         osize = SIZE(*((hdrtype_t *) pptr));
227
228         /*
229          * Free the memory to update the tables - this won't touch the actual
230          * memory, so we can still use it for the copy after we have
231          * reallocated the new space.
232          */
233         free(ptr);
234         ret = alloc(size);
235
236         /*
237          * if ret == NULL, then doh - failure.
238          * if ret == ptr then woo-hoo! no copy needed.
239          */
240         if (ret == NULL || ret == ptr)
241                 return ret;
242
243         /* Copy the memory to the new location. */
244         memcpy(ret, ptr, osize > size ? size : osize);
245
246         return ret;
247 }
248
249 struct align_region_t
250 {
251         int alignment;
252         /* start in memory, and size in bytes */
253         void* start;
254         int size;
255         /* layout within a region:
256           - num_elements bytes, 0: free, 1: used, 2: used, combines with next
257           - padding to alignment
258           - data section
259           - waste space
260
261           start_data points to the start of the data section
262         */
263         void* start_data;
264         /* number of free blocks sized "alignment" */
265         int free;
266         struct align_region_t *next;
267 };
268
269 static struct align_region_t* align_regions = 0;
270
271 static struct align_region_t *allocate_region(struct align_region_t *old_first, int alignment, int num_elements)
272 {
273         struct align_region_t *new_region = malloc(sizeof(struct align_region_t));
274         new_region->alignment = alignment;
275         new_region->start = malloc((num_elements+1) * alignment + num_elements);
276         new_region->start_data = (void*)((u32)(new_region->start + num_elements + alignment - 1) & (~(alignment-1)));
277         new_region->size = num_elements * alignment;
278         new_region->free = num_elements;
279         new_region->next = old_first;
280         memset(new_region->start, 0, num_elements);
281         return new_region;
282 }
283
284
285 static int free_aligned(void* addr)
286 {
287         struct align_region_t *reg = align_regions;
288         while (reg != 0)
289         {
290                 if ((addr >= reg->start_data) && (addr < reg->start_data + reg->size))
291                 {
292                         int i = (addr-reg->start_data)/reg->alignment;
293                         while (((u8*)reg->start)[i]==2)
294                         {
295                                 ((u8*)reg->start)[i++]=0;
296                                 reg->free++;
297                         }
298                         ((u8*)reg->start)[i]=0;
299                         reg->free++;
300                         return 1;
301                 }
302                 reg = reg->next;
303         }
304         return 0;
305 }
306
307 void *memalign(size_t align, size_t size)
308 {
309         if (size == 0) return 0;
310         if (align_regions == 0) {
311                 align_regions = malloc(sizeof(struct align_region_t));
312                 memset(align_regions, 0, sizeof(struct align_region_t));
313         }
314         struct align_region_t *reg = align_regions;
315 look_further:   
316         while (reg != 0)
317         {
318                 if ((reg->alignment == align) && (reg->free >= (size + align - 1)/align))
319                 {
320                         break;
321                 }
322                 reg = reg->next;
323         }
324         if (reg == 0)
325         {
326                 align_regions = allocate_region(align_regions, align, (size/align<99)?100:((size/align)+1));
327                 reg = align_regions;
328         }
329         int i, count = 0, target = (size+align-1)/align;
330         for (i = 0; i < (reg->size/align); i++)
331         {
332                 if (((u8*)reg->start)[i] == 0)
333                 {
334                         count++;
335                         if (count == target) {
336                                 count = i+1-count;
337                                 for (i=0; i<target-1; i++)
338                                 {
339                                         ((u8*)reg->start)[count+i]=2;
340                                 }
341                                 ((u8*)reg->start)[count+target-1]=1;
342                                 reg->free -= target;
343                                 return reg->start_data+(align*count);
344                         }
345                 } else {
346                         count = 0;
347                 }
348         }
349         goto look_further; // end condition is once a new region is allocated - it always has enough space
350 }
351
352 /* This is for debugging purposes. */
353 #ifdef TEST
354 void print_malloc_map(void)
355 {
356         void *ptr = hstart;
357
358         while (ptr < hend) {
359                 hdrtype_t hdr = *((hdrtype_t *) ptr);
360
361                 if (!HAS_MAGIC(hdr)) {
362                         printf("Poisoned magic - we're toast\n");
363                         break;
364                 }
365
366                 /* FIXME: Verify the size of the block. */
367
368                 printf("%x: %s (%x bytes)\n",
369                        (unsigned int)(ptr - hstart),
370                        hdr & FLAG_FREE ? "FREE" : "USED", SIZE(hdr));
371
372                 ptr += HDRSIZE + SIZE(hdr);
373         }
374 }
375 #endif