Add memalign(align, size).
[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 void print_malloc_map(void);
67
68 static void setup(void)
69 {
70         int size = (unsigned int)(&_eheap - &_heap) - HDRSIZE;
71
72         *((hdrtype_t *) hstart) = FREE_BLOCK(size);
73 }
74
75 static void *alloc(int len, int align)
76 {
77         hdrtype_t header;
78         void *ptr = hstart;
79
80         /* Align the size. */
81         len = (len + 3) & ~3;
82
83         if (!len || len > 0xffffff)
84                 return (void *)NULL;
85
86         /* Make sure the region is setup correctly. */
87         if (!HAS_MAGIC(*((hdrtype_t *) ptr)))
88                 setup();
89
90         /* Find some free space. */
91         do {
92                 header = *((hdrtype_t *) ptr);
93                 int size = SIZE(header);
94
95                 if (!HAS_MAGIC(header)) {
96                         printf("memory allocator panic.\n");
97                         halt();
98                 }
99
100                 if (header & FLAG_FREE) {
101                         int realaddr = (int)(ptr + HDRSIZE);
102                         int overhead = ((realaddr+align-1) & ~(align-1)) - realaddr;
103                         if (len + overhead <= size) {
104                                 if (overhead != 0) {
105                                         *((hdrtype_t *) ptr) = FREE_BLOCK(overhead - HDRSIZE);
106                                         ptr += overhead;
107                                         size -= overhead;
108                                 }
109                                 void *nptr = ptr + (HDRSIZE + len);
110                                 int nsize = size - (HDRSIZE + len);
111
112                                 /* Mark the block as used. */
113                                 *((hdrtype_t *) ptr) = USED_BLOCK(len);
114
115                                 /* If there is still room in this block,
116                                  * then mark it as such.
117                                  */
118
119                                 if (nsize > 0)
120                                         *((hdrtype_t *) nptr) =
121                                             FREE_BLOCK(nsize);
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         ptr -= HDRSIZE;
175
176         /* Sanity check. */
177         if (ptr < hstart || ptr >= hend)
178                 return;
179
180         hdr = *((hdrtype_t *) ptr);
181
182         /* Not our header (we're probably poisoned). */
183         if (!HAS_MAGIC(hdr))
184                 return;
185
186         /* Double free. */
187         if (hdr & FLAG_FREE)
188                 return;
189
190         *((hdrtype_t *) ptr) = FREE_BLOCK(SIZE(hdr));
191         _consolidate();
192 }
193
194 void *malloc(size_t size)
195 {
196         return alloc(size, 1);
197 }
198
199 void *calloc(size_t nmemb, size_t size)
200 {
201         size_t total = nmemb * size;
202         void *ptr = alloc(total, 1);
203
204         if (ptr)
205                 memset(ptr, 0, total);
206
207         return ptr;
208 }
209
210 void *realloc(void *ptr, size_t size)
211 {
212         void *ret, *pptr;
213         unsigned int osize;
214
215         if (ptr == NULL)
216                 return alloc(size, 1);
217
218         pptr = ptr - HDRSIZE;
219
220         if (!HAS_MAGIC(*((hdrtype_t *) pptr)))
221                 return NULL;
222
223         /* Get the original size of the block. */
224         osize = SIZE(*((hdrtype_t *) pptr));
225
226         /*
227          * Free the memory to update the tables - this won't touch the actual
228          * memory, so we can still use it for the copy after we have
229          * reallocated the new space.
230          */
231         free(ptr);
232         ret = alloc(size, 1);
233
234         /*
235          * if ret == NULL, then doh - failure.
236          * if ret == ptr then woo-hoo! no copy needed.
237          */
238         if (ret == NULL || ret == ptr)
239                 return ret;
240
241         /* Copy the memory to the new location. */
242         memcpy(ret, ptr, osize > size ? size : osize);
243
244         return ret;
245 }
246
247 /**
248  * Allocate an aligned chunk of memory
249  *
250  * @param align alignment, must be power of two
251  * @param size size of chunk in bytes
252  * @return Return the address of such a memory region or NULL
253  */
254 void *memalign(size_t align, size_t size)
255 {
256         return alloc(size, align);
257 }
258
259 /* This is for debugging purposes. */
260 #ifdef TEST
261 void print_malloc_map(void)
262 {
263 void *ptr = hstart;
264
265         while (ptr < hend) {
266                 hdrtype_t hdr = *((hdrtype_t *) ptr);
267
268                 if (!HAS_MAGIC(hdr)) {
269                         printf("Poisoned magic - we're toast\n");
270                         break;
271                 }
272
273                 /* FIXME: Verify the size of the block. */
274
275                 printf("%x: %s (%x bytes)\n",
276                        (unsigned int)(ptr - hstart),
277                        hdr & FLAG_FREE ? "FREE" : "USED", SIZE(hdr));
278
279                 ptr += HDRSIZE + SIZE(hdr);
280         }
281 }
282 #endif