]> git.sur5r.net Git - freertos/blob - FreeRTOS/Source/portable/MemMang/heap_4.c
5394be79eed5e3914cb99468b08b19adadbf5f89
[freertos] / FreeRTOS / Source / portable / MemMang / heap_4.c
1 /*\r
2     FreeRTOS V9.0.0rc1 - Copyright (C) 2016 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 #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 )\r
91         #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0\r
92 #endif\r
93 \r
94 /* Block sizes must not get too small. */\r
95 #define heapMINIMUM_BLOCK_SIZE  ( ( size_t ) ( xHeapStructSize << 1 ) )\r
96 \r
97 /* Assumes 8bit bytes! */\r
98 #define heapBITS_PER_BYTE               ( ( size_t ) 8 )\r
99 \r
100 /* Allocate the memory for the heap. */\r
101 #if( configAPPLICATION_ALLOCATED_HEAP == 1 )\r
102         /* The application writer has already defined the array used for the RTOS\r
103         heap - probably so it can be placed in a special segment or address. */\r
104         extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];\r
105 #else\r
106         static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];\r
107 #endif /* configAPPLICATION_ALLOCATED_HEAP */\r
108 \r
109 /* Define the linked list structure.  This is used to link free blocks in order\r
110 of their memory address. */\r
111 typedef struct A_BLOCK_LINK\r
112 {\r
113         struct A_BLOCK_LINK *pxNextFreeBlock;   /*<< The next free block in the list. */\r
114         size_t xBlockSize;                                              /*<< The size of the free block. */\r
115 } BlockLink_t;\r
116 \r
117 /*-----------------------------------------------------------*/\r
118 \r
119 /*\r
120  * Inserts a block of memory that is being freed into the correct position in\r
121  * the list of free memory blocks.  The block being freed will be merged with\r
122  * the block in front it and/or the block behind it if the memory blocks are\r
123  * adjacent to each other.\r
124  */\r
125 static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );\r
126 \r
127 /*\r
128  * Called automatically to setup the required heap structures the first time\r
129  * pvPortMalloc() is called.\r
130  */\r
131 static void prvHeapInit( void );\r
132 \r
133 /*-----------------------------------------------------------*/\r
134 \r
135 /* The size of the structure placed at the beginning of each allocated memory\r
136 block must by correctly byte aligned. */\r
137 static const size_t xHeapStructSize     = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );\r
138 \r
139 /* Create a couple of list links to mark the start and end of the list. */\r
140 static BlockLink_t xStart, *pxEnd = NULL;\r
141 \r
142 /* Keeps track of the number of free bytes remaining, but says nothing about\r
143 fragmentation. */\r
144 static size_t xFreeBytesRemaining = 0U;\r
145 static size_t xMinimumEverFreeBytesRemaining = 0U;\r
146 \r
147 /* Gets set to the top bit of an size_t type.  When this bit in the xBlockSize\r
148 member of an BlockLink_t structure is set then the block belongs to the\r
149 application.  When the bit is free the block is still part of the free heap\r
150 space. */\r
151 static size_t xBlockAllocatedBit = 0;\r
152 \r
153 /*-----------------------------------------------------------*/\r
154 \r
155 void *pvPortMalloc( size_t xWantedSize )\r
156 {\r
157 BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;\r
158 void *pvReturn = NULL;\r
159 \r
160         vTaskSuspendAll();\r
161         {\r
162                 /* If this is the first call to malloc then the heap will require\r
163                 initialisation to setup the list of free blocks. */\r
164                 if( pxEnd == NULL )\r
165                 {\r
166                         prvHeapInit();\r
167                 }\r
168                 else\r
169                 {\r
170                         mtCOVERAGE_TEST_MARKER();\r
171                 }\r
172 \r
173                 /* Check the requested block size is not so large that the top bit is\r
174                 set.  The top bit of the block size member of the BlockLink_t structure\r
175                 is used to determine who owns the block - the application or the\r
176                 kernel, so it must be free. */\r
177                 if( ( xWantedSize & xBlockAllocatedBit ) == 0 )\r
178                 {\r
179                         /* The wanted size is increased so it can contain a BlockLink_t\r
180                         structure in addition to the requested amount of bytes. */\r
181                         if( xWantedSize > 0 )\r
182                         {\r
183                                 xWantedSize += xHeapStructSize;\r
184 \r
185                                 /* Ensure that blocks are always aligned to the required number\r
186                                 of bytes. */\r
187                                 if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )\r
188                                 {\r
189                                         /* Byte alignment required. */\r
190                                         xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );\r
191                                         configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );\r
192                                 }\r
193                                 else\r
194                                 {\r
195                                         mtCOVERAGE_TEST_MARKER();\r
196                                 }\r
197                         }\r
198                         else\r
199                         {\r
200                                 mtCOVERAGE_TEST_MARKER();\r
201                         }\r
202 \r
203                         if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )\r
204                         {\r
205                                 /* Traverse the list from the start     (lowest address) block until\r
206                                 one     of adequate size is found. */\r
207                                 pxPreviousBlock = &xStart;\r
208                                 pxBlock = xStart.pxNextFreeBlock;\r
209                                 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )\r
210                                 {\r
211                                         pxPreviousBlock = pxBlock;\r
212                                         pxBlock = pxBlock->pxNextFreeBlock;\r
213                                 }\r
214 \r
215                                 /* If the end marker was reached then a block of adequate size\r
216                                 was     not found. */\r
217                                 if( pxBlock != pxEnd )\r
218                                 {\r
219                                         /* Return the memory space pointed to - jumping over the\r
220                                         BlockLink_t structure at its start. */\r
221                                         pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );\r
222 \r
223                                         /* This block is being returned for use so must be taken out\r
224                                         of the list of free blocks. */\r
225                                         pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;\r
226 \r
227                                         /* If the block is larger than required it can be split into\r
228                                         two. */\r
229                                         if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )\r
230                                         {\r
231                                                 /* This block is to be split into two.  Create a new\r
232                                                 block following the number of bytes requested. The void\r
233                                                 cast is used to prevent byte alignment warnings from the\r
234                                                 compiler. */\r
235                                                 pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );\r
236                                                 configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );\r
237 \r
238                                                 /* Calculate the sizes of two blocks split from the\r
239                                                 single block. */\r
240                                                 pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;\r
241                                                 pxBlock->xBlockSize = xWantedSize;\r
242 \r
243                                                 /* Insert the new block into the list of free blocks. */\r
244                                                 prvInsertBlockIntoFreeList( pxNewBlockLink );\r
245                                         }\r
246                                         else\r
247                                         {\r
248                                                 mtCOVERAGE_TEST_MARKER();\r
249                                         }\r
250 \r
251                                         xFreeBytesRemaining -= pxBlock->xBlockSize;\r
252 \r
253                                         if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )\r
254                                         {\r
255                                                 xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;\r
256                                         }\r
257                                         else\r
258                                         {\r
259                                                 mtCOVERAGE_TEST_MARKER();\r
260                                         }\r
261 \r
262                                         /* The block is being returned - it is allocated and owned\r
263                                         by the application and has no "next" block. */\r
264                                         pxBlock->xBlockSize |= xBlockAllocatedBit;\r
265                                         pxBlock->pxNextFreeBlock = NULL;\r
266                                 }\r
267                                 else\r
268                                 {\r
269                                         mtCOVERAGE_TEST_MARKER();\r
270                                 }\r
271                         }\r
272                         else\r
273                         {\r
274                                 mtCOVERAGE_TEST_MARKER();\r
275                         }\r
276                 }\r
277                 else\r
278                 {\r
279                         mtCOVERAGE_TEST_MARKER();\r
280                 }\r
281 \r
282                 traceMALLOC( pvReturn, xWantedSize );\r
283         }\r
284         ( void ) xTaskResumeAll();\r
285 \r
286         #if( configUSE_MALLOC_FAILED_HOOK == 1 )\r
287         {\r
288                 if( pvReturn == NULL )\r
289                 {\r
290                         extern void vApplicationMallocFailedHook( void );\r
291                         vApplicationMallocFailedHook();\r
292                 }\r
293                 else\r
294                 {\r
295                         mtCOVERAGE_TEST_MARKER();\r
296                 }\r
297         }\r
298         #endif\r
299 \r
300         configASSERT( ( ( ( uint32_t ) pvReturn ) & portBYTE_ALIGNMENT_MASK ) == 0 );\r
301         return pvReturn;\r
302 }\r
303 /*-----------------------------------------------------------*/\r
304 \r
305 void vPortFree( void *pv )\r
306 {\r
307 uint8_t *puc = ( uint8_t * ) pv;\r
308 BlockLink_t *pxLink;\r
309 \r
310         if( pv != NULL )\r
311         {\r
312                 /* The memory being freed will have an BlockLink_t structure immediately\r
313                 before it. */\r
314                 puc -= xHeapStructSize;\r
315 \r
316                 /* This casting is to keep the compiler from issuing warnings. */\r
317                 pxLink = ( void * ) puc;\r
318 \r
319                 /* Check the block is actually allocated. */\r
320                 configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );\r
321                 configASSERT( pxLink->pxNextFreeBlock == NULL );\r
322 \r
323                 if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )\r
324                 {\r
325                         if( pxLink->pxNextFreeBlock == NULL )\r
326                         {\r
327                                 /* The block is being returned to the heap - it is no longer\r
328                                 allocated. */\r
329                                 pxLink->xBlockSize &= ~xBlockAllocatedBit;\r
330 \r
331                                 vTaskSuspendAll();\r
332                                 {\r
333                                         /* Add this block to the list of free blocks. */\r
334                                         xFreeBytesRemaining += pxLink->xBlockSize;\r
335                                         traceFREE( pv, pxLink->xBlockSize );\r
336                                         prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );\r
337                                 }\r
338                                 ( void ) xTaskResumeAll();\r
339                         }\r
340                         else\r
341                         {\r
342                                 mtCOVERAGE_TEST_MARKER();\r
343                         }\r
344                 }\r
345                 else\r
346                 {\r
347                         mtCOVERAGE_TEST_MARKER();\r
348                 }\r
349         }\r
350 }\r
351 /*-----------------------------------------------------------*/\r
352 \r
353 size_t xPortGetFreeHeapSize( void )\r
354 {\r
355         return xFreeBytesRemaining;\r
356 }\r
357 /*-----------------------------------------------------------*/\r
358 \r
359 size_t xPortGetMinimumEverFreeHeapSize( void )\r
360 {\r
361         return xMinimumEverFreeBytesRemaining;\r
362 }\r
363 /*-----------------------------------------------------------*/\r
364 \r
365 void vPortInitialiseBlocks( void )\r
366 {\r
367         /* This just exists to keep the linker quiet. */\r
368 }\r
369 /*-----------------------------------------------------------*/\r
370 \r
371 static void prvHeapInit( void )\r
372 {\r
373 BlockLink_t *pxFirstFreeBlock;\r
374 uint8_t *pucAlignedHeap;\r
375 size_t uxAddress;\r
376 size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;\r
377 \r
378         /* Ensure the heap starts on a correctly aligned boundary. */\r
379         uxAddress = ( size_t ) ucHeap;\r
380 \r
381         if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )\r
382         {\r
383                 uxAddress += ( portBYTE_ALIGNMENT - 1 );\r
384                 uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );\r
385                 xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;\r
386         }\r
387 \r
388         pucAlignedHeap = ( uint8_t * ) uxAddress;\r
389 \r
390         /* xStart is used to hold a pointer to the first item in the list of free\r
391         blocks.  The void cast is used to prevent compiler warnings. */\r
392         xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;\r
393         xStart.xBlockSize = ( size_t ) 0;\r
394 \r
395         /* pxEnd is used to mark the end of the list of free blocks and is inserted\r
396         at the end of the heap space. */\r
397         uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;\r
398         uxAddress -= xHeapStructSize;\r
399         uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );\r
400         pxEnd = ( void * ) uxAddress;\r
401         pxEnd->xBlockSize = 0;\r
402         pxEnd->pxNextFreeBlock = NULL;\r
403 \r
404         /* To start with there is a single free block that is sized to take up the\r
405         entire heap space, minus the space taken by pxEnd. */\r
406         pxFirstFreeBlock = ( void * ) pucAlignedHeap;\r
407         pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;\r
408         pxFirstFreeBlock->pxNextFreeBlock = pxEnd;\r
409 \r
410         /* Only one block exists - and it covers the entire usable heap space. */\r
411         xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;\r
412         xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;\r
413 \r
414         /* Work out the position of the top bit in a size_t variable. */\r
415         xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );\r
416 }\r
417 /*-----------------------------------------------------------*/\r
418 \r
419 static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )\r
420 {\r
421 BlockLink_t *pxIterator;\r
422 uint8_t *puc;\r
423 \r
424         /* Iterate through the list until a block is found that has a higher address\r
425         than the block being inserted. */\r
426         for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )\r
427         {\r
428                 /* Nothing to do here, just iterate to the right position. */\r
429         }\r
430 \r
431         /* Do the block being inserted, and the block it is being inserted after\r
432         make a contiguous block of memory? */\r
433         puc = ( uint8_t * ) pxIterator;\r
434         if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )\r
435         {\r
436                 pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;\r
437                 pxBlockToInsert = pxIterator;\r
438         }\r
439         else\r
440         {\r
441                 mtCOVERAGE_TEST_MARKER();\r
442         }\r
443 \r
444         /* Do the block being inserted, and the block it is being inserted before\r
445         make a contiguous block of memory? */\r
446         puc = ( uint8_t * ) pxBlockToInsert;\r
447         if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )\r
448         {\r
449                 if( pxIterator->pxNextFreeBlock != pxEnd )\r
450                 {\r
451                         /* Form one big block from the two blocks. */\r
452                         pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;\r
453                         pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;\r
454                 }\r
455                 else\r
456                 {\r
457                         pxBlockToInsert->pxNextFreeBlock = pxEnd;\r
458                 }\r
459         }\r
460         else\r
461         {\r
462                 pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;\r
463         }\r
464 \r
465         /* If the block being inserted plugged a gab, so was merged with the block\r
466         before and the block after, then it's pxNextFreeBlock pointer will have\r
467         already been set, and should not be set here as that would make it point\r
468         to itself. */\r
469         if( pxIterator != pxBlockToInsert )\r
470         {\r
471                 pxIterator->pxNextFreeBlock = pxBlockToInsert;\r
472         }\r
473         else\r
474         {\r
475                 mtCOVERAGE_TEST_MARKER();\r
476         }\r
477 }\r
478 \r