heap_4.c 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. * FreeRTOS Kernel V10.4.6
  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 combines
  30. * (coalescences) adjacent memory blocks as they are freed, and in so doing
  31. * limits memory fragmentation.
  32. *
  33. * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the
  34. * memory management pages of https://www.FreeRTOS.org for more information.
  35. */
  36. #include <stdlib.h>
  37. #include "FreeRTOS.h"
  38. #include "task.h"
  39. #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  40. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  41. #endif
  42. /* Block sizes must not get too small. */
  43. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  44. /* Assumes 8bit bytes! */
  45. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  46. /* Allocate the memory for the heap. */
  47. #if ( configAPPLICATION_ALLOCATED_HEAP == 1 )
  48. /* The application writer has already defined the array used for the RTOS
  49. * heap - probably so it can be placed in a special segment or address. */
  50. extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  51. #else
  52. static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  53. #endif /* configAPPLICATION_ALLOCATED_HEAP */
  54. /* Define the linked list structure. This is used to link free blocks in order
  55. * of their memory address. */
  56. typedef struct A_BLOCK_LINK
  57. {
  58. struct A_BLOCK_LINK * pxNextFreeBlock; /*<< The next free block in the list. */
  59. size_t xBlockSize; /*<< The size of the free block. */
  60. } BlockLink_t;
  61. /*-----------------------------------------------------------*/
  62. /*
  63. * Inserts a block of memory that is being freed into the correct position in
  64. * the list of free memory blocks. The block being freed will be merged with
  65. * the block in front it and/or the block behind it if the memory blocks are
  66. * adjacent to each other.
  67. */
  68. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert );
  69. /*
  70. * Called automatically to setup the required heap structures the first time
  71. * pvPortMalloc() is called.
  72. */
  73. static void prvHeapInit( void );
  74. /*-----------------------------------------------------------*/
  75. /* The size of the structure placed at the beginning of each allocated memory
  76. * block must by correctly byte aligned. */
  77. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  78. /* Create a couple of list links to mark the start and end of the list. */
  79. static BlockLink_t xStart, * pxEnd = NULL;
  80. /* Keeps track of the number of calls to allocate and free memory as well as the
  81. * number of free bytes remaining, but says nothing about fragmentation. */
  82. static size_t xFreeBytesRemaining = 0U;
  83. static size_t xMinimumEverFreeBytesRemaining = 0U;
  84. static size_t xNumberOfSuccessfulAllocations = 0;
  85. static size_t xNumberOfSuccessfulFrees = 0;
  86. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  87. * member of an BlockLink_t structure is set then the block belongs to the
  88. * application. When the bit is free the block is still part of the free heap
  89. * space. */
  90. static size_t xBlockAllocatedBit = 0;
  91. /*-----------------------------------------------------------*/
  92. void * pvPortMalloc( size_t xWantedSize )
  93. {
  94. BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink;
  95. void * pvReturn = NULL;
  96. vTaskSuspendAll();
  97. {
  98. /* If this is the first call to malloc then the heap will require
  99. * initialisation to setup the list of free blocks. */
  100. if( pxEnd == NULL )
  101. {
  102. prvHeapInit();
  103. }
  104. /* Check the requested block size is not so large that the top bit is
  105. * set. The top bit of the block size member of the BlockLink_t structure
  106. * is used to determine who owns the block - the application or the
  107. * kernel, so it must be free. */
  108. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  109. {
  110. /* The wanted size must be increased so it can contain a BlockLink_t
  111. * structure in addition to the requested amount of bytes. */
  112. if( ( xWantedSize > 0 ) &&
  113. ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */
  114. {
  115. xWantedSize += xHeapStructSize;
  116. /* Ensure that blocks are always aligned. */
  117. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  118. {
  119. /* Byte alignment required. Check for overflow. */
  120. if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) )
  121. > xWantedSize )
  122. {
  123. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  124. configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );
  125. }
  126. else
  127. {
  128. xWantedSize = 0;
  129. }
  130. }
  131. }
  132. else
  133. {
  134. xWantedSize = 0;
  135. }
  136. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  137. {
  138. /* Traverse the list from the start (lowest address) block until
  139. * one of adequate size is found. */
  140. pxPreviousBlock = &xStart;
  141. pxBlock = xStart.pxNextFreeBlock;
  142. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  143. {
  144. pxPreviousBlock = pxBlock;
  145. pxBlock = pxBlock->pxNextFreeBlock;
  146. }
  147. /* If the end marker was reached then a block of adequate size
  148. * was not found. */
  149. if( pxBlock != pxEnd )
  150. {
  151. /* Return the memory space pointed to - jumping over the
  152. * BlockLink_t structure at its start. */
  153. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  154. /* This block is being returned for use so must be taken out
  155. * of the list of free blocks. */
  156. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  157. /* If the block is larger than required it can be split into
  158. * two. */
  159. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  160. {
  161. /* This block is to be split into two. Create a new
  162. * block following the number of bytes requested. The void
  163. * cast is used to prevent byte alignment warnings from the
  164. * compiler. */
  165. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  166. configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
  167. /* Calculate the sizes of two blocks split from the
  168. * single block. */
  169. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  170. pxBlock->xBlockSize = xWantedSize;
  171. /* Insert the new block into the list of free blocks. */
  172. prvInsertBlockIntoFreeList( pxNewBlockLink );
  173. }
  174. xFreeBytesRemaining -= pxBlock->xBlockSize;
  175. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  176. {
  177. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  178. }
  179. /* The block is being returned - it is allocated and owned
  180. * by the application and has no "next" block. */
  181. pxBlock->xBlockSize |= xBlockAllocatedBit;
  182. pxBlock->pxNextFreeBlock = NULL;
  183. xNumberOfSuccessfulAllocations++;
  184. }
  185. }
  186. }
  187. }
  188. ( void ) xTaskResumeAll();
  189. #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
  190. {
  191. if( pvReturn == NULL )
  192. {
  193. extern void vApplicationMallocFailedHook( void );
  194. vApplicationMallocFailedHook();
  195. }
  196. }
  197. #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
  198. configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
  199. return pvReturn;
  200. }
  201. /*-----------------------------------------------------------*/
  202. void vPortFree( void * pv )
  203. {
  204. uint8_t * puc = ( uint8_t * ) pv;
  205. BlockLink_t * pxLink;
  206. if( pv != NULL )
  207. {
  208. /* The memory being freed will have an BlockLink_t structure immediately
  209. * before it. */
  210. puc -= xHeapStructSize;
  211. /* This casting is to keep the compiler from issuing warnings. */
  212. pxLink = ( void * ) puc;
  213. /* Check the block is actually allocated. */
  214. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  215. configASSERT( pxLink->pxNextFreeBlock == NULL );
  216. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  217. {
  218. if( pxLink->pxNextFreeBlock == NULL )
  219. {
  220. /* The block is being returned to the heap - it is no longer
  221. * allocated. */
  222. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  223. vTaskSuspendAll();
  224. {
  225. /* Add this block to the list of free blocks. */
  226. xFreeBytesRemaining += pxLink->xBlockSize;
  227. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  228. xNumberOfSuccessfulFrees++;
  229. }
  230. ( void ) xTaskResumeAll();
  231. }
  232. }
  233. }
  234. }
  235. /*-----------------------------------------------------------*/
  236. size_t xPortGetFreeHeapSize( void )
  237. {
  238. return xFreeBytesRemaining;
  239. }
  240. /*-----------------------------------------------------------*/
  241. size_t xPortGetMinimumEverFreeHeapSize( void )
  242. {
  243. return xMinimumEverFreeBytesRemaining;
  244. }
  245. /*-----------------------------------------------------------*/
  246. void vPortInitialiseBlocks( void )
  247. {
  248. /* This just exists to keep the linker quiet. */
  249. }
  250. /*-----------------------------------------------------------*/
  251. static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
  252. {
  253. BlockLink_t * pxFirstFreeBlock;
  254. uint8_t * pucAlignedHeap;
  255. size_t uxAddress;
  256. size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
  257. /* Ensure the heap starts on a correctly aligned boundary. */
  258. uxAddress = ( size_t ) ucHeap;
  259. if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  260. {
  261. uxAddress += ( portBYTE_ALIGNMENT - 1 );
  262. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  263. xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;
  264. }
  265. pucAlignedHeap = ( uint8_t * ) uxAddress;
  266. /* xStart is used to hold a pointer to the first item in the list of free
  267. * blocks. The void cast is used to prevent compiler warnings. */
  268. xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
  269. xStart.xBlockSize = ( size_t ) 0;
  270. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  271. * at the end of the heap space. */
  272. uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;
  273. uxAddress -= xHeapStructSize;
  274. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  275. pxEnd = ( void * ) uxAddress;
  276. pxEnd->xBlockSize = 0;
  277. pxEnd->pxNextFreeBlock = NULL;
  278. /* To start with there is a single free block that is sized to take up the
  279. * entire heap space, minus the space taken by pxEnd. */
  280. pxFirstFreeBlock = ( void * ) pucAlignedHeap;
  281. pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;
  282. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  283. /* Only one block exists - and it covers the entire usable heap space. */
  284. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  285. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  286. /* Work out the position of the top bit in a size_t variable. */
  287. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  288. }
  289. /*-----------------------------------------------------------*/
  290. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
  291. {
  292. BlockLink_t * pxIterator;
  293. uint8_t * puc;
  294. /* Iterate through the list until a block is found that has a higher address
  295. * than the block being inserted. */
  296. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  297. {
  298. /* Nothing to do here, just iterate to the right position. */
  299. }
  300. /* Do the block being inserted, and the block it is being inserted after
  301. * make a contiguous block of memory? */
  302. puc = ( uint8_t * ) pxIterator;
  303. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  304. {
  305. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  306. pxBlockToInsert = pxIterator;
  307. }
  308. /* Do the block being inserted, and the block it is being inserted before
  309. * make a contiguous block of memory? */
  310. puc = ( uint8_t * ) pxBlockToInsert;
  311. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  312. {
  313. if( pxIterator->pxNextFreeBlock != pxEnd )
  314. {
  315. /* Form one big block from the two blocks. */
  316. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  317. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  318. }
  319. else
  320. {
  321. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  322. }
  323. }
  324. else
  325. {
  326. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  327. }
  328. /* If the block being inserted plugged a gab, so was merged with the block
  329. * before and the block after, then it's pxNextFreeBlock pointer will have
  330. * already been set, and should not be set here as that would make it point
  331. * to itself. */
  332. if( pxIterator != pxBlockToInsert )
  333. {
  334. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  335. }
  336. }
  337. /*-----------------------------------------------------------*/
  338. void vPortGetHeapStats( HeapStats_t * pxHeapStats )
  339. {
  340. BlockLink_t * pxBlock;
  341. size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
  342. vTaskSuspendAll();
  343. {
  344. pxBlock = xStart.pxNextFreeBlock;
  345. /* pxBlock will be NULL if the heap has not been initialised. The heap
  346. * is initialised automatically when the first allocation is made. */
  347. if( pxBlock != NULL )
  348. {
  349. do
  350. {
  351. /* Increment the number of blocks and record the largest block seen
  352. * so far. */
  353. xBlocks++;
  354. if( pxBlock->xBlockSize > xMaxSize )
  355. {
  356. xMaxSize = pxBlock->xBlockSize;
  357. }
  358. if( pxBlock->xBlockSize < xMinSize )
  359. {
  360. xMinSize = pxBlock->xBlockSize;
  361. }
  362. /* Move to the next block in the chain until the last block is
  363. * reached. */
  364. pxBlock = pxBlock->pxNextFreeBlock;
  365. } while( pxBlock != pxEnd );
  366. }
  367. }
  368. ( void ) xTaskResumeAll();
  369. pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
  370. pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
  371. pxHeapStats->xNumberOfFreeBlocks = xBlocks;
  372. taskENTER_CRITICAL();
  373. {
  374. pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
  375. pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
  376. pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
  377. pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
  378. }
  379. taskEXIT_CRITICAL();
  380. }