heap_5.c 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  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. /* 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 calls to allocate and free memory as well as the
  107. * number of free bytes remaining, but says nothing about fragmentation. */
  108. static size_t xFreeBytesRemaining = 0U;
  109. static size_t xMinimumEverFreeBytesRemaining = 0U;
  110. static size_t xNumberOfSuccessfulAllocations = 0;
  111. static size_t xNumberOfSuccessfulFrees = 0;
  112. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  113. * member of an BlockLink_t structure is set then the block belongs to the
  114. * application. When the bit is free the block is still part of the free heap
  115. * space. */
  116. static size_t xBlockAllocatedBit = 0;
  117. /*-----------------------------------------------------------*/
  118. void * pvPortMalloc( size_t xWantedSize )
  119. {
  120. BlockLink_t * pxBlock, * pxPreviousBlock, * pxNewBlockLink;
  121. void * pvReturn = NULL;
  122. /* The heap must be initialised before the first call to
  123. * prvPortMalloc(). */
  124. configASSERT( pxEnd );
  125. vTaskSuspendAll();
  126. {
  127. /* Check the requested block size is not so large that the top bit is
  128. * set. The top bit of the block size member of the BlockLink_t structure
  129. * is used to determine who owns the block - the application or the
  130. * kernel, so it must be free. */
  131. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  132. {
  133. /* The wanted size is increased so it can contain a BlockLink_t
  134. * structure in addition to the requested amount of bytes. */
  135. if( ( xWantedSize > 0 ) &&
  136. ( ( xWantedSize + xHeapStructSize ) > xWantedSize ) ) /* Overflow check */
  137. {
  138. xWantedSize += xHeapStructSize;
  139. /* Ensure that blocks are always aligned */
  140. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  141. {
  142. /* Byte alignment required. Check for overflow */
  143. if( ( xWantedSize + ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) ) ) >
  144. xWantedSize )
  145. {
  146. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  147. }
  148. else
  149. {
  150. xWantedSize = 0;
  151. }
  152. }
  153. else
  154. {
  155. mtCOVERAGE_TEST_MARKER();
  156. }
  157. }
  158. else
  159. {
  160. xWantedSize = 0;
  161. }
  162. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  163. {
  164. /* Traverse the list from the start (lowest address) block until
  165. * one of adequate size is found. */
  166. pxPreviousBlock = &xStart;
  167. pxBlock = xStart.pxNextFreeBlock;
  168. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  169. {
  170. pxPreviousBlock = pxBlock;
  171. pxBlock = pxBlock->pxNextFreeBlock;
  172. }
  173. /* If the end marker was reached then a block of adequate size
  174. * was not found. */
  175. if( pxBlock != pxEnd )
  176. {
  177. /* Return the memory space pointed to - jumping over the
  178. * BlockLink_t structure at its start. */
  179. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  180. /* This block is being returned for use so must be taken out
  181. * of the list of free blocks. */
  182. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  183. /* If the block is larger than required it can be split into
  184. * two. */
  185. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  186. {
  187. /* This block is to be split into two. Create a new
  188. * block following the number of bytes requested. The void
  189. * cast is used to prevent byte alignment warnings from the
  190. * compiler. */
  191. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  192. /* Calculate the sizes of two blocks split from the
  193. * single block. */
  194. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  195. pxBlock->xBlockSize = xWantedSize;
  196. /* Insert the new block into the list of free blocks. */
  197. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  198. }
  199. else
  200. {
  201. mtCOVERAGE_TEST_MARKER();
  202. }
  203. xFreeBytesRemaining -= pxBlock->xBlockSize;
  204. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  205. {
  206. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  207. }
  208. else
  209. {
  210. mtCOVERAGE_TEST_MARKER();
  211. }
  212. /* The block is being returned - it is allocated and owned
  213. * by the application and has no "next" block. */
  214. pxBlock->xBlockSize |= xBlockAllocatedBit;
  215. pxBlock->pxNextFreeBlock = NULL;
  216. xNumberOfSuccessfulAllocations++;
  217. }
  218. else
  219. {
  220. mtCOVERAGE_TEST_MARKER();
  221. }
  222. }
  223. else
  224. {
  225. mtCOVERAGE_TEST_MARKER();
  226. }
  227. }
  228. else
  229. {
  230. mtCOVERAGE_TEST_MARKER();
  231. }
  232. traceMALLOC( pvReturn, xWantedSize );
  233. }
  234. ( void ) xTaskResumeAll();
  235. #if ( configUSE_MALLOC_FAILED_HOOK == 1 )
  236. {
  237. if( pvReturn == NULL )
  238. {
  239. extern void vApplicationMallocFailedHook( void );
  240. vApplicationMallocFailedHook();
  241. }
  242. else
  243. {
  244. mtCOVERAGE_TEST_MARKER();
  245. }
  246. }
  247. #endif /* if ( configUSE_MALLOC_FAILED_HOOK == 1 ) */
  248. return pvReturn;
  249. }
  250. /*-----------------------------------------------------------*/
  251. void vPortFree( void * pv )
  252. {
  253. uint8_t * puc = ( uint8_t * ) pv;
  254. BlockLink_t * pxLink;
  255. if( pv != NULL )
  256. {
  257. /* The memory being freed will have an BlockLink_t structure immediately
  258. * before it. */
  259. puc -= xHeapStructSize;
  260. /* This casting is to keep the compiler from issuing warnings. */
  261. pxLink = ( void * ) puc;
  262. /* Check the block is actually allocated. */
  263. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  264. configASSERT( pxLink->pxNextFreeBlock == NULL );
  265. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  266. {
  267. if( pxLink->pxNextFreeBlock == NULL )
  268. {
  269. /* The block is being returned to the heap - it is no longer
  270. * allocated. */
  271. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  272. vTaskSuspendAll();
  273. {
  274. /* Add this block to the list of free blocks. */
  275. xFreeBytesRemaining += pxLink->xBlockSize;
  276. traceFREE( pv, pxLink->xBlockSize );
  277. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  278. xNumberOfSuccessfulFrees++;
  279. }
  280. ( void ) xTaskResumeAll();
  281. }
  282. else
  283. {
  284. mtCOVERAGE_TEST_MARKER();
  285. }
  286. }
  287. else
  288. {
  289. mtCOVERAGE_TEST_MARKER();
  290. }
  291. }
  292. }
  293. /*-----------------------------------------------------------*/
  294. size_t xPortGetFreeHeapSize( void )
  295. {
  296. return xFreeBytesRemaining;
  297. }
  298. /*-----------------------------------------------------------*/
  299. size_t xPortGetMinimumEverFreeHeapSize( void )
  300. {
  301. return xMinimumEverFreeBytesRemaining;
  302. }
  303. /*-----------------------------------------------------------*/
  304. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert )
  305. {
  306. BlockLink_t * pxIterator;
  307. uint8_t * puc;
  308. /* Iterate through the list until a block is found that has a higher address
  309. * than the block being inserted. */
  310. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  311. {
  312. /* Nothing to do here, just iterate to the right position. */
  313. }
  314. /* Do the block being inserted, and the block it is being inserted after
  315. * make a contiguous block of memory? */
  316. puc = ( uint8_t * ) pxIterator;
  317. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  318. {
  319. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  320. pxBlockToInsert = pxIterator;
  321. }
  322. else
  323. {
  324. mtCOVERAGE_TEST_MARKER();
  325. }
  326. /* Do the block being inserted, and the block it is being inserted before
  327. * make a contiguous block of memory? */
  328. puc = ( uint8_t * ) pxBlockToInsert;
  329. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  330. {
  331. if( pxIterator->pxNextFreeBlock != pxEnd )
  332. {
  333. /* Form one big block from the two blocks. */
  334. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  335. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  336. }
  337. else
  338. {
  339. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  340. }
  341. }
  342. else
  343. {
  344. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  345. }
  346. /* If the block being inserted plugged a gab, so was merged with the block
  347. * before and the block after, then it's pxNextFreeBlock pointer will have
  348. * already been set, and should not be set here as that would make it point
  349. * to itself. */
  350. if( pxIterator != pxBlockToInsert )
  351. {
  352. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  353. }
  354. else
  355. {
  356. mtCOVERAGE_TEST_MARKER();
  357. }
  358. }
  359. /*-----------------------------------------------------------*/
  360. void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
  361. {
  362. BlockLink_t * pxFirstFreeBlockInRegion = NULL, * pxPreviousFreeBlock;
  363. size_t xAlignedHeap;
  364. size_t xTotalRegionSize, xTotalHeapSize = 0;
  365. BaseType_t xDefinedRegions = 0;
  366. size_t xAddress;
  367. const HeapRegion_t * pxHeapRegion;
  368. /* Can only call once! */
  369. configASSERT( pxEnd == NULL );
  370. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  371. while( pxHeapRegion->xSizeInBytes > 0 )
  372. {
  373. xTotalRegionSize = pxHeapRegion->xSizeInBytes;
  374. /* Ensure the heap region starts on a correctly aligned boundary. */
  375. xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
  376. if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  377. {
  378. xAddress += ( portBYTE_ALIGNMENT - 1 );
  379. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  380. /* Adjust the size for the bytes lost to alignment. */
  381. xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
  382. }
  383. xAlignedHeap = xAddress;
  384. /* Set xStart if it has not already been set. */
  385. if( xDefinedRegions == 0 )
  386. {
  387. /* xStart is used to hold a pointer to the first item in the list of
  388. * free blocks. The void cast is used to prevent compiler warnings. */
  389. xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
  390. xStart.xBlockSize = ( size_t ) 0;
  391. }
  392. else
  393. {
  394. /* Should only get here if one region has already been added to the
  395. * heap. */
  396. configASSERT( pxEnd != NULL );
  397. /* Check blocks are passed in with increasing start addresses. */
  398. configASSERT( xAddress > ( size_t ) pxEnd );
  399. }
  400. /* Remember the location of the end marker in the previous region, if
  401. * any. */
  402. pxPreviousFreeBlock = pxEnd;
  403. /* pxEnd is used to mark the end of the list of free blocks and is
  404. * inserted at the end of the region space. */
  405. xAddress = xAlignedHeap + xTotalRegionSize;
  406. xAddress -= xHeapStructSize;
  407. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  408. pxEnd = ( BlockLink_t * ) xAddress;
  409. pxEnd->xBlockSize = 0;
  410. pxEnd->pxNextFreeBlock = NULL;
  411. /* To start with there is a single free block in this region that is
  412. * sized to take up the entire heap region minus the space taken by the
  413. * free block structure. */
  414. pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
  415. pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
  416. pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
  417. /* If this is not the first region that makes up the entire heap space
  418. * then link the previous region to this region. */
  419. if( pxPreviousFreeBlock != NULL )
  420. {
  421. pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
  422. }
  423. xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
  424. /* Move onto the next HeapRegion_t structure. */
  425. xDefinedRegions++;
  426. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  427. }
  428. xMinimumEverFreeBytesRemaining = xTotalHeapSize;
  429. xFreeBytesRemaining = xTotalHeapSize;
  430. /* Check something was actually defined before it is accessed. */
  431. configASSERT( xTotalHeapSize );
  432. /* Work out the position of the top bit in a size_t variable. */
  433. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  434. }
  435. /*-----------------------------------------------------------*/
  436. void vPortGetHeapStats( HeapStats_t * pxHeapStats )
  437. {
  438. BlockLink_t * pxBlock;
  439. size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
  440. vTaskSuspendAll();
  441. {
  442. pxBlock = xStart.pxNextFreeBlock;
  443. /* pxBlock will be NULL if the heap has not been initialised. The heap
  444. * is initialised automatically when the first allocation is made. */
  445. if( pxBlock != NULL )
  446. {
  447. do
  448. {
  449. /* Increment the number of blocks and record the largest block seen
  450. * so far. */
  451. xBlocks++;
  452. if( pxBlock->xBlockSize > xMaxSize )
  453. {
  454. xMaxSize = pxBlock->xBlockSize;
  455. }
  456. /* Heap five will have a zero sized block at the end of each
  457. * each region - the block is only used to link to the next
  458. * heap region so it not a real block. */
  459. if( pxBlock->xBlockSize != 0 )
  460. {
  461. if( pxBlock->xBlockSize < xMinSize )
  462. {
  463. xMinSize = pxBlock->xBlockSize;
  464. }
  465. }
  466. /* Move to the next block in the chain until the last block is
  467. * reached. */
  468. pxBlock = pxBlock->pxNextFreeBlock;
  469. } while( pxBlock != pxEnd );
  470. }
  471. }
  472. ( void ) xTaskResumeAll();
  473. pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
  474. pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
  475. pxHeapStats->xNumberOfFreeBlocks = xBlocks;
  476. taskENTER_CRITICAL();
  477. {
  478. pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
  479. pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
  480. pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
  481. pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
  482. }
  483. taskEXIT_CRITICAL();
  484. }