heap_5.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. /*
  2. * FreeRTOS Kernel V10.0.0
  3. * Copyright (C) 2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
  4. *
  5. * Permission is hereby granted, free of charge, to any person obtaining a copy of
  6. * this software and associated documentation files (the "Software"), to deal in
  7. * the Software without restriction, including without limitation the rights to
  8. * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
  9. * the Software, and to permit persons to whom the Software is furnished to do so,
  10. * subject to the following conditions:
  11. *
  12. * The above copyright notice and this permission notice shall be included in all
  13. * copies or substantial portions of the Software. If you wish to use our Amazon
  14. * FreeRTOS name, please do so in a fair use way that does not cause confusion.
  15. *
  16. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  17. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  18. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  19. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  20. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  21. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  22. *
  23. * http://www.FreeRTOS.org
  24. * http://aws.amazon.com/freertos
  25. *
  26. * 1 tab == 4 spaces!
  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 http://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. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  72. all the API functions to use the MPU wrappers. That should only be done when
  73. task.h is included from an application file. */
  74. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  75. #include "FreeRTOS.h"
  76. #include "task.h"
  77. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  78. #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  79. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  80. #endif
  81. /* Block sizes must not get too small. */
  82. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  83. /* Assumes 8bit bytes! */
  84. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  85. /* Define the linked list structure. This is used to link free blocks in order
  86. of their memory address. */
  87. typedef struct A_BLOCK_LINK
  88. {
  89. struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
  90. size_t xBlockSize; /*<< The size of the free block. */
  91. } BlockLink_t;
  92. /*-----------------------------------------------------------*/
  93. /*
  94. * Inserts a block of memory that is being freed into the correct position in
  95. * the list of free memory blocks. The block being freed will be merged with
  96. * the block in front it and/or the block behind it if the memory blocks are
  97. * adjacent to each other.
  98. */
  99. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );
  100. /*-----------------------------------------------------------*/
  101. /* The size of the structure placed at the beginning of each allocated memory
  102. block must by correctly byte aligned. */
  103. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  104. /* Create a couple of list links to mark the start and end of the list. */
  105. static BlockLink_t xStart, *pxEnd = NULL;
  106. /* Keeps track of the number of free bytes remaining, but says nothing about
  107. fragmentation. */
  108. static size_t xFreeBytesRemaining = 0U;
  109. static size_t xMinimumEverFreeBytesRemaining = 0U;
  110. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  111. member of an BlockLink_t structure is set then the block belongs to the
  112. application. When the bit is free the block is still part of the free heap
  113. space. */
  114. static size_t xBlockAllocatedBit = 0;
  115. /*-----------------------------------------------------------*/
  116. void *pvPortMalloc( size_t xWantedSize )
  117. {
  118. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  119. void *pvReturn = NULL;
  120. /* The heap must be initialised before the first call to
  121. prvPortMalloc(). */
  122. configASSERT( pxEnd );
  123. vTaskSuspendAll();
  124. {
  125. /* Check the requested block size is not so large that the top bit is
  126. set. The top bit of the block size member of the BlockLink_t structure
  127. is used to determine who owns the block - the application or the
  128. kernel, so it must be free. */
  129. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  130. {
  131. /* The wanted size is increased so it can contain a BlockLink_t
  132. structure in addition to the requested amount of bytes. */
  133. if( xWantedSize > 0 )
  134. {
  135. xWantedSize += xHeapStructSize;
  136. /* Ensure that blocks are always aligned to the required number
  137. of bytes. */
  138. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  139. {
  140. /* Byte alignment required. */
  141. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  142. }
  143. else
  144. {
  145. mtCOVERAGE_TEST_MARKER();
  146. }
  147. }
  148. else
  149. {
  150. mtCOVERAGE_TEST_MARKER();
  151. }
  152. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  153. {
  154. /* Traverse the list from the start (lowest address) block until
  155. one of adequate size is found. */
  156. pxPreviousBlock = &xStart;
  157. pxBlock = xStart.pxNextFreeBlock;
  158. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  159. {
  160. pxPreviousBlock = pxBlock;
  161. pxBlock = pxBlock->pxNextFreeBlock;
  162. }
  163. /* If the end marker was reached then a block of adequate size
  164. was not found. */
  165. if( pxBlock != pxEnd )
  166. {
  167. /* Return the memory space pointed to - jumping over the
  168. BlockLink_t structure at its start. */
  169. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  170. /* This block is being returned for use so must be taken out
  171. of the list of free blocks. */
  172. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  173. /* If the block is larger than required it can be split into
  174. two. */
  175. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  176. {
  177. /* This block is to be split into two. Create a new
  178. block following the number of bytes requested. The void
  179. cast is used to prevent byte alignment warnings from the
  180. compiler. */
  181. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  182. /* Calculate the sizes of two blocks split from the
  183. single block. */
  184. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  185. pxBlock->xBlockSize = xWantedSize;
  186. /* Insert the new block into the list of free blocks. */
  187. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  188. }
  189. else
  190. {
  191. mtCOVERAGE_TEST_MARKER();
  192. }
  193. xFreeBytesRemaining -= pxBlock->xBlockSize;
  194. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  195. {
  196. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  197. }
  198. else
  199. {
  200. mtCOVERAGE_TEST_MARKER();
  201. }
  202. /* The block is being returned - it is allocated and owned
  203. by the application and has no "next" block. */
  204. pxBlock->xBlockSize |= xBlockAllocatedBit;
  205. pxBlock->pxNextFreeBlock = NULL;
  206. }
  207. else
  208. {
  209. mtCOVERAGE_TEST_MARKER();
  210. }
  211. }
  212. else
  213. {
  214. mtCOVERAGE_TEST_MARKER();
  215. }
  216. }
  217. else
  218. {
  219. mtCOVERAGE_TEST_MARKER();
  220. }
  221. traceMALLOC( pvReturn, xWantedSize );
  222. }
  223. ( void ) xTaskResumeAll();
  224. #if( configUSE_MALLOC_FAILED_HOOK == 1 )
  225. {
  226. if( pvReturn == NULL )
  227. {
  228. extern void vApplicationMallocFailedHook( void );
  229. vApplicationMallocFailedHook();
  230. }
  231. else
  232. {
  233. mtCOVERAGE_TEST_MARKER();
  234. }
  235. }
  236. #endif
  237. return pvReturn;
  238. }
  239. /*-----------------------------------------------------------*/
  240. void vPortFree( void *pv )
  241. {
  242. uint8_t *puc = ( uint8_t * ) pv;
  243. BlockLink_t *pxLink;
  244. if( pv != NULL )
  245. {
  246. /* The memory being freed will have an BlockLink_t structure immediately
  247. before it. */
  248. puc -= xHeapStructSize;
  249. /* This casting is to keep the compiler from issuing warnings. */
  250. pxLink = ( void * ) puc;
  251. /* Check the block is actually allocated. */
  252. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  253. configASSERT( pxLink->pxNextFreeBlock == NULL );
  254. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  255. {
  256. if( pxLink->pxNextFreeBlock == NULL )
  257. {
  258. /* The block is being returned to the heap - it is no longer
  259. allocated. */
  260. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  261. vTaskSuspendAll();
  262. {
  263. /* Add this block to the list of free blocks. */
  264. xFreeBytesRemaining += pxLink->xBlockSize;
  265. traceFREE( pv, pxLink->xBlockSize );
  266. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  267. }
  268. ( void ) xTaskResumeAll();
  269. }
  270. else
  271. {
  272. mtCOVERAGE_TEST_MARKER();
  273. }
  274. }
  275. else
  276. {
  277. mtCOVERAGE_TEST_MARKER();
  278. }
  279. }
  280. }
  281. /*-----------------------------------------------------------*/
  282. size_t xPortGetFreeHeapSize( void )
  283. {
  284. return xFreeBytesRemaining;
  285. }
  286. /*-----------------------------------------------------------*/
  287. size_t xPortGetMinimumEverFreeHeapSize( void )
  288. {
  289. return xMinimumEverFreeBytesRemaining;
  290. }
  291. /*-----------------------------------------------------------*/
  292. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )
  293. {
  294. BlockLink_t *pxIterator;
  295. uint8_t *puc;
  296. /* Iterate through the list until a block is found that has a higher address
  297. than the block being inserted. */
  298. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  299. {
  300. /* Nothing to do here, just iterate to the right position. */
  301. }
  302. /* Do the block being inserted, and the block it is being inserted after
  303. make a contiguous block of memory? */
  304. puc = ( uint8_t * ) pxIterator;
  305. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  306. {
  307. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  308. pxBlockToInsert = pxIterator;
  309. }
  310. else
  311. {
  312. mtCOVERAGE_TEST_MARKER();
  313. }
  314. /* Do the block being inserted, and the block it is being inserted before
  315. make a contiguous block of memory? */
  316. puc = ( uint8_t * ) pxBlockToInsert;
  317. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  318. {
  319. if( pxIterator->pxNextFreeBlock != pxEnd )
  320. {
  321. /* Form one big block from the two blocks. */
  322. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  323. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  324. }
  325. else
  326. {
  327. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  328. }
  329. }
  330. else
  331. {
  332. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  333. }
  334. /* If the block being inserted plugged a gab, so was merged with the block
  335. before and the block after, then it's pxNextFreeBlock pointer will have
  336. already been set, and should not be set here as that would make it point
  337. to itself. */
  338. if( pxIterator != pxBlockToInsert )
  339. {
  340. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  341. }
  342. else
  343. {
  344. mtCOVERAGE_TEST_MARKER();
  345. }
  346. }
  347. /*-----------------------------------------------------------*/
  348. void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
  349. {
  350. BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock;
  351. size_t xAlignedHeap;
  352. size_t xTotalRegionSize, xTotalHeapSize = 0;
  353. BaseType_t xDefinedRegions = 0;
  354. size_t xAddress;
  355. const HeapRegion_t *pxHeapRegion;
  356. /* Can only call once! */
  357. configASSERT( pxEnd == NULL );
  358. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  359. while( pxHeapRegion->xSizeInBytes > 0 )
  360. {
  361. xTotalRegionSize = pxHeapRegion->xSizeInBytes;
  362. /* Ensure the heap region starts on a correctly aligned boundary. */
  363. xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
  364. if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  365. {
  366. xAddress += ( portBYTE_ALIGNMENT - 1 );
  367. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  368. /* Adjust the size for the bytes lost to alignment. */
  369. xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
  370. }
  371. xAlignedHeap = xAddress;
  372. /* Set xStart if it has not already been set. */
  373. if( xDefinedRegions == 0 )
  374. {
  375. /* xStart is used to hold a pointer to the first item in the list of
  376. free blocks. The void cast is used to prevent compiler warnings. */
  377. xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
  378. xStart.xBlockSize = ( size_t ) 0;
  379. }
  380. else
  381. {
  382. /* Should only get here if one region has already been added to the
  383. heap. */
  384. configASSERT( pxEnd != NULL );
  385. /* Check blocks are passed in with increasing start addresses. */
  386. configASSERT( xAddress > ( size_t ) pxEnd );
  387. }
  388. /* Remember the location of the end marker in the previous region, if
  389. any. */
  390. pxPreviousFreeBlock = pxEnd;
  391. /* pxEnd is used to mark the end of the list of free blocks and is
  392. inserted at the end of the region space. */
  393. xAddress = xAlignedHeap + xTotalRegionSize;
  394. xAddress -= xHeapStructSize;
  395. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  396. pxEnd = ( BlockLink_t * ) xAddress;
  397. pxEnd->xBlockSize = 0;
  398. pxEnd->pxNextFreeBlock = NULL;
  399. /* To start with there is a single free block in this region that is
  400. sized to take up the entire heap region minus the space taken by the
  401. free block structure. */
  402. pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
  403. pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
  404. pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
  405. /* If this is not the first region that makes up the entire heap space
  406. then link the previous region to this region. */
  407. if( pxPreviousFreeBlock != NULL )
  408. {
  409. pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
  410. }
  411. xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
  412. /* Move onto the next HeapRegion_t structure. */
  413. xDefinedRegions++;
  414. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  415. }
  416. xMinimumEverFreeBytesRemaining = xTotalHeapSize;
  417. xFreeBytesRemaining = xTotalHeapSize;
  418. /* Check something was actually defined before it is accessed. */
  419. configASSERT( xTotalHeapSize );
  420. /* Work out the position of the top bit in a size_t variable. */
  421. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  422. }