heap_5.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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() that allows the heap to be defined
  30. * across multiple non-contigous blocks and combines (coalescences) adjacent
  31. * memory blocks as they are freed.
  32. *
  33. * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative
  34. * implementations, and the memory management pages of https://www.FreeRTOS.org
  35. * for more information.
  36. *
  37. * Usage notes:
  38. *
  39. * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc().
  40. * pvPortMalloc() will be called if any task objects (tasks, queues, event
  41. * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be
  42. * called before any other objects are defined.
  43. *
  44. * vPortDefineHeapRegions() takes a single parameter. The parameter is an array
  45. * of HeapRegion_t structures. HeapRegion_t is defined in portable.h as
  46. *
  47. * typedef struct HeapRegion
  48. * {
  49. * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap.
  50. * size_t xSizeInBytes; << Size of the block of memory.
  51. * } HeapRegion_t;
  52. *
  53. * The array is terminated using a NULL zero sized region definition, and the
  54. * memory regions defined in the array ***must*** appear in address order from
  55. * low address to high address. So the following is a valid example of how
  56. * to use the function.
  57. *
  58. * HeapRegion_t xHeapRegions[] =
  59. * {
  60. * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000
  61. * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000
  62. * { NULL, 0 } << Terminates the array.
  63. * };
  64. *
  65. * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions().
  66. *
  67. * Note 0x80000000 is the lower address so appears in the array first.
  68. *
  69. */
  70. #include <stdlib.h>
  71. #include "FreeRTOS.h"
  72. #include "task.h"
  73. #if ( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  74. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  75. #endif
  76. /* Block sizes must not get too small. */
  77. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  78. /* Assumes 8bit bytes! */
  79. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  80. /* Define the linked list structure. This is used to link free blocks in order
  81. * of their memory address. */
  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. /*-----------------------------------------------------------*/
  88. /*
  89. * Inserts a block of memory that is being freed into the correct position in
  90. * the list of free memory blocks. The block being freed will be merged with
  91. * the block in front it and/or the block behind it if the memory blocks are
  92. * adjacent to each other.
  93. */
  94. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert );
  95. /*-----------------------------------------------------------*/
  96. /* The size of the structure placed at the beginning of each allocated memory
  97. * block must by correctly byte aligned. */
  98. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  99. /* Create a couple of list links to mark the start and end of the list. */
  100. static BlockLink_t xStart, * pxEnd = NULL;
  101. /* Keeps track of the number of calls to allocate and free memory as well as the
  102. * number of free bytes remaining, but says nothing about fragmentation. */
  103. static size_t xFreeBytesRemaining = 0U;
  104. static size_t xMinimumEverFreeBytesRemaining = 0U;
  105. static size_t xNumberOfSuccessfulAllocations = 0;
  106. static size_t xNumberOfSuccessfulFrees = 0;
  107. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  108. * member of an BlockLink_t structure is set then the block belongs to the
  109. * application. When the bit is free the block is still part of the free heap
  110. * space. */
  111. static size_t xBlockAllocatedBit = 0;
  112. /*-----------------------------------------------------------*/
  113. void * pvPortMalloc( size_t xWantedSize )
  114. {
  115. BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink;
  116. void * pvReturn = NULL;
  117. /* The heap must be initialised before the first call to
  118. * prvPortMalloc(). */
  119. configASSERT( pxEnd );
  120. vTaskSuspendAll();
  121. {
  122. /* Check the requested block size is not so large that the top bit is
  123. * set. The top bit of the block size member of the BlockLink_t structure
  124. * is used to determine who owns the block - the application or the
  125. * kernel, so it must be free. */
  126. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  127. {
  128. /* The wanted size is increased so it can contain a BlockLink_t
  129. * structure in addition to the requested amount of bytes. */
  130. if( ( xWantedSize > 0 ) &&
  131. ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */
  132. {
  133. xWantedSize += xHeapStructSize;
  134. /* Ensure that blocks are always aligned */
  135. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  136. {
  137. /* Byte alignment required. Check for overflow */
  138. if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) >
  139. xWantedSize )
  140. {
  141. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  142. }
  143. else
  144. {
  145. xWantedSize = 0;
  146. }
  147. }
  148. }
  149. else
  150. {
  151. xWantedSize = 0;
  152. }
  153. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  154. {
  155. /* Traverse the list from the start (lowest address) block until
  156. * one of adequate size is found. */
  157. pxPreviousBlock = &xStart;
  158. pxBlock = xStart.pxNextFreeBlock;
  159. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  160. {
  161. pxPreviousBlock = pxBlock;
  162. pxBlock = pxBlock->pxNextFreeBlock;
  163. }
  164. /* If the end marker was reached then a block of adequate size
  165. * was not found. */
  166. if( pxBlock != pxEnd )
  167. {
  168. /* Return the memory space pointed to - jumping over the
  169. * BlockLink_t structure at its start. */
  170. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  171. /* This block is being returned for use so must be taken out
  172. * of the list of free blocks. */
  173. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  174. /* If the block is larger than required it can be split into
  175. * two. */
  176. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  177. {
  178. /* This block is to be split into two. Create a new
  179. * block following the number of bytes requested. The void
  180. * cast is used to prevent byte alignment warnings from the
  181. * compiler. */
  182. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  183. /* Calculate the sizes of two blocks split from the
  184. * single block. */
  185. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  186. pxBlock->xBlockSize = xWantedSize;
  187. /* Insert the new block into the list of free blocks. */
  188. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  189. }
  190. xFreeBytesRemaining -= pxBlock->xBlockSize;
  191. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  192. {
  193. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  194. }
  195. /* The block is being returned - it is allocated and owned
  196. * by the application and has no "next" block. */
  197. pxBlock->xBlockSize |= xBlockAllocatedBit;
  198. pxBlock->pxNextFreeBlock = NULL;
  199. xNumberOfSuccessfulAllocations++;
  200. }
  201. }
  202. }
  203. }
  204. ( void ) xTaskResumeAll();
  205. #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
  206. {
  207. if( pvReturn == NULL )
  208. {
  209. extern void vApplicationMallocFailedHook( void );
  210. vApplicationMallocFailedHook();
  211. }
  212. }
  213. #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
  214. return pvReturn;
  215. }
  216. /*-----------------------------------------------------------*/
  217. void vPortFree( void * pv )
  218. {
  219. uint8_t * puc = ( uint8_t * ) pv;
  220. BlockLink_t * pxLink;
  221. if( pv != NULL )
  222. {
  223. /* The memory being freed will have an BlockLink_t structure immediately
  224. * before it. */
  225. puc -= xHeapStructSize;
  226. /* This casting is to keep the compiler from issuing warnings. */
  227. pxLink = ( void * ) puc;
  228. /* Check the block is actually allocated. */
  229. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  230. configASSERT( pxLink->pxNextFreeBlock == NULL );
  231. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  232. {
  233. if( pxLink->pxNextFreeBlock == NULL )
  234. {
  235. /* The block is being returned to the heap - it is no longer
  236. * allocated. */
  237. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  238. vTaskSuspendAll();
  239. {
  240. /* Add this block to the list of free blocks. */
  241. xFreeBytesRemaining += pxLink->xBlockSize;
  242. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  243. xNumberOfSuccessfulFrees++;
  244. }
  245. ( void ) xTaskResumeAll();
  246. }
  247. }
  248. }
  249. }
  250. /*-----------------------------------------------------------*/
  251. size_t xPortGetFreeHeapSize( void )
  252. {
  253. return xFreeBytesRemaining;
  254. }
  255. /*-----------------------------------------------------------*/
  256. size_t xPortGetMinimumEverFreeHeapSize( void )
  257. {
  258. return xMinimumEverFreeBytesRemaining;
  259. }
  260. /*-----------------------------------------------------------*/
  261. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert )
  262. {
  263. BlockLink_t * pxIterator;
  264. uint8_t * puc;
  265. /* Iterate through the list until a block is found that has a higher address
  266. * than the block being inserted. */
  267. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  268. {
  269. /* Nothing to do here, just iterate to the right position. */
  270. }
  271. /* Do the block being inserted, and the block it is being inserted after
  272. * make a contiguous block of memory? */
  273. puc = ( uint8_t * ) pxIterator;
  274. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  275. {
  276. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  277. pxBlockToInsert = pxIterator;
  278. }
  279. /* Do the block being inserted, and the block it is being inserted before
  280. * make a contiguous block of memory? */
  281. puc = ( uint8_t * ) pxBlockToInsert;
  282. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  283. {
  284. if( pxIterator->pxNextFreeBlock != pxEnd )
  285. {
  286. /* Form one big block from the two blocks. */
  287. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  288. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  289. }
  290. else
  291. {
  292. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  293. }
  294. }
  295. else
  296. {
  297. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  298. }
  299. /* If the block being inserted plugged a gab, so was merged with the block
  300. * before and the block after, then it's pxNextFreeBlock pointer will have
  301. * already been set, and should not be set here as that would make it point
  302. * to itself. */
  303. if( pxIterator != pxBlockToInsert )
  304. {
  305. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  306. }
  307. }
  308. /*-----------------------------------------------------------*/
  309. void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
  310. {
  311. BlockLink_t * pxFirstFreeBlockInRegion = NULL, * pxPreviousFreeBlock;
  312. size_t xAlignedHeap;
  313. size_t xTotalRegionSize, xTotalHeapSize = 0;
  314. BaseType_t xDefinedRegions = 0;
  315. size_t xAddress;
  316. const HeapRegion_t * pxHeapRegion;
  317. /* Can only call once! */
  318. configASSERT( pxEnd == NULL );
  319. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  320. while( pxHeapRegion->xSizeInBytes > 0 )
  321. {
  322. xTotalRegionSize = pxHeapRegion->xSizeInBytes;
  323. /* Ensure the heap region starts on a correctly aligned boundary. */
  324. xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
  325. if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  326. {
  327. xAddress += ( portBYTE_ALIGNMENT - 1 );
  328. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  329. /* Adjust the size for the bytes lost to alignment. */
  330. xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
  331. }
  332. xAlignedHeap = xAddress;
  333. /* Set xStart if it has not already been set. */
  334. if( xDefinedRegions == 0 )
  335. {
  336. /* xStart is used to hold a pointer to the first item in the list of
  337. * free blocks. The void cast is used to prevent compiler warnings. */
  338. xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
  339. xStart.xBlockSize = ( size_t ) 0;
  340. }
  341. else
  342. {
  343. /* Should only get here if one region has already been added to the
  344. * heap. */
  345. configASSERT( pxEnd != NULL );
  346. /* Check blocks are passed in with increasing start addresses. */
  347. configASSERT( xAddress > ( size_t ) pxEnd );
  348. }
  349. /* Remember the location of the end marker in the previous region, if
  350. * any. */
  351. pxPreviousFreeBlock = pxEnd;
  352. /* pxEnd is used to mark the end of the list of free blocks and is
  353. * inserted at the end of the region space. */
  354. xAddress = xAlignedHeap + xTotalRegionSize;
  355. xAddress -= xHeapStructSize;
  356. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  357. pxEnd = ( BlockLink_t * ) xAddress;
  358. pxEnd->xBlockSize = 0;
  359. pxEnd->pxNextFreeBlock = NULL;
  360. /* To start with there is a single free block in this region that is
  361. * sized to take up the entire heap region minus the space taken by the
  362. * free block structure. */
  363. pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
  364. pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
  365. pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
  366. /* If this is not the first region that makes up the entire heap space
  367. * then link the previous region to this region. */
  368. if( pxPreviousFreeBlock != NULL )
  369. {
  370. pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
  371. }
  372. xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
  373. /* Move onto the next HeapRegion_t structure. */
  374. xDefinedRegions++;
  375. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  376. }
  377. xMinimumEverFreeBytesRemaining = xTotalHeapSize;
  378. xFreeBytesRemaining = xTotalHeapSize;
  379. /* Check something was actually defined before it is accessed. */
  380. configASSERT( xTotalHeapSize );
  381. /* Work out the position of the top bit in a size_t variable. */
  382. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  383. }
  384. /*-----------------------------------------------------------*/
  385. void vPortGetHeapStats( HeapStats_t * pxHeapStats )
  386. {
  387. BlockLink_t * pxBlock;
  388. size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
  389. vTaskSuspendAll();
  390. {
  391. pxBlock = xStart.pxNextFreeBlock;
  392. /* pxBlock will be NULL if the heap has not been initialised. The heap
  393. * is initialised automatically when the first allocation is made. */
  394. if( pxBlock != NULL )
  395. {
  396. do
  397. {
  398. /* Increment the number of blocks and record the largest block seen
  399. * so far. */
  400. xBlocks++;
  401. if( pxBlock->xBlockSize > xMaxSize )
  402. {
  403. xMaxSize = pxBlock->xBlockSize;
  404. }
  405. /* Heap five will have a zero sized block at the end of each
  406. * each region - the block is only used to link to the next
  407. * heap region so it not a real block. */
  408. if( pxBlock->xBlockSize != 0 )
  409. {
  410. if( pxBlock->xBlockSize < xMinSize )
  411. {
  412. xMinSize = pxBlock->xBlockSize;
  413. }
  414. }
  415. /* Move to the next block in the chain until the last block is
  416. * reached. */
  417. pxBlock = pxBlock->pxNextFreeBlock;
  418. } while( pxBlock != pxEnd );
  419. }
  420. }
  421. ( void ) xTaskResumeAll();
  422. pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
  423. pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
  424. pxHeapStats->xNumberOfFreeBlocks = xBlocks;
  425. taskENTER_CRITICAL();
  426. {
  427. pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
  428. pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
  429. pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
  430. pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
  431. }
  432. taskEXIT_CRITICAL();
  433. }