heap_4.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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 __no_init 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( unsigned int size );
  226. vApplicationMallocFailedHook(xWantedSize);
  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 xPortGetMemSize( void * pv )
  282. {
  283. uint8_t * puc = ( uint8_t * ) pv;
  284. BlockLink_t * pxLink;
  285. if( pv != NULL )
  286. {
  287. /* The memory being freed will have an BlockLink_t structure immediately
  288. * before it. */
  289. puc -= xHeapStructSize;
  290. /* This casting is to keep the compiler from issuing warnings. */
  291. pxLink = ( void * ) puc;
  292. /* Check the block is actually allocated. */
  293. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  294. configASSERT( pxLink->pxNextFreeBlock == NULL );
  295. return (pxLink->xBlockSize & ~xBlockAllocatedBit) - xHeapStructSize;
  296. }
  297. return 0;
  298. }
  299. /*-----------------------------------------------------------*/
  300. void * pvPortRealloc( void * pv, size_t xSize )
  301. {
  302. void * new_p = NULL;
  303. uint32_t new_size;
  304. uint32_t old_size = xPortGetMemSize(pv);
  305. new_size = xSize + (portBYTE_ALIGNMENT - (xSize & portBYTE_ALIGNMENT_MASK));
  306. if(old_size == new_size) return pv; /*Also avoid reallocating the same memory*/
  307. new_p = pvPortMalloc(xSize);
  308. if(new_p == NULL) {
  309. return NULL;
  310. }
  311. if(pv != NULL) {
  312. /*Copy the old data to the new. Use the smaller size*/
  313. if(old_size != 0 && xSize != 0) {
  314. int i;
  315. uint8_t *psrc = pv;
  316. uint8_t *pdst = new_p;
  317. for (i = 0; i < configMIN(xSize, old_size); i++)
  318. pdst[i] = psrc[i];
  319. }
  320. vPortFree(pv);
  321. }
  322. return new_p;
  323. }
  324. /*-----------------------------------------------------------*/
  325. size_t xPortGetFreeHeapSize( void )
  326. {
  327. return xFreeBytesRemaining;
  328. }
  329. /*-----------------------------------------------------------*/
  330. size_t xPortGetMinimumEverFreeHeapSize( void )
  331. {
  332. return xMinimumEverFreeBytesRemaining;
  333. }
  334. /*-----------------------------------------------------------*/
  335. void vPortInitialiseBlocks( void )
  336. {
  337. /* This just exists to keep the linker quiet. */
  338. }
  339. /*-----------------------------------------------------------*/
  340. static void prvHeapInit( void ) /* PRIVILEGED_FUNCTION */
  341. {
  342. BlockLink_t * pxFirstFreeBlock;
  343. uint8_t * pucAlignedHeap;
  344. size_t uxAddress;
  345. size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
  346. /* Ensure the heap starts on a correctly aligned boundary. */
  347. uxAddress = ( size_t ) ucHeap;
  348. if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  349. {
  350. uxAddress += ( portBYTE_ALIGNMENT - 1 );
  351. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  352. xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;
  353. }
  354. pucAlignedHeap = ( uint8_t * ) uxAddress;
  355. /* xStart is used to hold a pointer to the first item in the list of free
  356. * blocks. The void cast is used to prevent compiler warnings. */
  357. xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
  358. xStart.xBlockSize = ( size_t ) 0;
  359. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  360. * at the end of the heap space. */
  361. uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;
  362. uxAddress -= xHeapStructSize;
  363. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  364. pxEnd = ( void * ) uxAddress;
  365. pxEnd->xBlockSize = 0;
  366. pxEnd->pxNextFreeBlock = NULL;
  367. /* To start with there is a single free block that is sized to take up the
  368. * entire heap space, minus the space taken by pxEnd. */
  369. pxFirstFreeBlock = ( void * ) pucAlignedHeap;
  370. pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;
  371. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  372. /* Only one block exists - and it covers the entire usable heap space. */
  373. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  374. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  375. /* Work out the position of the top bit in a size_t variable. */
  376. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  377. }
  378. /*-----------------------------------------------------------*/
  379. static void prvInsertBlockIntoFreeList( BlockLink_t * pxBlockToInsert ) /* PRIVILEGED_FUNCTION */
  380. {
  381. BlockLink_t * pxIterator;
  382. uint8_t * puc;
  383. /* Iterate through the list until a block is found that has a higher address
  384. * than the block being inserted. */
  385. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  386. {
  387. /* Nothing to do here, just iterate to the right position. */
  388. }
  389. /* Do the block being inserted, and the block it is being inserted after
  390. * make a contiguous block of memory? */
  391. puc = ( uint8_t * ) pxIterator;
  392. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  393. {
  394. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  395. pxBlockToInsert = pxIterator;
  396. }
  397. else
  398. {
  399. mtCOVERAGE_TEST_MARKER();
  400. }
  401. /* Do the block being inserted, and the block it is being inserted before
  402. * make a contiguous block of memory? */
  403. puc = ( uint8_t * ) pxBlockToInsert;
  404. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  405. {
  406. if( pxIterator->pxNextFreeBlock != pxEnd )
  407. {
  408. /* Form one big block from the two blocks. */
  409. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  410. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  411. }
  412. else
  413. {
  414. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  415. }
  416. }
  417. else
  418. {
  419. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  420. }
  421. /* If the block being inserted plugged a gab, so was merged with the block
  422. * before and the block after, then it's pxNextFreeBlock pointer will have
  423. * already been set, and should not be set here as that would make it point
  424. * to itself. */
  425. if( pxIterator != pxBlockToInsert )
  426. {
  427. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  428. }
  429. else
  430. {
  431. mtCOVERAGE_TEST_MARKER();
  432. }
  433. }
  434. /*-----------------------------------------------------------*/
  435. void vPortGetHeapStats( HeapStats_t * pxHeapStats )
  436. {
  437. BlockLink_t * pxBlock;
  438. size_t xBlocks = 0, xMaxSize = 0, xMinSize = portMAX_DELAY; /* portMAX_DELAY used as a portable way of getting the maximum value. */
  439. vTaskSuspendAll();
  440. {
  441. pxBlock = xStart.pxNextFreeBlock;
  442. /* pxBlock will be NULL if the heap has not been initialised. The heap
  443. * is initialised automatically when the first allocation is made. */
  444. if( pxBlock != NULL )
  445. {
  446. do
  447. {
  448. /* Increment the number of blocks and record the largest block seen
  449. * so far. */
  450. xBlocks++;
  451. if( pxBlock->xBlockSize > xMaxSize )
  452. {
  453. xMaxSize = pxBlock->xBlockSize;
  454. }
  455. if( pxBlock->xBlockSize < xMinSize )
  456. {
  457. xMinSize = pxBlock->xBlockSize;
  458. }
  459. /* Move to the next block in the chain until the last block is
  460. * reached. */
  461. pxBlock = pxBlock->pxNextFreeBlock;
  462. } while( pxBlock != pxEnd );
  463. }
  464. }
  465. ( void ) xTaskResumeAll();
  466. pxHeapStats->xSizeOfLargestFreeBlockInBytes = xMaxSize;
  467. pxHeapStats->xSizeOfSmallestFreeBlockInBytes = xMinSize;
  468. pxHeapStats->xNumberOfFreeBlocks = xBlocks;
  469. taskENTER_CRITICAL();
  470. {
  471. pxHeapStats->xAvailableHeapSpaceInBytes = xFreeBytesRemaining;
  472. pxHeapStats->xNumberOfSuccessfulAllocations = xNumberOfSuccessfulAllocations;
  473. pxHeapStats->xNumberOfSuccessfulFrees = xNumberOfSuccessfulFrees;
  474. pxHeapStats->xMinimumEverFreeBytesRemaining = xMinimumEverFreeBytesRemaining;
  475. }
  476. taskEXIT_CRITICAL();
  477. }