heap_4.c 18 KB

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