2375c1f140ebcd2267090f4285edd91c295fdf56
[bertos.git] / bertos / struct / heap.c
1 /**
2  * \file
3  * <!--
4  * This file is part of BeRTOS.
5  *
6  * Bertos is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 2 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
19  *
20  * As a special exception, you may use this file as part of a free software
21  * library without restriction.  Specifically, if other files instantiate
22  * templates or use macros or inline functions from this file, or you compile
23  * this file and link it with other files to produce an executable, this
24  * file does not by itself cause the resulting executable to be covered by
25  * the GNU General Public License.  This exception does not however
26  * invalidate any other reasons why the executable file might be covered by
27  * the GNU General Public License.
28  *
29  * Copyright 2004 Develer S.r.l. (http://www.develer.com/)
30  * Copyright 1999, 2000, 2001, 2008 Bernie Innocenti <bernie@codewiz.org>
31  * -->
32  *
33  * \brief Heap subsystem (public interface).
34  *
35  * \version $Id: heap.c 1532 2008-08-04 07:21:26Z bernie $
36  * \author Bernie Innocenti <bernie@codewiz.org>
37  */
38
39 #include "heap.h"
40
41 #include <cfg/macros.h>           // IS_POW2()
42 #include <cfg/debug.h>            // ASSERT()
43
44 #include <string.h>           // memset()
45
46 /* NOTE: struct size must be a 2's power! */
47 typedef struct _MemChunk
48 {
49         struct _MemChunk *next;
50         size_t size;
51 } MemChunk;
52
53 STATIC_ASSERT(IS_POW2(sizeof(MemChunk)));
54
55 #define FREE_FILL_CODE     0xDEAD
56 #define ALLOC_FILL_CODE    0xBEEF
57
58 void heap_init(struct Heap* h, void* memory, size_t size)
59 {
60 #ifdef _DEBUG
61         memset(memory, FREE_FILL_CODE, size);
62 #endif
63
64         /* Initialize heap with a single big chunk */
65         h->FreeList = (MemChunk *)memory;
66         h->FreeList->next = NULL;
67         h->FreeList->size = size;
68 }
69
70
71 void *heap_allocmem(struct Heap* h, size_t size)
72 {
73         MemChunk *chunk, *prev;
74
75         /* Round size up to the allocation granularity */
76         size = ROUND_UP2(size, sizeof(MemChunk));
77
78         /* Handle allocations of 0 bytes */
79         if (!size)
80                 size = sizeof(MemChunk);
81
82         /* Walk on the free list looking for any chunk big enough to
83          * fit the requested block size.
84          */
85         for (prev = (MemChunk *)&h->FreeList, chunk = h->FreeList;
86                 chunk;
87                 prev = chunk, chunk = chunk->next)
88         {
89                 if (chunk->size >= size)
90                 {
91                         if (chunk->size == size)
92                         {
93                                 /* Just remove this chunk from the free list */
94                                 prev->next = chunk->next;
95                                 #ifdef _DEBUG
96                                         memset(chunk, ALLOC_FILL_CODE, size);
97                                 #endif
98                                 return (void *)chunk;
99                         }
100                         else
101                         {
102                                 /* Allocate from the END of an existing chunk */
103                                 chunk->size -= size;
104                                 #ifdef _DEBUG
105                                         memset((uint8_t *)chunk + chunk->size, ALLOC_FILL_CODE, size);
106                                 #endif
107                                 return (void *)((uint8_t *)chunk + chunk->size);
108                         }
109                 }
110         }
111
112         return NULL; /* fail */
113 }
114
115
116 void heap_freemem(struct Heap* h, void *mem, size_t size)
117 {
118         MemChunk *prev;
119         ASSERT(mem);
120
121 #ifdef _DEBUG
122         memset(mem, FREE_FILL_CODE, size);
123 #endif
124
125         /* Round size up to the allocation granularity */
126         size = ROUND_UP2(size, sizeof(MemChunk));
127
128         /* Handle allocations of 0 bytes */
129         if (!size)
130                 size = sizeof(MemChunk);
131
132         /* Special case: first chunk in the free list */
133         ASSERT((uint8_t*)mem != (uint8_t*)h->FreeList);
134         if (((uint8_t *)mem) < ((uint8_t *)h->FreeList))
135         {
136                 /* Insert memory block before the current free list head */
137                 prev = (MemChunk *)mem;
138                 prev->next = h->FreeList;
139                 prev->size = size;
140                 h->FreeList = prev;
141         }
142         else /* Normal case: not the first chunk in the free list */
143         {
144                 /*
145                  * Walk on the free list. Stop at the insertion point (when mem
146                  * is between prev and prev->next)
147                  */
148                 prev = h->FreeList;
149                 while (prev->next < (MemChunk *)mem && prev->next)
150                         prev = prev->next;
151
152                 /* Make sure mem is not *within* prev */
153                 ASSERT((uint8_t*)mem >= (uint8_t*)prev + prev->size);
154
155                 /* Should it be merged with previous block? */
156                 if (((uint8_t *)prev) + prev->size == ((uint8_t *)mem))
157                 {
158                         /* Yes */
159                         prev->size += size;
160                 }
161                 else /* not merged with previous chunk */
162                 {
163                         MemChunk *curr = (MemChunk*)mem;
164
165                         /* insert it after the previous node
166                          * and move the 'prev' pointer forward
167                          * for the following operations
168                          */
169                         curr->next = prev->next;
170                         curr->size = size;
171                         prev->next = curr;
172
173                         /* Adjust for the following test */
174                         prev = curr;
175                 }
176         }
177
178         /* Also merge with next chunk? */
179         if (((uint8_t *)prev) + prev->size == ((uint8_t *)prev->next))
180         {
181                 prev->size += prev->next->size;
182                 prev->next = prev->next->next;
183
184                 /* There should be only one merge opportunity, becuase we always merge on free */
185                 ASSERT((uint8_t*)prev + prev->size != (uint8_t*)prev->next);
186         }
187 }
188
189 #if CONFIG_HEAP_MALLOC
190
191 void *heap_malloc(struct Heap* h, size_t size)
192 {
193         size_t *mem;
194
195         size += sizeof(size_t);
196         if ((mem = (size_t*)heap_allocmem(h, size)))
197                 *mem++ = size;
198
199         return mem;
200 }
201
202 void *heap_calloc(struct Heap* h, size_t size)
203 {
204         void *mem;
205
206         if ((mem = heap_malloc(h, size)))
207                 memset(mem, 0, size);
208
209         return mem;
210 }
211
212 /**
213  * Free a block of memory, determining its size automatically.
214  *
215  * \param h    Heap from which the block was allocated.
216  * \param mem  Pointer to a block of memory previously allocated with
217  *             either heap_malloc() or heap_calloc().
218  *
219  * \note If \a mem is a NULL pointer, no operation is performed.
220  *
221  * \note Freeing the same memory block twice has undefined behavior.
222  *
223  * \note This function works like the ANSI C free().
224  */
225 void heap_free(struct Heap *h, void *mem)
226 {
227         size_t *_mem = (size_t *)mem;
228
229         if (_mem)
230         {
231                 --_mem;
232                 heap_freemem(h, _mem, *_mem);
233         }
234 }
235
236 #endif /* CONFIG_HEAP_MALLOC */