]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/MemMang/heap_4.c
8de666d0b728d078d159b72b15eda75411934c48
[freertos] / FreeRTOS / Source / portable / MemMang / heap_4.c
1 /*\r
2     FreeRTOS V7.5.2 - Copyright (C) 2013 Real Time Engineers Ltd.\r
3 \r
4     VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.\r
5 \r
6     ***************************************************************************\r
7      *                                                                       *\r
8      *    FreeRTOS provides completely free yet professionally developed,    *\r
9      *    robust, strictly quality controlled, supported, and cross          *\r
10      *    platform software that has become a de facto standard.             *\r
11      *                                                                       *\r
12      *    Help yourself get started quickly and support the FreeRTOS         *\r
13      *    project by purchasing a FreeRTOS tutorial book, reference          *\r
14      *    manual, or both from: http://www.FreeRTOS.org/Documentation        *\r
15      *                                                                       *\r
16      *    Thank you!                                                         *\r
17      *                                                                       *\r
18     ***************************************************************************\r
19 \r
20     This file is part of the FreeRTOS distribution.\r
21 \r
22     FreeRTOS is free software; you can redistribute it and/or modify it under\r
23     the terms of the GNU General Public License (version 2) as published by the\r
24     Free Software Foundation >>!AND MODIFIED BY!<< the FreeRTOS exception.\r
25 \r
26     >>! NOTE: The modification to the GPL is included to allow you to distribute\r
27     >>! a combined work that includes FreeRTOS without being obliged to provide\r
28     >>! the source code for proprietary components outside of the FreeRTOS\r
29     >>! kernel.\r
30 \r
31     FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY\r
32     WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS\r
33     FOR A PARTICULAR PURPOSE.  Full license text is available from the following\r
34     link: http://www.freertos.org/a00114.html\r
35 \r
36     1 tab == 4 spaces!\r
37 \r
38     ***************************************************************************\r
39      *                                                                       *\r
40      *    Having a problem?  Start by reading the FAQ "My application does   *\r
41      *    not run, what could be wrong?"                                     *\r
42      *                                                                       *\r
43      *    http://www.FreeRTOS.org/FAQHelp.html                               *\r
44      *                                                                       *\r
45     ***************************************************************************\r
46 \r
47     http://www.FreeRTOS.org - Documentation, books, training, latest versions,\r
48     license and Real Time Engineers Ltd. contact details.\r
49 \r
50     http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,\r
51     including FreeRTOS+Trace - an indispensable productivity tool, a DOS\r
52     compatible FAT file system, and our tiny thread aware UDP/IP stack.\r
53 \r
54     http://www.OpenRTOS.com - Real Time Engineers ltd license FreeRTOS to High\r
55     Integrity Systems to sell under the OpenRTOS brand.  Low cost OpenRTOS\r
56     licenses offer ticketed support, indemnification and middleware.\r
57 \r
58     http://www.SafeRTOS.com - High Integrity Systems also provide a safety\r
59     engineered and independently SIL3 certified version for use in safety and\r
60     mission critical applications that require provable dependability.\r
61 \r
62     1 tab == 4 spaces!\r
63 */\r
64 \r
65 /*\r
66  * A sample implementation of pvPortMalloc() and vPortFree() that combines \r
67  * (coalescences) adjacent memory blocks as they are freed, and in so doing \r
68  * limits memory fragmentation.\r
69  *\r
70  * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the \r
71  * memory management pages of http://www.FreeRTOS.org for more information.\r
72  */\r
73 #include <stdlib.h>\r
74 \r
75 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining\r
76 all the API functions to use the MPU wrappers.  That should only be done when\r
77 task.h is included from an application file. */\r
78 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
79 \r
80 #include "FreeRTOS.h"\r
81 #include "task.h"\r
82 \r
83 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE\r
84 \r
85 /* Block sizes must not get too small. */\r
86 #define heapMINIMUM_BLOCK_SIZE  ( ( size_t ) ( heapSTRUCT_SIZE * 2 ) )\r
87 \r
88 /* Assumes 8bit bytes! */\r
89 #define heapBITS_PER_BYTE               ( ( size_t ) 8 )\r
90 \r
91 /* A few bytes might be lost to byte aligning the heap start address. */\r
92 #define heapADJUSTED_HEAP_SIZE  ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )\r
93 \r
94 /* Allocate the memory for the heap. */\r
95 static unsigned char ucHeap[ configTOTAL_HEAP_SIZE ];\r
96 \r
97 /* Define the linked list structure.  This is used to link free blocks in order\r
98 of their memory address. */\r
99 typedef struct A_BLOCK_LINK\r
100 {\r
101         struct A_BLOCK_LINK *pxNextFreeBlock;   /*<< The next free block in the list. */\r
102         size_t xBlockSize;                                              /*<< The size of the free block. */\r
103 } xBlockLink;\r
104 \r
105 /*-----------------------------------------------------------*/\r
106 \r
107 /*\r
108  * Inserts a block of memory that is being freed into the correct position in \r
109  * the list of free memory blocks.  The block being freed will be merged with\r
110  * the block in front it and/or the block behind it if the memory blocks are\r
111  * adjacent to each other.\r
112  */\r
113 static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert );\r
114 \r
115 /*\r
116  * Called automatically to setup the required heap structures the first time\r
117  * pvPortMalloc() is called.\r
118  */\r
119 static void prvHeapInit( void );\r
120 \r
121 /*-----------------------------------------------------------*/\r
122 \r
123 /* The size of the structure placed at the beginning of each allocated memory\r
124 block must by correctly byte aligned. */\r
125 static const unsigned short heapSTRUCT_SIZE     = ( ( sizeof ( xBlockLink ) + ( portBYTE_ALIGNMENT - 1 ) ) & ~portBYTE_ALIGNMENT_MASK );\r
126 \r
127 /* Ensure the pxEnd pointer will end up on the correct byte alignment. */\r
128 static const size_t xTotalHeapSize = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );\r
129 \r
130 /* Create a couple of list links to mark the start and end of the list. */\r
131 static xBlockLink xStart, *pxEnd = NULL;\r
132 \r
133 /* Keeps track of the number of free bytes remaining, but says nothing about\r
134 fragmentation. */\r
135 static size_t xFreeBytesRemaining = ( ( size_t ) heapADJUSTED_HEAP_SIZE ) & ( ( size_t ) ~portBYTE_ALIGNMENT_MASK );\r
136 \r
137 /* Gets set to the top bit of an size_t type.  When this bit in the xBlockSize \r
138 member of an xBlockLink structure is set then the block belongs to the \r
139 application.  When the bit is free the block is still part of the free heap\r
140 space. */\r
141 static size_t xBlockAllocatedBit = 0;\r
142 \r
143 /*-----------------------------------------------------------*/\r
144 \r
145 void *pvPortMalloc( size_t xWantedSize )\r
146 {\r
147 xBlockLink *pxBlock, *pxPreviousBlock, *pxNewBlockLink;\r
148 void *pvReturn = NULL;\r
149 \r
150         vTaskSuspendAll();\r
151         {\r
152                 /* If this is the first call to malloc then the heap will require\r
153                 initialisation to setup the list of free blocks. */\r
154                 if( pxEnd == NULL )\r
155                 {\r
156                         prvHeapInit();\r
157                 }\r
158 \r
159                 /* Check the requested block size is not so large that the top bit is\r
160                 set.  The top bit of the block size member of the xBlockLink structure \r
161                 is used to determine who owns the block - the application or the\r
162                 kernel, so it must be free. */\r
163                 if( ( xWantedSize & xBlockAllocatedBit ) == 0 )\r
164                 {\r
165                         /* The wanted size is increased so it can contain a xBlockLink\r
166                         structure in addition to the requested amount of bytes. */\r
167                         if( xWantedSize > 0 )\r
168                         {\r
169                                 xWantedSize += heapSTRUCT_SIZE;\r
170 \r
171                                 /* Ensure that blocks are always aligned to the required number \r
172                                 of bytes. */\r
173                                 if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )\r
174                                 {\r
175                                         /* Byte alignment required. */\r
176                                         xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r
177                                 }\r
178                         }\r
179 \r
180                         if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )\r
181                         {\r
182                                 /* Traverse the list from the start     (lowest address) block until \r
183                                 one     of adequate size is found. */\r
184                                 pxPreviousBlock = &xStart;\r
185                                 pxBlock = xStart.pxNextFreeBlock;\r
186                                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )\r
187                                 {\r
188                                         pxPreviousBlock = pxBlock;\r
189                                         pxBlock = pxBlock->pxNextFreeBlock;\r
190                                 }\r
191 \r
192                                 /* If the end marker was reached then a block of adequate size \r
193                                 was     not found. */\r
194                                 if( pxBlock != pxEnd )\r
195                                 {\r
196                                         /* Return the memory space pointed to - jumping over the \r
197                                         xBlockLink structure at its start. */\r
198                                         pvReturn = ( void * ) ( ( ( unsigned char * ) pxPreviousBlock->pxNextFreeBlock ) + heapSTRUCT_SIZE );\r
199 \r
200                                         /* This block is being returned for use so must be taken out \r
201                                         of the list of free blocks. */\r
202                                         pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;\r
203 \r
204                                         /* If the block is larger than required it can be split into \r
205                                         two. */\r
206                                         if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )\r
207                                         {\r
208                                                 /* This block is to be split into two.  Create a new \r
209                                                 block following the number of bytes requested. The void \r
210                                                 cast is used to prevent byte alignment warnings from the \r
211                                                 compiler. */\r
212                                                 pxNewBlockLink = ( void * ) ( ( ( unsigned char * ) pxBlock ) + xWantedSize );\r
213 \r
214                                                 /* Calculate the sizes of two blocks split from the \r
215                                                 single block. */\r
216                                                 pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;\r
217                                                 pxBlock->xBlockSize = xWantedSize;\r
218 \r
219                                                 /* Insert the new block into the list of free blocks. */\r
220                                                 prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );\r
221                                         }\r
222 \r
223                                         xFreeBytesRemaining -= pxBlock->xBlockSize;\r
224 \r
225                                         /* The block is being returned - it is allocated and owned\r
226                                         by the application and has no "next" block. */\r
227                                         pxBlock->xBlockSize |= xBlockAllocatedBit;\r
228                                         pxBlock->pxNextFreeBlock = NULL;\r
229                                 }\r
230                         }\r
231                 }\r
232 \r
233                 traceMALLOC( pvReturn, xWantedSize );\r
234         }\r
235         xTaskResumeAll();\r
236 \r
237         #if( configUSE_MALLOC_FAILED_HOOK == 1 )\r
238         {\r
239                 if( pvReturn == NULL )\r
240                 {\r
241                         extern void vApplicationMallocFailedHook( void );\r
242                         vApplicationMallocFailedHook();\r
243                 }\r
244         }\r
245         #endif\r
246 \r
247         return pvReturn;\r
248 }\r
249 /*-----------------------------------------------------------*/\r
250 \r
251 void vPortFree( void *pv )\r
252 {\r
253 unsigned char *puc = ( unsigned char * ) pv;\r
254 xBlockLink *pxLink;\r
255 \r
256         if( pv != NULL )\r
257         {\r
258                 /* The memory being freed will have an xBlockLink structure immediately\r
259                 before it. */\r
260                 puc -= heapSTRUCT_SIZE;\r
261 \r
262                 /* This casting is to keep the compiler from issuing warnings. */\r
263                 pxLink = ( void * ) puc;\r
264 \r
265                 /* Check the block is actually allocated. */\r
266                 configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );\r
267                 configASSERT( pxLink->pxNextFreeBlock == NULL );\r
268                 \r
269                 if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )\r
270                 {\r
271                         if( pxLink->pxNextFreeBlock == NULL )\r
272                         {\r
273                                 /* The block is being returned to the heap - it is no longer\r
274                                 allocated. */\r
275                                 pxLink->xBlockSize &= ~xBlockAllocatedBit;\r
276 \r
277                                 vTaskSuspendAll();\r
278                                 {\r
279                                         /* Add this block to the list of free blocks. */\r
280                                         xFreeBytesRemaining += pxLink->xBlockSize;\r
281                                         prvInsertBlockIntoFreeList( ( ( xBlockLink * ) pxLink ) );\r
282                                         traceFREE( pv, pxLink->xBlockSize );\r
283                                 }\r
284                                 xTaskResumeAll();\r
285                         }\r
286                 }\r
287         }\r
288 }\r
289 /*-----------------------------------------------------------*/\r
290 \r
291 size_t xPortGetFreeHeapSize( void )\r
292 {\r
293         return xFreeBytesRemaining;\r
294 }\r
295 /*-----------------------------------------------------------*/\r
296 \r
297 void vPortInitialiseBlocks( void )\r
298 {\r
299         /* This just exists to keep the linker quiet. */\r
300 }\r
301 /*-----------------------------------------------------------*/\r
302 \r
303 static void prvHeapInit( void )\r
304 {\r
305 xBlockLink *pxFirstFreeBlock;\r
306 unsigned char *pucHeapEnd, *pucAlignedHeap;\r
307 \r
308         /* Ensure the heap starts on a correctly aligned boundary. */\r
309         pucAlignedHeap = ( unsigned char * ) ( ( ( portPOINTER_SIZE_TYPE ) &ucHeap[ portBYTE_ALIGNMENT ] ) & ( ( portPOINTER_SIZE_TYPE ) ~portBYTE_ALIGNMENT_MASK ) );\r
310 \r
311         /* xStart is used to hold a pointer to the first item in the list of free\r
312         blocks.  The void cast is used to prevent compiler warnings. */\r
313         xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;\r
314         xStart.xBlockSize = ( size_t ) 0;\r
315 \r
316         /* pxEnd is used to mark the end of the list of free blocks and is inserted\r
317         at the end of the heap space. */\r
318         pucHeapEnd = pucAlignedHeap + xTotalHeapSize;\r
319         pucHeapEnd -= heapSTRUCT_SIZE;\r
320         pxEnd = ( void * ) pucHeapEnd;\r
321         configASSERT( ( ( ( unsigned long ) pxEnd ) & ( ( unsigned long ) portBYTE_ALIGNMENT_MASK ) ) == 0UL );\r
322         pxEnd->xBlockSize = 0;\r
323         pxEnd->pxNextFreeBlock = NULL;\r
324 \r
325         /* To start with there is a single free block that is sized to take up the\r
326         entire heap space, minus the space taken by pxEnd. */\r
327         pxFirstFreeBlock = ( void * ) pucAlignedHeap;\r
328         pxFirstFreeBlock->xBlockSize = xTotalHeapSize - heapSTRUCT_SIZE;\r
329         pxFirstFreeBlock->pxNextFreeBlock = pxEnd;\r
330 \r
331         /* The heap now contains pxEnd. */\r
332         xFreeBytesRemaining -= heapSTRUCT_SIZE;\r
333 \r
334         /* Work out the position of the top bit in a size_t variable. */\r
335         xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );\r
336 }\r
337 /*-----------------------------------------------------------*/\r
338 \r
339 static void prvInsertBlockIntoFreeList( xBlockLink *pxBlockToInsert )\r
340 {\r
341 xBlockLink *pxIterator;\r
342 unsigned char *puc;\r
343 \r
344         /* Iterate through the list until a block is found that has a higher address\r
345         than the block being inserted. */\r
346         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )\r
347         {\r
348                 /* Nothing to do here, just iterate to the right position. */\r
349         }\r
350 \r
351         /* Do the block being inserted, and the block it is being inserted after\r
352         make a contiguous block of memory? */   \r
353         puc = ( unsigned char * ) pxIterator;\r
354         if( ( puc + pxIterator->xBlockSize ) == ( unsigned char * ) pxBlockToInsert )\r
355         {\r
356                 pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;\r
357                 pxBlockToInsert = pxIterator;\r
358         }\r
359 \r
360         /* Do the block being inserted, and the block it is being inserted before\r
361         make a contiguous block of memory? */\r
362         puc = ( unsigned char * ) pxBlockToInsert;\r
363         if( ( puc + pxBlockToInsert->xBlockSize ) == ( unsigned char * ) pxIterator->pxNextFreeBlock )\r
364         {\r
365                 if( pxIterator->pxNextFreeBlock != pxEnd )\r
366                 {\r
367                         /* Form one big block from the two blocks. */\r
368                         pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;\r
369                         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;\r
370                 }\r
371                 else\r
372                 {\r
373                         pxBlockToInsert->pxNextFreeBlock = pxEnd;\r
374                 }\r
375         }\r
376         else\r
377         {\r
378                 pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;         \r
379         }\r
380 \r
381         /* If the block being inserted plugged a gab, so was merged with the block\r
382         before and the block after, then it's pxNextFreeBlock pointer will have\r
383         already been set, and should not be set here as that would make it point\r
384         to itself. */\r
385         if( pxIterator != pxBlockToInsert )\r
386         {\r
387                 pxIterator->pxNextFreeBlock = pxBlockToInsert;\r
388         }\r
389 }\r
390 \r