heap_2.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  1. /*
  2. * FreeRTOS Kernel <DEVELOPMENT BRANCH>
  3. * Copyright (C) 2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * SPDX-License-Identifier: MIT
  6. *
  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:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or substantial portions of the Software.
  16. *
  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.
  23. *
  24. * https://www.FreeRTOS.org
  25. * https://github.com/FreeRTOS
  26. *
  27. */
  28. /*
  29. * A sample implementation of pvPortMalloc() and vPortFree() that permits
  30. * allocated blocks to be freed, but does not combine adjacent free blocks
  31. * into a single larger block (and so will fragment memory). See heap_4.c for
  32. * an equivalent that does combine adjacent blocks into single larger blocks.
  33. *
  34. * See heap_1.c, heap_3.c and heap_4.c for alternative implementations, and the
  35. * memory management pages of https://www.FreeRTOS.org for more information.
  36. */
  37. #include <stdlib.h>
  38. #include <string.h>
  39. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  40. * all the API functions to use the MPU wrappers. That should only be done when
  41. * task.h is included from an application file. */
  42. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  43. #include "FreeRTOS.h"
  44. #include "task.h"
  45. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  46. #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  47. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  48. #endif
  49. #ifndef configHEAP_CLEAR_MEMORY_ON_FREE
  50. #define configHEAP_CLEAR_MEMORY_ON_FREE 0
  51. #endif
  52. /* A few bytes might be lost to byte aligning the heap start address. */
  53. #define configADJUSTED_HEAP_SIZE ( configTOTAL_HEAP_SIZE - portBYTE_ALIGNMENT )
  54. /* Assumes 8bit bytes! */
  55. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  56. /* Max value that fits in a size_t type. */
  57. #define heapSIZE_MAX ( ~( ( size_t ) 0 ) )
  58. /* Check if multiplying a and b will result in overflow. */
  59. #define heapMULTIPLY_WILL_OVERFLOW( a, b ) ( ( ( a ) > 0 ) && ( ( b ) > ( heapSIZE_MAX / ( a ) ) ) )
  60. /* Check if adding a and b will result in overflow. */
  61. #define heapADD_WILL_OVERFLOW( a, b ) ( ( a ) > ( heapSIZE_MAX - ( b ) ) )
  62. /* MSB of the xBlockSize member of an BlockLink_t structure is used to track
  63. * the allocation status of a block. When MSB of the xBlockSize member of
  64. * an BlockLink_t structure is set then the block belongs to the application.
  65. * When the bit is free the block is still part of the free heap space. */
  66. #define heapBLOCK_ALLOCATED_BITMASK ( ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 ) )
  67. #define heapBLOCK_SIZE_IS_VALID( xBlockSize ) ( ( ( xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) == 0 )
  68. #define heapBLOCK_IS_ALLOCATED( pxBlock ) ( ( ( pxBlock->xBlockSize ) & heapBLOCK_ALLOCATED_BITMASK ) != 0 )
  69. #define heapALLOCATE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) |= heapBLOCK_ALLOCATED_BITMASK )
  70. #define heapFREE_BLOCK( pxBlock ) ( ( pxBlock->xBlockSize ) &= ~heapBLOCK_ALLOCATED_BITMASK )
  71. /*-----------------------------------------------------------*/
  72. /* Allocate the memory for the heap. */
  73. #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
  74. /* The application writer has already defined the array used for the RTOS
  75. * heap - probably so it can be placed in a special segment or address. */
  76. extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  77. #else
  78. PRIVILEGED_DATA static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  79. #endif /* configAPPLICATION_ALLOCATED_HEAP */
  80. /* Define the linked list structure. This is used to link free blocks in order
  81. * of their size. */
  82. typedef struct A_BLOCK_LINK
  83. {
  84. struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */
  85. size_t xBlockSize; /*<< The size of the free block. */
  86. } BlockLink_t;
  87. static const size_t xHeapStructSize = ( ( sizeof( BlockLink_t ) + ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK ) );
  88. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize * 2 ) )
  89. /* Create a couple of list links to mark the start and end of the list. */
  90. PRIVILEGED_DATA static BlockLink_t xStart, xEnd;
  91. /* Keeps track of the number of free bytes remaining, but says nothing about
  92. * fragmentation. */
  93. PRIVILEGED_DATA static size_t xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
  94. /* Indicates whether the heap has been initialised or not. */
  95. PRIVILEGED_DATA static BaseType_t xHeapHasBeenInitialised = pdFALSE;
  96. /*-----------------------------------------------------------*/
  97. /*
  98. * Initialises the heap structures before their first use.
  99. */
  100. static void prvHeapInit( void ) PRIVILEGED_FUNCTION;
  101. /*-----------------------------------------------------------*/
  102. /* STATIC FUNCTIONS ARE DEFINED AS MACROS TO MINIMIZE THE FUNCTION CALL DEPTH. */
  103. /*
  104. * Insert a block into the list of free blocks - which is ordered by size of
  105. * the block. Small blocks at the start of the list and large blocks at the end
  106. * of the list.
  107. */
  108. #define prvInsertBlockIntoFreeList( pxBlockToInsert ) \
  109. { \
  110. BlockLink_t * pxIterator; \
  111. size_t xBlockSize; \
  112. \
  113. xBlockSize = pxBlockToInsert->xBlockSize; \
  114. \
  115. /* Iterate through the list until a block is found that has a larger size */ \
  116. /* than the block we are inserting. */ \
  117. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock->xBlockSize < xBlockSize; pxIterator = pxIterator->pxNextFreeBlock ) \
  118. { \
  119. /* There is nothing to do here - just iterate to the correct position. */ \
  120. } \
  121. \
  122. /* Update the list to include the block being inserted in the correct */ \
  123. /* position. */ \
  124. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock; \
  125. pxIterator->pxNextFreeBlock = pxBlockToInsert; \
  126. }
  127. /*-----------------------------------------------------------*/
  128. void * pvPortMalloc( size_t xWantedSize )
  129. {
  130. BlockLink_t * pxBlock;
  131. BlockLink_t * pxPreviousBlock;
  132. BlockLink_t * pxNewBlockLink;
  133. void * pvReturn = NULL;
  134. size_t xAdditionalRequiredSize;
  135. size_t xAllocatedBlockSize = 0;
  136. if( xWantedSize > 0 )
  137. {
  138. /* The wanted size must be increased so it can contain a BlockLink_t
  139. * structure in addition to the requested amount of bytes. */
  140. if( heapADD_WILL_OVERFLOW( xWantedSize, xHeapStructSize ) == 0 )
  141. {
  142. xWantedSize += xHeapStructSize;
  143. /* Ensure that blocks are always aligned to the required number
  144. * of bytes. */
  145. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  146. {
  147. /* Byte alignment required. */
  148. xAdditionalRequiredSize = portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK );
  149. if( heapADD_WILL_OVERFLOW( xWantedSize, xAdditionalRequiredSize ) == 0 )
  150. {
  151. xWantedSize += xAdditionalRequiredSize;
  152. }
  153. else
  154. {
  155. xWantedSize = 0;
  156. }
  157. }
  158. else
  159. {
  160. mtCOVERAGE_TEST_MARKER();
  161. }
  162. }
  163. else
  164. {
  165. xWantedSize = 0;
  166. }
  167. }
  168. else
  169. {
  170. mtCOVERAGE_TEST_MARKER();
  171. }
  172. vTaskSuspendAll();
  173. {
  174. /* If this is the first call to malloc then the heap will require
  175. * initialisation to setup the list of free blocks. */
  176. if( xHeapHasBeenInitialised == pdFALSE )
  177. {
  178. prvHeapInit();
  179. xHeapHasBeenInitialised = pdTRUE;
  180. }
  181. /* Check the block size we are trying to allocate is not so large that the
  182. * top bit is set. The top bit of the block size member of the BlockLink_t
  183. * structure is used to determine who owns the block - the application or
  184. * the kernel, so it must be free. */
  185. if( heapBLOCK_SIZE_IS_VALID( xWantedSize ) != 0 )
  186. {
  187. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  188. {
  189. /* Blocks are stored in byte order - traverse the list from the start
  190. * (smallest) block until one of adequate size is found. */
  191. pxPreviousBlock = &xStart;
  192. pxBlock = xStart.pxNextFreeBlock;
  193. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  194. {
  195. pxPreviousBlock = pxBlock;
  196. pxBlock = pxBlock->pxNextFreeBlock;
  197. }
  198. /* If we found the end marker then a block of adequate size was not found. */
  199. if( pxBlock != &xEnd )
  200. {
  201. /* Return the memory space - jumping over the BlockLink_t structure
  202. * at its start. */
  203. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  204. /* This block is being returned for use so must be taken out of the
  205. * list of free blocks. */
  206. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  207. /* If the block is larger than required it can be split into two. */
  208. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  209. {
  210. /* This block is to be split into two. Create a new block
  211. * following the number of bytes requested. The void cast is
  212. * used to prevent byte alignment warnings from the compiler. */
  213. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  214. /* Calculate the sizes of two blocks split from the single
  215. * block. */
  216. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  217. pxBlock->xBlockSize = xWantedSize;
  218. /* Insert the new block into the list of free blocks.
  219. * The list of free blocks is sorted by their size, we have to
  220. * iterate to find the right place to insert new block. */
  221. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  222. }
  223. xFreeBytesRemaining -= pxBlock->xBlockSize;
  224. xAllocatedBlockSize = pxBlock->xBlockSize;
  225. /* The block is being returned - it is allocated and owned
  226. * by the application and has no "next" block. */
  227. heapALLOCATE_BLOCK( pxBlock );
  228. pxBlock->pxNextFreeBlock = NULL;
  229. }
  230. }
  231. }
  232. traceMALLOC( pvReturn, xAllocatedBlockSize );
  233. /* Prevent compiler warnings when trace macros are not used. */
  234. ( void ) xAllocatedBlockSize;
  235. }
  236. ( void ) xTaskResumeAll();
  237. #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
  238. {
  239. if( pvReturn == NULL )
  240. {
  241. vApplicationMallocFailedHook();
  242. }
  243. }
  244. #endif
  245. return pvReturn;
  246. }
  247. /*-----------------------------------------------------------*/
  248. void vPortFree( void * pv )
  249. {
  250. uint8_t * puc = ( uint8_t * ) pv;
  251. BlockLink_t * pxLink;
  252. if( pv != NULL )
  253. {
  254. /* The memory being freed will have an BlockLink_t structure immediately
  255. * before it. */
  256. puc -= xHeapStructSize;
  257. /* This unexpected casting is to keep some compilers from issuing
  258. * byte alignment warnings. */
  259. pxLink = ( void * ) puc;
  260. configASSERT( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 );
  261. configASSERT( pxLink->pxNextFreeBlock == NULL );
  262. if( heapBLOCK_IS_ALLOCATED( pxLink ) != 0 )
  263. {
  264. if( pxLink->pxNextFreeBlock == NULL )
  265. {
  266. /* The block is being returned to the heap - it is no longer
  267. * allocated. */
  268. heapFREE_BLOCK( pxLink );
  269. #if ( configHEAP_CLEAR_MEMORY_ON_FREE == 1 )
  270. {
  271. ( void ) memset( puc + xHeapStructSize, 0, pxLink->xBlockSize - xHeapStructSize );
  272. }
  273. #endif
  274. vTaskSuspendAll();
  275. {
  276. /* Add this block to the list of free blocks. */
  277. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  278. xFreeBytesRemaining += pxLink->xBlockSize;
  279. traceFREE( pv, pxLink->xBlockSize );
  280. }
  281. ( void ) xTaskResumeAll();
  282. }
  283. }
  284. }
  285. }
  286. /*-----------------------------------------------------------*/
  287. size_t xPortGetFreeHeapSize( void )
  288. {
  289. return xFreeBytesRemaining;
  290. }
  291. /*-----------------------------------------------------------*/
  292. void vPortInitialiseBlocks( void )
  293. {
  294. /* This just exists to keep the linker quiet. */
  295. }
  296. /*-----------------------------------------------------------*/
  297. void * pvPortCalloc( size_t xNum,
  298. size_t xSize )
  299. {
  300. void * pv = NULL;
  301. if( heapMULTIPLY_WILL_OVERFLOW( xNum, xSize ) == 0 )
  302. {
  303. pv = pvPortMalloc( xNum * xSize );
  304. if( pv != NULL )
  305. {
  306. ( void ) memset( pv, 0, xNum * xSize );
  307. }
  308. }
  309. return pv;
  310. }
  311. /*-----------------------------------------------------------*/
  312. static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
  313. {
  314. BlockLink_t * pxFirstFreeBlock;
  315. uint8_t * pucAlignedHeap;
  316. /* Ensure the heap starts on a correctly aligned boundary. */
  317. pucAlignedHeap = ( uint8_t * ) ( ( ( portPOINTER_SIZE_TYPE ) & ucHeap[ portBYTE_ALIGNMENT - 1 ] ) & ( ~( ( portPOINTER_SIZE_TYPE ) portBYTE_ALIGNMENT_MASK ) ) );
  318. /* xStart is used to hold a pointer to the first item in the list of free
  319. * blocks. The void cast is used to prevent compiler warnings. */
  320. xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
  321. xStart.xBlockSize = ( size_t ) 0;
  322. /* xEnd is used to mark the end of the list of free blocks. */
  323. xEnd.xBlockSize = configADJUSTED_HEAP_SIZE;
  324. xEnd.pxNextFreeBlock = NULL;
  325. /* To start with there is a single free block that is sized to take up the
  326. * entire heap space. */
  327. pxFirstFreeBlock = ( BlockLink_t * ) pucAlignedHeap;
  328. pxFirstFreeBlock->xBlockSize = configADJUSTED_HEAP_SIZE;
  329. pxFirstFreeBlock->pxNextFreeBlock = &xEnd;
  330. }
  331. /*-----------------------------------------------------------*/
  332. /*
  333. * Reset the state in this file. This state is normally initialized at start up.
  334. * This function must be called by the application before restarting the
  335. * scheduler.
  336. */
  337. void vPortHeapResetState( void )
  338. {
  339. xFreeBytesRemaining = configADJUSTED_HEAP_SIZE;
  340. xHeapHasBeenInitialised = pdFALSE;
  341. }
  342. /*-----------------------------------------------------------*/