heap_5.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523
  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() that allows the heap to be defined
  57. * across multiple non-contigous blocks and combines (coalescences) adjacent
  58. * memory blocks as they are freed.
  59. *
  60. * See heap_1.c, heap_2.c, heap_3.c and heap_4.c for alternative
  61. * implementations, and the memory management pages of http://www.FreeRTOS.org
  62. * for more information.
  63. *
  64. * Usage notes:
  65. *
  66. * vPortDefineHeapRegions() ***must*** be called before pvPortMalloc().
  67. * pvPortMalloc() will be called if any task objects (tasks, queues, event
  68. * groups, etc.) are created, therefore vPortDefineHeapRegions() ***must*** be
  69. * called before any other objects are defined.
  70. *
  71. * vPortDefineHeapRegions() takes a single parameter. The parameter is an array
  72. * of HeapRegion_t structures. HeapRegion_t is defined in portable.h as
  73. *
  74. * typedef struct HeapRegion
  75. * {
  76. * uint8_t *pucStartAddress; << Start address of a block of memory that will be part of the heap.
  77. * size_t xSizeInBytes; << Size of the block of memory.
  78. * } HeapRegion_t;
  79. *
  80. * The array is terminated using a NULL zero sized region definition, and the
  81. * memory regions defined in the array ***must*** appear in address order from
  82. * low address to high address. So the following is a valid example of how
  83. * to use the function.
  84. *
  85. * HeapRegion_t xHeapRegions[] =
  86. * {
  87. * { ( uint8_t * ) 0x80000000UL, 0x10000 }, << Defines a block of 0x10000 bytes starting at address 0x80000000
  88. * { ( uint8_t * ) 0x90000000UL, 0xa0000 }, << Defines a block of 0xa0000 bytes starting at address of 0x90000000
  89. * { NULL, 0 } << Terminates the array.
  90. * };
  91. *
  92. * vPortDefineHeapRegions( xHeapRegions ); << Pass the array into vPortDefineHeapRegions().
  93. *
  94. * Note 0x80000000 is the lower address so appears in the array first.
  95. *
  96. */
  97. #include <stdlib.h>
  98. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  99. all the API functions to use the MPU wrappers. That should only be done when
  100. task.h is included from an application file. */
  101. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  102. #include "FreeRTOS.h"
  103. #include "task.h"
  104. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  105. /* Block sizes must not get too small. */
  106. #define heapMINIMUM_BLOCK_SIZE ( ( size_t ) ( xHeapStructSize << 1 ) )
  107. /* Assumes 8bit bytes! */
  108. #define heapBITS_PER_BYTE ( ( size_t ) 8 )
  109. /* Define the linked list structure. This is used to link free blocks in order
  110. of their memory address. */
  111. typedef struct A_BLOCK_LINK
  112. {
  113. struct A_BLOCK_LINK *pxNextFreeBlock; /*<< The next free block in the list. */
  114. size_t xBlockSize; /*<< The size of the free block. */
  115. } BlockLink_t;
  116. /*-----------------------------------------------------------*/
  117. /*
  118. * Inserts a block of memory that is being freed into the correct position in
  119. * the list of free memory blocks. The block being freed will be merged with
  120. * the block in front it and/or the block behind it if the memory blocks are
  121. * adjacent to each other.
  122. */
  123. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert );
  124. /*-----------------------------------------------------------*/
  125. /* The size of the structure placed at the beginning of each allocated memory
  126. block must by correctly byte aligned. */
  127. static const size_t xHeapStructSize = ( sizeof( BlockLink_t ) + ( ( size_t ) ( portBYTE_ALIGNMENT - 1 ) ) ) & ~( ( size_t ) portBYTE_ALIGNMENT_MASK );
  128. /* Create a couple of list links to mark the start and end of the list. */
  129. static BlockLink_t xStart, *pxEnd = NULL;
  130. /* Keeps track of the number of free bytes remaining, but says nothing about
  131. fragmentation. */
  132. static size_t xFreeBytesRemaining = 0U;
  133. static size_t xMinimumEverFreeBytesRemaining = 0U;
  134. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  135. member of an BlockLink_t structure is set then the block belongs to the
  136. application. When the bit is free the block is still part of the free heap
  137. space. */
  138. static size_t xBlockAllocatedBit = 0;
  139. /*-----------------------------------------------------------*/
  140. void *pvPortMalloc( size_t xWantedSize )
  141. {
  142. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  143. void *pvReturn = NULL;
  144. /* The heap must be initialised before the first call to
  145. prvPortMalloc(). */
  146. configASSERT( pxEnd );
  147. vTaskSuspendAll();
  148. {
  149. /* Check the requested block size is not so large that the top bit is
  150. set. The top bit of the block size member of the BlockLink_t structure
  151. is used to determine who owns the block - the application or the
  152. kernel, so it must be free. */
  153. if( ( xWantedSize & xBlockAllocatedBit ) == 0 )
  154. {
  155. /* The wanted size is increased so it can contain a BlockLink_t
  156. structure in addition to the requested amount of bytes. */
  157. if( xWantedSize > 0 )
  158. {
  159. xWantedSize += xHeapStructSize;
  160. /* Ensure that blocks are always aligned to the required number
  161. of bytes. */
  162. if( ( xWantedSize & portBYTE_ALIGNMENT_MASK ) != 0x00 )
  163. {
  164. /* Byte alignment required. */
  165. xWantedSize += ( portBYTE_ALIGNMENT - ( xWantedSize & portBYTE_ALIGNMENT_MASK ) );
  166. }
  167. else
  168. {
  169. mtCOVERAGE_TEST_MARKER();
  170. }
  171. }
  172. else
  173. {
  174. mtCOVERAGE_TEST_MARKER();
  175. }
  176. if( ( xWantedSize > 0 ) && ( xWantedSize <= xFreeBytesRemaining ) )
  177. {
  178. /* Traverse the list from the start (lowest address) block until
  179. one of adequate size is found. */
  180. pxPreviousBlock = &xStart;
  181. pxBlock = xStart.pxNextFreeBlock;
  182. while( ( pxBlock->xBlockSize < xWantedSize ) && ( pxBlock->pxNextFreeBlock != NULL ) )
  183. {
  184. pxPreviousBlock = pxBlock;
  185. pxBlock = pxBlock->pxNextFreeBlock;
  186. }
  187. /* If the end marker was reached then a block of adequate size
  188. was not found. */
  189. if( pxBlock != pxEnd )
  190. {
  191. /* Return the memory space pointed to - jumping over the
  192. BlockLink_t structure at its start. */
  193. pvReturn = ( void * ) ( ( ( uint8_t * ) pxPreviousBlock->pxNextFreeBlock ) + xHeapStructSize );
  194. /* This block is being returned for use so must be taken out
  195. of the list of free blocks. */
  196. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  197. /* If the block is larger than required it can be split into
  198. two. */
  199. if( ( pxBlock->xBlockSize - xWantedSize ) > heapMINIMUM_BLOCK_SIZE )
  200. {
  201. /* This block is to be split into two. Create a new
  202. block following the number of bytes requested. The void
  203. cast is used to prevent byte alignment warnings from the
  204. compiler. */
  205. pxNewBlockLink = ( void * ) ( ( ( uint8_t * ) pxBlock ) + xWantedSize );
  206. /* Calculate the sizes of two blocks split from the
  207. single block. */
  208. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  209. pxBlock->xBlockSize = xWantedSize;
  210. /* Insert the new block into the list of free blocks. */
  211. prvInsertBlockIntoFreeList( ( pxNewBlockLink ) );
  212. }
  213. else
  214. {
  215. mtCOVERAGE_TEST_MARKER();
  216. }
  217. xFreeBytesRemaining -= pxBlock->xBlockSize;
  218. if( xFreeBytesRemaining < xMinimumEverFreeBytesRemaining )
  219. {
  220. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  221. }
  222. else
  223. {
  224. mtCOVERAGE_TEST_MARKER();
  225. }
  226. /* The block is being returned - it is allocated and owned
  227. by the application and has no "next" block. */
  228. pxBlock->xBlockSize |= xBlockAllocatedBit;
  229. pxBlock->pxNextFreeBlock = NULL;
  230. }
  231. else
  232. {
  233. mtCOVERAGE_TEST_MARKER();
  234. }
  235. }
  236. else
  237. {
  238. mtCOVERAGE_TEST_MARKER();
  239. }
  240. }
  241. else
  242. {
  243. mtCOVERAGE_TEST_MARKER();
  244. }
  245. traceMALLOC( pvReturn, xWantedSize );
  246. }
  247. ( void ) xTaskResumeAll();
  248. #if( configUSE_MALLOC_FAILED_HOOK == 1 )
  249. {
  250. if( pvReturn == NULL )
  251. {
  252. extern void vApplicationMallocFailedHook( void );
  253. vApplicationMallocFailedHook();
  254. }
  255. else
  256. {
  257. mtCOVERAGE_TEST_MARKER();
  258. }
  259. }
  260. #endif
  261. return pvReturn;
  262. }
  263. /*-----------------------------------------------------------*/
  264. void vPortFree( void *pv )
  265. {
  266. uint8_t *puc = ( uint8_t * ) pv;
  267. BlockLink_t *pxLink;
  268. if( pv != NULL )
  269. {
  270. /* The memory being freed will have an BlockLink_t structure immediately
  271. before it. */
  272. puc -= xHeapStructSize;
  273. /* This casting is to keep the compiler from issuing warnings. */
  274. pxLink = ( void * ) puc;
  275. /* Check the block is actually allocated. */
  276. configASSERT( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 );
  277. configASSERT( pxLink->pxNextFreeBlock == NULL );
  278. if( ( pxLink->xBlockSize & xBlockAllocatedBit ) != 0 )
  279. {
  280. if( pxLink->pxNextFreeBlock == NULL )
  281. {
  282. /* The block is being returned to the heap - it is no longer
  283. allocated. */
  284. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  285. vTaskSuspendAll();
  286. {
  287. /* Add this block to the list of free blocks. */
  288. xFreeBytesRemaining += pxLink->xBlockSize;
  289. traceFREE( pv, pxLink->xBlockSize );
  290. prvInsertBlockIntoFreeList( ( ( BlockLink_t * ) pxLink ) );
  291. }
  292. ( void ) xTaskResumeAll();
  293. }
  294. else
  295. {
  296. mtCOVERAGE_TEST_MARKER();
  297. }
  298. }
  299. else
  300. {
  301. mtCOVERAGE_TEST_MARKER();
  302. }
  303. }
  304. }
  305. /*-----------------------------------------------------------*/
  306. size_t xPortGetFreeHeapSize( void )
  307. {
  308. return xFreeBytesRemaining;
  309. }
  310. /*-----------------------------------------------------------*/
  311. size_t xPortGetMinimumEverFreeHeapSize( void )
  312. {
  313. return xMinimumEverFreeBytesRemaining;
  314. }
  315. /*-----------------------------------------------------------*/
  316. static void prvInsertBlockIntoFreeList( BlockLink_t *pxBlockToInsert )
  317. {
  318. BlockLink_t *pxIterator;
  319. uint8_t *puc;
  320. /* Iterate through the list until a block is found that has a higher address
  321. than the block being inserted. */
  322. for( pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert; pxIterator = pxIterator->pxNextFreeBlock )
  323. {
  324. /* Nothing to do here, just iterate to the right position. */
  325. }
  326. /* Do the block being inserted, and the block it is being inserted after
  327. make a contiguous block of memory? */
  328. puc = ( uint8_t * ) pxIterator;
  329. if( ( puc + pxIterator->xBlockSize ) == ( uint8_t * ) pxBlockToInsert )
  330. {
  331. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  332. pxBlockToInsert = pxIterator;
  333. }
  334. else
  335. {
  336. mtCOVERAGE_TEST_MARKER();
  337. }
  338. /* Do the block being inserted, and the block it is being inserted before
  339. make a contiguous block of memory? */
  340. puc = ( uint8_t * ) pxBlockToInsert;
  341. if( ( puc + pxBlockToInsert->xBlockSize ) == ( uint8_t * ) pxIterator->pxNextFreeBlock )
  342. {
  343. if( pxIterator->pxNextFreeBlock != pxEnd )
  344. {
  345. /* Form one big block from the two blocks. */
  346. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  347. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  348. }
  349. else
  350. {
  351. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  352. }
  353. }
  354. else
  355. {
  356. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  357. }
  358. /* If the block being inserted plugged a gab, so was merged with the block
  359. before and the block after, then it's pxNextFreeBlock pointer will have
  360. already been set, and should not be set here as that would make it point
  361. to itself. */
  362. if( pxIterator != pxBlockToInsert )
  363. {
  364. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  365. }
  366. else
  367. {
  368. mtCOVERAGE_TEST_MARKER();
  369. }
  370. }
  371. /*-----------------------------------------------------------*/
  372. void vPortDefineHeapRegions( const HeapRegion_t * const pxHeapRegions )
  373. {
  374. BlockLink_t *pxFirstFreeBlockInRegion = NULL, *pxPreviousFreeBlock;
  375. size_t xAlignedHeap;
  376. size_t xTotalRegionSize, xTotalHeapSize = 0;
  377. BaseType_t xDefinedRegions = 0;
  378. size_t xAddress;
  379. const HeapRegion_t *pxHeapRegion;
  380. /* Can only call once! */
  381. configASSERT( pxEnd == NULL );
  382. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  383. while( pxHeapRegion->xSizeInBytes > 0 )
  384. {
  385. xTotalRegionSize = pxHeapRegion->xSizeInBytes;
  386. /* Ensure the heap region starts on a correctly aligned boundary. */
  387. xAddress = ( size_t ) pxHeapRegion->pucStartAddress;
  388. if( ( xAddress & portBYTE_ALIGNMENT_MASK ) != 0 )
  389. {
  390. xAddress += ( portBYTE_ALIGNMENT - 1 );
  391. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  392. /* Adjust the size for the bytes lost to alignment. */
  393. xTotalRegionSize -= xAddress - ( size_t ) pxHeapRegion->pucStartAddress;
  394. }
  395. xAlignedHeap = xAddress;
  396. /* Set xStart if it has not already been set. */
  397. if( xDefinedRegions == 0 )
  398. {
  399. /* xStart is used to hold a pointer to the first item in the list of
  400. free blocks. The void cast is used to prevent compiler warnings. */
  401. xStart.pxNextFreeBlock = ( BlockLink_t * ) xAlignedHeap;
  402. xStart.xBlockSize = ( size_t ) 0;
  403. }
  404. else
  405. {
  406. /* Should only get here if one region has already been added to the
  407. heap. */
  408. configASSERT( pxEnd != NULL );
  409. /* Check blocks are passed in with increasing start addresses. */
  410. configASSERT( xAddress > ( size_t ) pxEnd );
  411. }
  412. /* Remember the location of the end marker in the previous region, if
  413. any. */
  414. pxPreviousFreeBlock = pxEnd;
  415. /* pxEnd is used to mark the end of the list of free blocks and is
  416. inserted at the end of the region space. */
  417. xAddress = xAlignedHeap + xTotalRegionSize;
  418. xAddress -= xHeapStructSize;
  419. xAddress &= ~portBYTE_ALIGNMENT_MASK;
  420. pxEnd = ( BlockLink_t * ) xAddress;
  421. pxEnd->xBlockSize = 0;
  422. pxEnd->pxNextFreeBlock = NULL;
  423. /* To start with there is a single free block in this region that is
  424. sized to take up the entire heap region minus the space taken by the
  425. free block structure. */
  426. pxFirstFreeBlockInRegion = ( BlockLink_t * ) xAlignedHeap;
  427. pxFirstFreeBlockInRegion->xBlockSize = xAddress - ( size_t ) pxFirstFreeBlockInRegion;
  428. pxFirstFreeBlockInRegion->pxNextFreeBlock = pxEnd;
  429. /* If this is not the first region that makes up the entire heap space
  430. then link the previous region to this region. */
  431. if( pxPreviousFreeBlock != NULL )
  432. {
  433. pxPreviousFreeBlock->pxNextFreeBlock = pxFirstFreeBlockInRegion;
  434. }
  435. xTotalHeapSize += pxFirstFreeBlockInRegion->xBlockSize;
  436. /* Move onto the next HeapRegion_t structure. */
  437. xDefinedRegions++;
  438. pxHeapRegion = &( pxHeapRegions[ xDefinedRegions ] );
  439. }
  440. xMinimumEverFreeBytesRemaining = xTotalHeapSize;
  441. xFreeBytesRemaining = xTotalHeapSize;
  442. /* Check something was actually defined before it is accessed. */
  443. configASSERT( xTotalHeapSize );
  444. /* Work out the position of the top bit in a size_t variable. */
  445. xBlockAllocatedBit = ( ( size_t ) 1 ) << ( ( sizeof( size_t ) * heapBITS_PER_BYTE ) - 1 );
  446. }