2 * FreeRTOS Kernel V11.1.0
3 * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
5 * SPDX-License-Identifier: MIT
7 * Permission is hereby granted, free of charge, to any person obtaining a copy of
8 * this software and associated documentation files (the "Software"), to deal in
9 * the Software without restriction, including without limitation the rights to
10 * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11 * the Software, and to permit persons to whom the Software is furnished to do so,
12 * subject to the following conditions:
14 * The above copyright notice and this permission notice shall be included in all
15 * copies or substantial portions of the Software.
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
19 * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
20 * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
21 * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
22 * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24 * https://www.FreeRTOS.org
25 * https://github.com/FreeRTOS
30 * A sample implementation of pvPortMalloc() and vPortFree() that permits
31 * allocated blocks to be freed, but does not combine adjacent free blocks
32 * into a single larger block (and so will fragment memory). See heap_4.c for
33 * an equivalent that does combine adjacent blocks into single larger blocks.
35 * See heap_1.c, heap_3.c and heap_4.c for alternative implementations, and the
36 * memory management pages of https://www.FreeRTOS.org for more information.
41 /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
42 * all the API functions to use the MPU wrappers. That should only be done when
43 * task.h is included from an application file. */
44 #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
49 #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
51 #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
52 #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
55 #ifndef configHEAP_CLEAR_MEMORY_ON_FREE
56 #define configHEAP_CLEAR_MEMORY_ON_FREE 0
59 /* A few bytes might be lost to byte aligning the heap start address. */
60 #define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
62 /* Assumes 8bit bytes! */
63 #define heapBITS_PER_BYTE ( ( size_t ) 8 )
65 /* Max value that fits in a size_t type. */
66 #define heapSIZE_MAX ( ~( ( size_t ) 0 ) )
68 /* Check if multiplying a and b will result in overflow. */
69 #define heapMULTIPLY_WILL_OVERFLOW( a, b ) ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )
71 /* Check if adding a and b will result in overflow. */
72 #define heapADD_WILL_OVERFLOW( a, b ) ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
74 /* MSB of the xBlockSize member of an BlockLink_t structure is used to track
75 * the allocation status of a block. When MSB of the xBlockSize member of
76 * an BlockLink_t structure is set then the block belongs to the application.
77 * When the bit is free the block is still part of the free heap space. */
78 #define heapBLOCK_ALLOCATED_BITMASK ( ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ) )
79 #define heapBLOCK_SIZE_IS_VALID( xBlockSize ) ( ( ( xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) == 0 )
80 #define heapBLOCK_IS_ALLOCATED( pxBlock ) ( ( ( pxBlock->xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) != 0 )
81 #define heapALLOCATE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) |= heapBLOCK_ALLOCATED_BITMASK )
82 #define heapFREE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) &= ~heapBLOCK_ALLOCATED_BITMASK )
84 /*-----------------------------------------------------------*/
86 /* Allocate the memory for the heap. */
87 #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
89 /* The application writer has already defined the array used for the RTOS
90 * heap - probably so it can be placed in a special segment or address. */
91 extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
93 PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
94 #endif /* configAPPLICATION_ALLOCATED_HEAP */
97 /* Define the linked list structure. This is used to link free blocks in order
99 typedef struct A_BLOCK_LINK
101 struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */
102 size_t xBlockSize; /*<< The size of the free block. */
106 static const size_t xHeapStructSize = ( ( sizeof( BlockLink_t ) + ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ) );
107 #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize * 2 ) )
109 /* Create a couple of list links to mark the start and end of the list. */
110 PRIVILEGED_DATA static BlockLink_t xStart, xEnd;
112 /* Keeps track of the number of free bytes remaining, but says nothing about
114 PRIVILEGED_DATA static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
116 /* Indicates whether the heap has been initialised or not. */
117 PRIVILEGED_DATA static BaseType_t xHeapHasBeenInitialised = pdFALSE;
119 /*-----------------------------------------------------------*/
122 * Initialises the heap structures before their first use.
124 static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
126 /*-----------------------------------------------------------*/
128 /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */
131 * Insert a block into the list of free blocks - which is ordered by size of
132 * the block. Small blocks at the start of the list and large blocks at the end
135 #define prvInsertBlockIntoFreeList( pxBlockToInsert ) \
137 BlockLink_t * pxIterator; \
140 xBlockSize = pxBlockToInsert->xBlockSize; \
142 /* Iterate through the list until a block is found that has a larger size */ \
143 /* than the block we are inserting. */ \
144 for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \
146 /* There is nothing to do here - just iterate to the correct position. */ \
149 /* Update the list to include the block being inserted in the correct */ \
151 pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \
152 pxIterator->pxNextFreeBlock = pxBlockToInsert; \
154 /*-----------------------------------------------------------*/
156 void * pvPortMalloc( size_t xWantedSize )
158 BlockLink_t * pxBlock;
159 BlockLink_t * pxPreviousBlock;
160 BlockLink_t * pxNewBlockLink;
161 void * pvReturn = NULL;
162 size_t xAdditionalRequiredSize;
164 if( xWantedSize > 0 )
166 /* The wanted size must be increased so it can contain a BlockLink_t
167 * structure in addition to the requested amount of bytes. */
168 if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
170 xWantedSize += xHeapStructSize;
172 /* Ensure that blocks are always aligned to the required number
174 if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
176 /* Byte alignment required. */
177 xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
179 if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
181 xWantedSize += xAdditionalRequiredSize;
190 mtCOVERAGE_TEST_MARKER();
200 mtCOVERAGE_TEST_MARKER();
205 /* If this is the first call to malloc then the heap will require
206 * initialisation to setup the list of free blocks. */
207 if( xHeapHasBeenInitialised == pdFALSE )
210 xHeapHasBeenInitialised = pdTRUE;
213 /* Check the block size we are trying to allocate is not so large that the
214 * top bit is set. The top bit of the block size member of the BlockLink_t
215 * structure is used to determine who owns the block - the application or
216 * the kernel, so it must be free. */
217 if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
219 if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
221 /* Blocks are stored in byte order - traverse the list from the start
222 * (smallest) block until one of adequate size is found. */
223 pxPreviousBlock = &xStart;
224 pxBlock = xStart.pxNextFreeBlock;
226 while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
228 pxPreviousBlock = pxBlock;
229 pxBlock = pxBlock->pxNextFreeBlock;
232 /* If we found the end marker then a block of adequate size was not found. */
233 if( pxBlock != &xEnd )
235 /* Return the memory space - jumping over the BlockLink_t structure
237 pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
239 /* This block is being returned for use so must be taken out of the
240 * list of free blocks. */
241 pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
243 /* If the block is larger than required it can be split into two. */
244 if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
246 /* This block is to be split into two. Create a new block
247 * following the number of bytes requested. The void cast is
248 * used to prevent byte alignment warnings from the compiler. */
249 pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
251 /* Calculate the sizes of two blocks split from the single
253 pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
254 pxBlock->xBlockSize = xWantedSize;
256 /* Insert the new block into the list of free blocks.
257 * The list of free blocks is sorted by their size, we have to
258 * iterate to find the right place to insert new block. */
259 prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
262 xFreeBytesRemaining -= pxBlock->xBlockSize;
264 /* The block is being returned - it is allocated and owned
265 * by the application and has no "next" block. */
266 heapALLOCATE_BLOCK( pxBlock );
267 pxBlock->pxNextFreeBlock = NULL;
272 traceMALLOC( pvReturn, xWantedSize );
274 ( void ) xTaskResumeAll();
276 #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
278 if( pvReturn == NULL )
280 vApplicationMallocFailedHook();
287 /*-----------------------------------------------------------*/
289 void vPortFree( void * pv )
291 uint8_t * puc = ( uint8_t * ) pv;
292 BlockLink_t * pxLink;
296 /* The memory being freed will have an BlockLink_t structure immediately
298 puc -= xHeapStructSize;
300 /* This unexpected casting is to keep some compilers from issuing
301 * byte alignment warnings. */
302 pxLink = ( void * ) puc;
304 configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
305 configASSERT( pxLink->pxNextFreeBlock == NULL );
307 if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
309 if( pxLink->pxNextFreeBlock == NULL )
311 /* The block is being returned to the heap - it is no longer
313 heapFREE_BLOCK( pxLink );
314 #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
316 ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
322 /* Add this block to the list of free blocks. */
323 prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
324 xFreeBytesRemaining += pxLink->xBlockSize;
325 traceFREE( pv, pxLink->xBlockSize );
327 ( void ) xTaskResumeAll();
332 /*-----------------------------------------------------------*/
334 size_t xPortGetFreeHeapSize( void )
336 return xFreeBytesRemaining;
338 /*-----------------------------------------------------------*/
340 void vPortInitialiseBlocks( void )
342 /* This just exists to keep the linker quiet. */
344 /*-----------------------------------------------------------*/
346 void * pvPortCalloc( size_t xNum,
351 if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
353 pv = pvPortMalloc( xNum * xSize );
357 ( void ) memset( pv, 0, xNum * xSize );
363 /*-----------------------------------------------------------*/
365 static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
367 BlockLink_t * pxFirstFreeBlock;
368 uint8_t * pucAlignedHeap;
370 /* Ensure the heap starts on a correctly aligned boundary. */
371 pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT - 1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
373 /* xStart is used to hold a pointer to the first item in the list of free
374 * blocks. The void cast is used to prevent compiler warnings. */
375 xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
376 xStart.xBlockSize = ( size_t ) 0;
378 /* xEnd is used to mark the end of the list of free blocks. */
379 xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;
380 xEnd.pxNextFreeBlock = NULL;
382 /* To start with there is a single free block that is sized to take up the
383 * entire heap space. */
384 pxFirstFreeBlock = ( BlockLink_t * ) pucAlignedHeap;
385 pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;
386 pxFirstFreeBlock->pxNextFreeBlock = &xEnd;
388 /*-----------------------------------------------------------*/
391 * Reset the state in this file. This state is normally initialized at start up.
392 * This function must be called by the application before restarting the
395 void vPortHeapResetState( void )
397 xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
399 xHeapHasBeenInitialised = pdFALSE;
401 /*-----------------------------------------------------------*/