heap_4.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  1. /*
  2. FreeRTOS V9.0.0 - Copyright (C) 2016 Real Time Engineers Ltd.
  3. All rights reserved
  4. VISIT http://www.FreeRTOS.org TO ENSURE YOU ARE USING THE LATEST VERSION.
  5. This file is part of the FreeRTOS distribution.
  6. FreeRTOS is free software; you can redistribute it and/or modify it under
  7. the terms of the GNU General Public License (version 2) as published by the
  8. Free Software Foundation >>>> AND MODIFIED BY <<<< the FreeRTOS exception.
  9. ***************************************************************************
  10. >>! NOTE: The modification to the GPL is included to allow you to !<<
  11. >>! distribute a combined work that includes FreeRTOS without being !<<
  12. >>! obliged to provide the source code for proprietary components !<<
  13. >>! outside of the FreeRTOS kernel. !<<
  14. ***************************************************************************
  15. FreeRTOS is distributed in the hope that it will be useful, but WITHOUT ANY
  16. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  17. FOR A PARTICULAR PURPOSE. Full license text is available on the following
  18. link: http://www.freertos.org/a00114.html
  19. ***************************************************************************
  20. * *
  21. * FreeRTOS provides completely free yet professionally developed, *
  22. * robust, strictly quality controlled, supported, and cross *
  23. * platform software that is more than just the market leader, it *
  24. * is the industry's de facto standard. *
  25. * *
  26. * Help yourself get started quickly while simultaneously helping *
  27. * to support the FreeRTOS project by purchasing a FreeRTOS *
  28. * tutorial book, reference manual, or both: *
  29. * http://www.FreeRTOS.org/Documentation *
  30. * *
  31. ***************************************************************************
  32. http://www.FreeRTOS.org/FAQHelp.html - Having a problem? Start by reading
  33. the FAQ page "My application does not run, what could be wrong?". Have you
  34. defined configASSERT()?
  35. http://www.FreeRTOS.org/support - In return for receiving this top quality
  36. embedded software for free we request you assist our global community by
  37. participating in the support forum.
  38. http://www.FreeRTOS.org/training - Investing in training allows your team to
  39. be as productive as possible as early as possible. Now you can receive
  40. FreeRTOS training directly from Richard Barry, CEO of Real Time Engineers
  41. Ltd, and the world's leading authority on the world's leading RTOS.
  42. http://www.FreeRTOS.org/plus - A selection of FreeRTOS ecosystem products,
  43. including FreeRTOS+Trace - an indispensable productivity tool, a DOS
  44. compatible FAT file system, and our tiny thread aware UDP/IP stack.
  45. http://www.FreeRTOS.org/labs - Where new FreeRTOS products go to incubate.
  46. Come and try FreeRTOS+TCP, our new open source TCP/IP stack for FreeRTOS.
  47. http://www.OpenRTOS.com - Real Time Engineers ltd. license FreeRTOS to High
  48. Integrity Systems ltd. to sell under the OpenRTOS brand. Low cost OpenRTOS
  49. licenses offer ticketed support, indemnification and commercial middleware.
  50. http://www.SafeRTOS.com - High Integrity Systems also provide a safety
  51. engineered and independently SIL3 certified version for use in safety and
  52. mission critical applications that require provable dependability.
  53. 1 tab == 4 spaces!
  54. */
  55. /*
  56. * A sample implementation of pvPortMalloc() and vPortFree() that combines
  57. * (coalescences) adjacent memory blocks as they are freed, and in so doing
  58. * limits memory fragmentation.
  59. *
  60. * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the
  61. * memory management pages of http://www.FreeRTOS.org for more information.
  62. */
  63. #include <stdlib.h>
  64. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  65. all the API functions to use the MPU wrappers. That should only be done when
  66. task.h is included from an application file. */
  67. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  68. #include "FreeRTOS.h"
  69. #include "task.h"
  70. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  71. #if( configSUPPORT_DYNAMIC_ALLOCATION == 0 )
  72. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  73. #endif
  74. /* Block sizes must not get too small. */
  75. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  76. /* Assumes 8bit bytes! */
  77. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  78. /* Allocate the memory for the heap. */
  79. #if( configAPPLICATION_ALLOCATED_HEAP == 1 )
  80. /* The application writer has already defined the array used for the RTOS
  81. heap - probably so it can be placed in a special segment or address. */
  82. extern uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  83. #else
  84. static uint8_t ucHeap[ configTOTAL_HEAP_SIZE ];
  85. #endif /* configAPPLICATION_ALLOCATED_HEAP */
  86. /* Define the linked list structure. This is used to link free blocks in order
  87. of their memory address. */
  88. typedef struct A_BLOCK_LINK
  89. {
  90. struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
  91. size_t xBlockSize; /*<< The size of the free block. */
  92. } BlockLink_t;
  93. /*-----------------------------------------------------------*/
  94. /*
  95. * Inserts a block of memory that is being freed into the correct position in
  96. * the list of free memory blocks. The block being freed will be merged with
  97. * the block in front it and/or the block behind it if the memory blocks are
  98. * adjacent to each other.
  99. */
  100. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );
  101. /*
  102. * Called automatically to setup the required heap structures the first time
  103. * pvPortMalloc() is called.
  104. */
  105. static void prvHeapInit( void );
  106. /*-----------------------------------------------------------*/
  107. /* The size of the structure placed at the beginning of each allocated memory
  108. block must by correctly byte aligned. */
  109. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  110. /* Create a couple of list links to mark the start and end of the list. */
  111. static BlockLink_t xStart, *pxEnd = NULL;
  112. /* Keeps track of the number of free bytes remaining, but says nothing about
  113. fragmentation. */
  114. static size_t xFreeBytesRemaining = 0U;
  115. static size_t xMinimumEverFreeBytesRemaining = 0U;
  116. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  117. member of an BlockLink_t structure is set then the block belongs to the
  118. application. When the bit is free the block is still part of the free heap
  119. space. */
  120. static size_t xBlockAllocatedBit = 0;
  121. /*-----------------------------------------------------------*/
  122. void *pvPortMalloc( size_t xWantedSize )
  123. {
  124. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  125. void *pvReturn = NULL;
  126. vTaskSuspendAll();
  127. {
  128. /* If this is the first call to malloc then the heap will require
  129. initialisation to setup the list of free blocks. */
  130. if( pxEnd == NULL )
  131. {
  132. prvHeapInit();
  133. }
  134. else
  135. {
  136. mtCOVERAGE_TEST_MARKER();
  137. }
  138. /* Check the requested block size is not so large that the top bit is
  139. set. The top bit of the block size member of the BlockLink_t structure
  140. is used to determine who owns the block - the application or the
  141. kernel, so it must be free. */
  142. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  143. {
  144. /* The wanted size is increased so it can contain a BlockLink_t
  145. structure in addition to the requested amount of bytes. */
  146. if( xWantedSize > 0 )
  147. {
  148. xWantedSize += xHeapStructSize;
  149. /* Ensure that blocks are always aligned to the required number
  150. of bytes. */
  151. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  152. {
  153. /* Byte alignment required. */
  154. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  155. configASSERT( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) == 0 );
  156. }
  157. else
  158. {
  159. mtCOVERAGE_TEST_MARKER();
  160. }
  161. }
  162. else
  163. {
  164. mtCOVERAGE_TEST_MARKER();
  165. }
  166. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  167. {
  168. /* Traverse the list from the start (lowest address) block until
  169. one of adequate size is found. */
  170. pxPreviousBlock = &xStart;
  171. pxBlock = xStart.pxNextFreeBlock;
  172. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  173. {
  174. pxPreviousBlock = pxBlock;
  175. pxBlock = pxBlock->pxNextFreeBlock;
  176. }
  177. /* If the end marker was reached then a block of adequate size
  178. was not found. */
  179. if( pxBlock != pxEnd )
  180. {
  181. /* Return the memory space pointed to - jumping over the
  182. BlockLink_t structure at its start. */
  183. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  184. /* This block is being returned for use so must be taken out
  185. of the list of free blocks. */
  186. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  187. /* If the block is larger than required it can be split into
  188. two. */
  189. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  190. {
  191. /* This block is to be split into two. Create a new
  192. block following the number of bytes requested. The void
  193. cast is used to prevent byte alignment warnings from the
  194. compiler. */
  195. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  196. configASSERT( ( ( ( size_t ) pxNewBlockLink ) & portBYTE_ALIGNMENT_MASK ) == 0 );
  197. /* Calculate the sizes of two blocks split from the
  198. single block. */
  199. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  200. pxBlock->xBlockSize = xWantedSize;
  201. /* Insert the new block into the list of free blocks. */
  202. prvInsertBlockIntoFreeList( pxNewBlockLink );
  203. }
  204. else
  205. {
  206. mtCOVERAGE_TEST_MARKER();
  207. }
  208. xFreeBytesRemaining -= pxBlock->xBlockSize;
  209. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  210. {
  211. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  212. }
  213. else
  214. {
  215. mtCOVERAGE_TEST_MARKER();
  216. }
  217. /* The block is being returned - it is allocated and owned
  218. by the application and has no "next" block. */
  219. pxBlock->xBlockSize |= xBlockAllocatedBit;
  220. pxBlock->pxNextFreeBlock = NULL;
  221. }
  222. else
  223. {
  224. mtCOVERAGE_TEST_MARKER();
  225. }
  226. }
  227. else
  228. {
  229. mtCOVERAGE_TEST_MARKER();
  230. }
  231. }
  232. else
  233. {
  234. mtCOVERAGE_TEST_MARKER();
  235. }
  236. traceMALLOC( pvReturn, xWantedSize );
  237. }
  238. ( void ) xTaskResumeAll();
  239. #if( configUSE_MALLOC_FAILED_HOOK == 1 )
  240. {
  241. if( pvReturn == NULL )
  242. {
  243. extern void vApplicationMallocFailedHook( void );
  244. vApplicationMallocFailedHook();
  245. }
  246. else
  247. {
  248. mtCOVERAGE_TEST_MARKER();
  249. }
  250. }
  251. #endif
  252. configASSERT( ( ( ( size_t ) pvReturn ) & ( size_t ) portBYTE_ALIGNMENT_MASK ) == 0 );
  253. return pvReturn;
  254. }
  255. /*-----------------------------------------------------------*/
  256. void vPortFree( void *pv )
  257. {
  258. uint8_t *puc = ( uint8_t * ) pv;
  259. BlockLink_t *pxLink;
  260. if( pv != NULL )
  261. {
  262. /* The memory being freed will have an BlockLink_t structure immediately
  263. before it. */
  264. puc -= xHeapStructSize;
  265. /* This casting is to keep the compiler from issuing warnings. */
  266. pxLink = ( void * ) puc;
  267. /* Check the block is actually allocated. */
  268. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  269. configASSERT( pxLink->pxNextFreeBlock == NULL );
  270. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  271. {
  272. if( pxLink->pxNextFreeBlock == NULL )
  273. {
  274. /* The block is being returned to the heap - it is no longer
  275. allocated. */
  276. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  277. vTaskSuspendAll();
  278. {
  279. /* Add this block to the list of free blocks. */
  280. xFreeBytesRemaining += pxLink->xBlockSize;
  281. traceFREE( pv, pxLink->xBlockSize );
  282. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  283. }
  284. ( void ) xTaskResumeAll();
  285. }
  286. else
  287. {
  288. mtCOVERAGE_TEST_MARKER();
  289. }
  290. }
  291. else
  292. {
  293. mtCOVERAGE_TEST_MARKER();
  294. }
  295. }
  296. }
  297. /*-----------------------------------------------------------*/
  298. size_t xPortGetFreeHeapSize( void )
  299. {
  300. return xFreeBytesRemaining;
  301. }
  302. /*-----------------------------------------------------------*/
  303. size_t xPortGetMinimumEverFreeHeapSize( void )
  304. {
  305. return xMinimumEverFreeBytesRemaining;
  306. }
  307. /*-----------------------------------------------------------*/
  308. void vPortInitialiseBlocks( void )
  309. {
  310. /* This just exists to keep the linker quiet. */
  311. }
  312. /*-----------------------------------------------------------*/
  313. static void prvHeapInit( void )
  314. {
  315. BlockLink_t *pxFirstFreeBlock;
  316. uint8_t *pucAlignedHeap;
  317. size_t uxAddress;
  318. size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
  319. /* Ensure the heap starts on a correctly aligned boundary. */
  320. uxAddress = ( size_t ) ucHeap;
  321. if( ( uxAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  322. {
  323. uxAddress += ( portBYTE_ALIGNMENT - 1 );
  324. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  325. xTotalHeapSize -= uxAddress - ( size_t ) ucHeap;
  326. }
  327. pucAlignedHeap = ( uint8_t * ) uxAddress;
  328. /* xStart is used to hold a pointer to the first item in the list of free
  329. blocks. The void cast is used to prevent compiler warnings. */
  330. xStart.pxNextFreeBlock = ( void * ) pucAlignedHeap;
  331. xStart.xBlockSize = ( size_t ) 0;
  332. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  333. at the end of the heap space. */
  334. uxAddress = ( ( size_t ) pucAlignedHeap ) + xTotalHeapSize;
  335. uxAddress -= xHeapStructSize;
  336. uxAddress &= ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  337. pxEnd = ( void * ) uxAddress;
  338. pxEnd->xBlockSize = 0;
  339. pxEnd->pxNextFreeBlock = NULL;
  340. /* To start with there is a single free block that is sized to take up the
  341. entire heap space, minus the space taken by pxEnd. */
  342. pxFirstFreeBlock = ( void * ) pucAlignedHeap;
  343. pxFirstFreeBlock->xBlockSize = uxAddress - ( size_t ) pxFirstFreeBlock;
  344. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  345. /* Only one block exists - and it covers the entire usable heap space. */
  346. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  347. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  348. /* Work out the position of the top bit in a size_t variable. */
  349. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  350. }
  351. /*-----------------------------------------------------------*/
  352. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )
  353. {
  354. BlockLink_t *pxIterator;
  355. uint8_t *puc;
  356. /* Iterate through the list until a block is found that has a higher address
  357. than the block being inserted. */
  358. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  359. {
  360. /* Nothing to do here, just iterate to the right position. */
  361. }
  362. /* Do the block being inserted, and the block it is being inserted after
  363. make a contiguous block of memory? */
  364. puc = ( uint8_t * ) pxIterator;
  365. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  366. {
  367. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  368. pxBlockToInsert = pxIterator;
  369. }
  370. else
  371. {
  372. mtCOVERAGE_TEST_MARKER();
  373. }
  374. /* Do the block being inserted, and the block it is being inserted before
  375. make a contiguous block of memory? */
  376. puc = ( uint8_t * ) pxBlockToInsert;
  377. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  378. {
  379. if( pxIterator->pxNextFreeBlock != pxEnd )
  380. {
  381. /* Form one big block from the two blocks. */
  382. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  383. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  384. }
  385. else
  386. {
  387. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  388. }
  389. }
  390. else
  391. {
  392. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  393. }
  394. /* If the block being inserted plugged a gab, so was merged with the block
  395. before and the block after, then it's pxNextFreeBlock pointer will have
  396. already been set, and should not be set here as that would make it point
  397. to itself. */
  398. if( pxIterator != pxBlockToInsert )
  399. {
  400. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  401. }
  402. else
  403. {
  404. mtCOVERAGE_TEST_MARKER();
  405. }
  406. }