heap_5.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * FreeRTOS Kernel V10.3.1
  3. * Copyright (C) 2020 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.
  14. *
  15. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
  17. * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
  18. * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
  19. * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  20. * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  21. *
  22. * http://www.FreeRTOS.org
  23. * http://aws.amazon.com/freertos
  24. *
  25. * 1 tab == 4 spaces!
  26. */
  27. /*
  28. * A sample implementation of pvPortMalloc() that allows the heap to be defined
  29. * across multiple non-contigous blocks and combines (coalescences) adjacent
  30. * memory blocks as they are freed.
  31. *
  32. * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative
  33. * implementations, and the memory management pages of http://www.FreeRTOS.org
  34. * for more information.
  35. *
  36. * Usage notes:
  37. *
  38. * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc().
  39. * pvPortMalloc() will be called if any task objects (tasks, queues, event
  40. * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be
  41. * called before any other objects are defined.
  42. *
  43. * vPortDefineHeapRegions() takes a single parameter. The parameter is an array
  44. * of HeapRegion_t structures. HeapRegion_t is defined in portable.h as
  45. *
  46. * typedef struct HeapRegion
  47. * {
  48. * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap.
  49. * size_t xSizeInBytes; << Size of the block of memory.
  50. * } HeapRegion_t;
  51. *
  52. * The array is terminated using a NULL zero sized region definition, and the
  53. * memory regions defined in the array ***must*** appear in address order from
  54. * low address to high address. So the following is a valid example of how
  55. * to use the function.
  56. *
  57. * HeapRegion_t xHeapRegions[] =
  58. * {
  59. * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000
  60. * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000
  61. * { NULL, 0 } << Terminates the array.
  62. * };
  63. *
  64. * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions().
  65. *
  66. * Note 0x80000000 is the lower address so appears in the array first.
  67. *
  68. */
  69. #include <stdlib.h>
  70. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  71. all the API functions to use the MPU wrappers. That should only be done when
  72. task.h is included from an application file. */
  73. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  74. #include "FreeRTOS.h"
  75. #include "task.h"
  76. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  77. #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  78. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  79. #endif
  80. /* Block sizes must not get too small. */
  81. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  82. /* Assumes 8bit bytes! */
  83. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  84. /* Define the linked list structure. This is used to link free blocks in order
  85. of their memory address. */
  86. typedef struct A_BLOCK_LINK
  87. {
  88. struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
  89. size_t xBlockSize; /*<< The size of the free block. */
  90. } BlockLink_t;
  91. /*-----------------------------------------------------------*/
  92. /*
  93. * Inserts a block of memory that is being freed into the correct position in
  94. * the list of free memory blocks. The block being freed will be merged with
  95. * the block in front it and/or the block behind it if the memory blocks are
  96. * adjacent to each other.
  97. */
  98. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );
  99. /*-----------------------------------------------------------*/
  100. /* The size of the structure placed at the beginning of each allocated memory
  101. block must by correctly byte aligned. */
  102. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  103. /* Create a couple of list links to mark the start and end of the list. */
  104. static BlockLink_t xStart, *pxEnd = NULL;
  105. /* Keeps track of the number of calls to allocate and free memory as well as the
  106. number of free bytes remaining, but says nothing about fragmentation. */
  107. static size_t xFreeBytesRemaining = 0U;
  108. static size_t xMinimumEverFreeBytesRemaining = 0U;
  109. static size_t xNumberOfSuccessfulAllocations = 0;
  110. static size_t xNumberOfSuccessfulFrees = 0;
  111. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  112. member of an BlockLink_t structure is set then the block belongs to the
  113. application. When the bit is free the block is still part of the free heap
  114. space. */
  115. static size_t xBlockAllocatedBit = 0;
  116. /*-----------------------------------------------------------*/
  117. void *pvPortMalloc( size_t xWantedSize )
  118. {
  119. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  120. void *pvReturn = NULL;
  121. /* The heap must be initialised before the first call to
  122. prvPortMalloc(). */
  123. configASSERT( pxEnd );
  124. vTaskSuspendAll();
  125. {
  126. /* Check the requested block size is not so large that the top bit is
  127. set. The top bit of the block size member of the BlockLink_t structure
  128. is used to determine who owns the block - the application or the
  129. kernel, so it must be free. */
  130. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  131. {
  132. /* The wanted size is increased so it can contain a BlockLink_t
  133. structure in addition to the requested amount of bytes. */
  134. if( xWantedSize > 0 )
  135. {
  136. xWantedSize += xHeapStructSize;
  137. /* Ensure that blocks are always aligned to the required number
  138. of bytes. */
  139. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  140. {
  141. /* Byte alignment required. */
  142. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  143. }
  144. else
  145. {
  146. mtCOVERAGE_TEST_MARKER();
  147. }
  148. }
  149. else
  150. {
  151. mtCOVERAGE_TEST_MARKER();
  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. else
  191. {
  192. mtCOVERAGE_TEST_MARKER();
  193. }
  194. xFreeBytesRemaining -= pxBlock->xBlockSize;
  195. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  196. {
  197. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  198. }
  199. else
  200. {
  201. mtCOVERAGE_TEST_MARKER();
  202. }
  203. /* The block is being returned - it is allocated and owned
  204. by the application and has no "next" block. */
  205. pxBlock->xBlockSize |= xBlockAllocatedBit;
  206. pxBlock->pxNextFreeBlock = NULL;
  207. xNumberOfSuccessfulAllocations++;
  208. }
  209. else
  210. {
  211. mtCOVERAGE_TEST_MARKER();
  212. }
  213. }
  214. else
  215. {
  216. mtCOVERAGE_TEST_MARKER();
  217. }
  218. }
  219. else
  220. {
  221. mtCOVERAGE_TEST_MARKER();
  222. }
  223. traceMALLOC( pvReturn, xWantedSize );
  224. }
  225. ( void ) xTaskResumeAll();
  226. #if( configUSE_MALLOC_FAILED_HOOK == 1 )
  227. {
  228. if( pvReturn == NULL )
  229. {
  230. extern void vApplicationMallocFailedHook( void );
  231. vApplicationMallocFailedHook();
  232. }
  233. else
  234. {
  235. mtCOVERAGE_TEST_MARKER();
  236. }
  237. }
  238. #endif
  239. return pvReturn;
  240. }
  241. /*-----------------------------------------------------------*/
  242. void vPortFree( void *pv )
  243. {
  244. uint8_t *puc = ( uint8_t * ) pv;
  245. BlockLink_t *pxLink;
  246. if( pv != NULL )
  247. {
  248. /* The memory being freed will have an BlockLink_t structure immediately
  249. before it. */
  250. puc -= xHeapStructSize;
  251. /* This casting is to keep the compiler from issuing warnings. */
  252. pxLink = ( void * ) puc;
  253. /* Check the block is actually allocated. */
  254. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  255. configASSERT( pxLink->pxNextFreeBlock == NULL );
  256. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  257. {
  258. if( pxLink->pxNextFreeBlock == NULL )
  259. {
  260. /* The block is being returned to the heap - it is no longer
  261. allocated. */
  262. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  263. vTaskSuspendAll();
  264. {
  265. /* Add this block to the list of free blocks. */
  266. xFreeBytesRemaining += pxLink->xBlockSize;
  267. traceFREE( pv, pxLink->xBlockSize );
  268. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  269. xNumberOfSuccessfulFrees++;
  270. }
  271. ( void ) xTaskResumeAll();
  272. }
  273. else
  274. {
  275. mtCOVERAGE_TEST_MARKER();
  276. }
  277. }
  278. else
  279. {
  280. mtCOVERAGE_TEST_MARKER();
  281. }
  282. }
  283. }
  284. /*-----------------------------------------------------------*/
  285. size_t xPortGetFreeHeapSize( void )
  286. {
  287. return xFreeBytesRemaining;
  288. }
  289. /*-----------------------------------------------------------*/
  290. size_t xPortGetMinimumEverFreeHeapSize( void )
  291. {
  292. return xMinimumEverFreeBytesRemaining;
  293. }
  294. /*-----------------------------------------------------------*/
  295. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )
  296. {
  297. BlockLink_t *pxIterator;
  298. uint8_t *puc;
  299. /* Iterate through the list until a block is found that has a higher address
  300. than the block being inserted. */
  301. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  302. {
  303. /* Nothing to do here, just iterate to the right position. */
  304. }
  305. /* Do the block being inserted, and the block it is being inserted after
  306. make a contiguous block of memory? */
  307. puc = ( uint8_t * ) pxIterator;
  308. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  309. {
  310. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  311. pxBlockToInsert = pxIterator;
  312. }
  313. else
  314. {
  315. mtCOVERAGE_TEST_MARKER();
  316. }
  317. /* Do the block being inserted, and the block it is being inserted before
  318. make a contiguous block of memory? */
  319. puc = ( uint8_t * ) pxBlockToInsert;
  320. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  321. {
  322. if( pxIterator->pxNextFreeBlock != pxEnd )
  323. {
  324. /* Form one big block from the two blocks. */
  325. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  326. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  327. }
  328. else
  329. {
  330. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  331. }
  332. }
  333. else
  334. {
  335. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  336. }
  337. /* If the block being inserted plugged a gab, so was merged with the block
  338. before and the block after, then it's pxNextFreeBlock pointer will have
  339. already been set, and should not be set here as that would make it point
  340. to itself. */
  341. if( pxIterator != pxBlockToInsert )
  342. {
  343. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  344. }
  345. else
  346. {
  347. mtCOVERAGE_TEST_MARKER();
  348. }
  349. }
  350. /*-----------------------------------------------------------*/
  351. void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
  352. {
  353. BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock;
  354. size_t xAlignedHeap;
  355. size_t xTotalRegionSize, xTotalHeapSize = 0;
  356. BaseType_t xDefinedRegions = 0;
  357. size_t xAddress;
  358. const HeapRegion_t *pxHeapRegion;
  359. /* Can only call once! */
  360. configASSERT( pxEnd == NULL );
  361. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  362. while( pxHeapRegion->xSizeInBytes > 0 )
  363. {
  364. xTotalRegionSize = pxHeapRegion->xSizeInBytes;
  365. /* Ensure the heap region starts on a correctly aligned boundary. */
  366. xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
  367. if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  368. {
  369. xAddress += ( portBYTE_ALIGNMENT - 1 );
  370. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  371. /* Adjust the size for the bytes lost to alignment. */
  372. xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
  373. }
  374. xAlignedHeap = xAddress;
  375. /* Set xStart if it has not already been set. */
  376. if( xDefinedRegions == 0 )
  377. {
  378. /* xStart is used to hold a pointer to the first item in the list of
  379. free blocks. The void cast is used to prevent compiler warnings. */
  380. xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
  381. xStart.xBlockSize = ( size_t ) 0;
  382. }
  383. else
  384. {
  385. /* Should only get here if one region has already been added to the
  386. heap. */
  387. configASSERT( pxEnd != NULL );
  388. /* Check blocks are passed in with increasing start addresses. */
  389. configASSERT( xAddress > ( size_t ) pxEnd );
  390. }
  391. /* Remember the location of the end marker in the previous region, if
  392. any. */
  393. pxPreviousFreeBlock = pxEnd;
  394. /* pxEnd is used to mark the end of the list of free blocks and is
  395. inserted at the end of the region space. */
  396. xAddress = xAlignedHeap + xTotalRegionSize;
  397. xAddress -= xHeapStructSize;
  398. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  399. pxEnd = ( BlockLink_t * ) xAddress;
  400. pxEnd->xBlockSize = 0;
  401. pxEnd->pxNextFreeBlock = NULL;
  402. /* To start with there is a single free block in this region that is
  403. sized to take up the entire heap region minus the space taken by the
  404. free block structure. */
  405. pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
  406. pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
  407. pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
  408. /* If this is not the first region that makes up the entire heap space
  409. then link the previous region to this region. */
  410. if( pxPreviousFreeBlock != NULL )
  411. {
  412. pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
  413. }
  414. xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
  415. /* Move onto the next HeapRegion_t structure. */
  416. xDefinedRegions++;
  417. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  418. }
  419. xMinimumEverFreeBytesRemaining = xTotalHeapSize;
  420. xFreeBytesRemaining = xTotalHeapSize;
  421. /* Check something was actually defined before it is accessed. */
  422. configASSERT( xTotalHeapSize );
  423. /* Work out the position of the top bit in a size_t variable. */
  424. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  425. }
  426. /*-----------------------------------------------------------*/
  427. void vPortGetHeapStats( HeapStats_t *pxHeapStats )
  428. {
  429. BlockLink_t *pxBlock;
  430. size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
  431. vTaskSuspendAll();
  432. {
  433. pxBlock = xStart.pxNextFreeBlock;
  434. /* pxBlock will be NULL if the heap has not been initialised. The heap
  435. is initialised automatically when the first allocation is made. */
  436. if( pxBlock != NULL )
  437. {
  438. do
  439. {
  440. /* Increment the number of blocks and record the largest block seen
  441. so far. */
  442. xBlocks++;
  443. if( pxBlock->xBlockSize > xMaxSize )
  444. {
  445. xMaxSize = pxBlock->xBlockSize;
  446. }
  447. /* Heap five will have a zero sized block at the end of each
  448. each region - the block is only used to link to the next
  449. heap region so it not a real block. */
  450. if( pxBlock->xBlockSize != 0 )
  451. {
  452. if( pxBlock->xBlockSize < xMinSize )
  453. {
  454. xMinSize = pxBlock->xBlockSize;
  455. }
  456. }
  457. /* Move to the next block in the chain until the last block is
  458. reached. */
  459. pxBlock = pxBlock->pxNextFreeBlock;
  460. } while( pxBlock != pxEnd );
  461. }
  462. }
  463. xTaskResumeAll();
  464. pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
  465. pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
  466. pxHeapStats->xNumberOfFreeBlocks = xBlocks;
  467. taskENTER_CRITICAL();
  468. {
  469. pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
  470. pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
  471. pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
  472. pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
  473. }
  474. taskEXIT_CRITICAL();
  475. }