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