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