Release version 2.5.1.
[bertos.git] / 2.5 / 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  * \author Bernie Innocenti <bernie@codewiz.org>
36  */
37
38 #include "heap.h"
39
40 #include <cfg/debug.h> // ASSERT()
41 #include <string.h>    // memset()
42
43 #define FREE_FILL_CODE     0xDEAD
44 #define ALLOC_FILL_CODE    0xBEEF
45
46
47 /*
48  * This function prototype is deprecated, will change in:
49  * void heap_init(struct Heap* h, heap_buf_t* memory, size_t size)
50  * in the next BeRTOS release.
51  */
52 void heap_init(struct Heap* h, void* memory, size_t size)
53 {
54         #ifdef _DEBUG
55         memset(memory, FREE_FILL_CODE, size);
56         #endif
57
58         ASSERT2(((size_t)memory % alignof(heap_buf_t)) == 0,
59         "memory buffer is unaligned, please use the HEAP_DEFINE_BUF() macro to declare heap buffers!\n");
60
61         /* Initialize heap with a single big chunk */
62         h->FreeList = (MemChunk *)memory;
63         h->FreeList->next = NULL;
64         h->FreeList->size = size;
65 }
66
67
68 void *heap_allocmem(struct Heap* h, size_t size)
69 {
70         MemChunk *chunk, *prev;
71
72         /* Round size up to the allocation granularity */
73         size = ROUND_UP2(size, sizeof(MemChunk));
74
75         /* Handle allocations of 0 bytes */
76         if (!size)
77                 size = sizeof(MemChunk);
78
79         /* Walk on the free list looking for any chunk big enough to
80          * fit the requested block size.
81          */
82         for (prev = (MemChunk *)&h->FreeList, chunk = h->FreeList;
83                 chunk;
84                 prev = chunk, chunk = chunk->next)
85         {
86                 if (chunk->size >= size)
87                 {
88                         if (chunk->size == size)
89                         {
90                                 /* Just remove this chunk from the free list */
91                                 prev->next = chunk->next;
92                                 #ifdef _DEBUG
93                                         memset(chunk, ALLOC_FILL_CODE, size);
94                                 #endif
95                                 return (void *)chunk;
96                         }
97                         else
98                         {
99                                 /* Allocate from the END of an existing chunk */
100                                 chunk->size -= size;
101                                 #ifdef _DEBUG
102                                         memset((uint8_t *)chunk + chunk->size, ALLOC_FILL_CODE, size);
103                                 #endif
104                                 return (void *)((uint8_t *)chunk + chunk->size);
105                         }
106                 }
107         }
108
109         return NULL; /* fail */
110 }
111
112
113 void heap_freemem(struct Heap* h, void *mem, size_t size)
114 {
115         MemChunk *prev;
116         ASSERT(mem);
117
118 #ifdef _DEBUG
119         memset(mem, FREE_FILL_CODE, size);
120 #endif
121
122         /* Round size up to the allocation granularity */
123         size = ROUND_UP2(size, sizeof(MemChunk));
124
125         /* Handle allocations of 0 bytes */
126         if (!size)
127                 size = sizeof(MemChunk);
128
129         /* Special cases: first chunk in the free list or memory completely full */
130         ASSERT((uint8_t*)mem != (uint8_t*)h->FreeList);
131         if (((uint8_t *)mem) < ((uint8_t *)h->FreeList) || !h->FreeList)
132         {
133                 /* Insert memory block before the current free list head */
134                 prev = (MemChunk *)mem;
135                 prev->next = h->FreeList;
136                 prev->size = size;
137                 h->FreeList = prev;
138         }
139         else /* Normal case: not the first chunk in the free list */
140         {
141                 /*
142                  * Walk on the free list. Stop at the insertion point (when mem
143                  * is between prev and prev->next)
144                  */
145                 prev = h->FreeList;
146                 while (prev->next < (MemChunk *)mem && prev->next)
147                         prev = prev->next;
148
149                 /* Make sure mem is not *within* prev */
150                 ASSERT((uint8_t*)mem >= (uint8_t*)prev + prev->size);
151
152                 /* Should it be merged with previous block? */
153                 if (((uint8_t *)prev) + prev->size == ((uint8_t *)mem))
154                 {
155                         /* Yes */
156                         prev->size += size;
157                 }
158                 else /* not merged with previous chunk */
159                 {
160                         MemChunk *curr = (MemChunk*)mem;
161
162                         /* insert it after the previous node
163                          * and move the 'prev' pointer forward
164                          * for the following operations
165                          */
166                         curr->next = prev->next;
167                         curr->size = size;
168                         prev->next = curr;
169
170                         /* Adjust for the following test */
171                         prev = curr;
172                 }
173         }
174
175         /* Also merge with next chunk? */
176         if (((uint8_t *)prev) + prev->size == ((uint8_t *)prev->next))
177         {
178                 prev->size += prev->next->size;
179                 prev->next = prev->next->next;
180
181                 /* There should be only one merge opportunity, becuase we always merge on free */
182                 ASSERT((uint8_t*)prev + prev->size != (uint8_t*)prev->next);
183         }
184 }
185
186 /**
187  * Returns the number of free bytes in a heap.
188  * \param h the heap to check.
189  *
190  * \note The returned value is the sum of all free memory regions 
191  *       in the heap.
192  *       Those regions are likely to be *not* contiguous,
193  *       so a successive allocation may fail even if the
194  *       requested amount of memory is lower than the current free space.
195  */
196 size_t heap_freeSpace(struct Heap *h)
197 {
198         size_t free_mem = 0;
199         for (MemChunk *chunk = h->FreeList; chunk; chunk = chunk->next)
200                 free_mem += chunk->size;
201
202         return free_mem;
203 }
204
205 #if CONFIG_HEAP_MALLOC
206
207 void *heap_malloc(struct Heap* h, size_t size)
208 {
209         size_t *mem;
210
211         size += sizeof(size_t);
212         if ((mem = (size_t*)heap_allocmem(h, size)))
213                 *mem++ = size;
214
215         return mem;
216 }
217
218 void *heap_calloc(struct Heap* h, size_t size)
219 {
220         void *mem;
221
222         if ((mem = heap_malloc(h, size)))
223                 memset(mem, 0, size);
224
225         return mem;
226 }
227
228 /**
229  * Free a block of memory, determining its size automatically.
230  *
231  * \param h    Heap from which the block was allocated.
232  * \param mem  Pointer to a block of memory previously allocated with
233  *             either heap_malloc() or heap_calloc().
234  *
235  * \note If \a mem is a NULL pointer, no operation is performed.
236  *
237  * \note Freeing the same memory block twice has undefined behavior.
238  *
239  * \note This function works like the ANSI C free().
240  */
241 void heap_free(struct Heap *h, void *mem)
242 {
243         size_t *_mem = (size_t *)mem;
244
245         if (_mem)
246         {
247                 --_mem;
248                 heap_freemem(h, _mem, *_mem);
249         }
250 }
251
252 #endif /* CONFIG_HEAP_MALLOC */