heap_4.c 16 KB

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