heap_4.c 18 KB

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