heap_4.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. /*
  2. * FreeRTOS Kernel V10.2.1
  3. * Copyright (C) 2019 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. * http://www.FreeRTOS.org
  23. * http://aws.amazon.com/freertos
  24. *
  25. * 1 tab == 4 spaces!
  26. */
  27. /*
  28. * A sample implementation of pvPortMalloc() and vPortFree() that combines
  29. * (coalescences) adjacent memory blocks as they are freed, and in so doing
  30. * limits memory fragmentation.
  31. *
  32. * See heap_1.c, heap_2.c and heap_3.c for alternative implementations, and the
  33. * memory management pages of http://www.FreeRTOS.org for more information.
  34. */
  35. #include "heap.h"
  36. osMutexId_t heap_managment_mutex = NULL;
  37. /* Block sizes must not get too small. */
  38. #define heapMINIMUM_BLOCK_SIZE ((size_t)(xHeapStructSize << 1))
  39. /* Assumes 8bit bytes! */
  40. #define heapBITS_PER_BYTE ((size_t)8)
  41. /* Allocate the memory for the heap. */
  42. #if(configAPPLICATION_ALLOCATED_HEAP == 1)
  43. /* The application writer has already defined the array used for the RTOS
  44. heap - probably so it can be placed in a special segment or address. */
  45. extern uint8_t ucHeap[configTOTAL_HEAP_SIZE];
  46. #else
  47. static uint8_t ucHeap[configTOTAL_HEAP_SIZE];
  48. #endif /* configAPPLICATION_ALLOCATED_HEAP */
  49. /* Define the linked list structure. This is used to link free blocks in order
  50. of their memory address. */
  51. typedef struct A_BLOCK_LINK {
  52. struct A_BLOCK_LINK* pxNextFreeBlock; /*<< The next free block in the list. */
  53. size_t xBlockSize; /*<< The size of the free block. */
  54. } BlockLink_t;
  55. /*-----------------------------------------------------------*/
  56. /*
  57. * Inserts a block of memory that is being freed into the correct position in
  58. * the list of free memory blocks. The block being freed will be merged with
  59. * the block in front it and/or the block behind it if the memory blocks are
  60. * adjacent to each other.
  61. */
  62. static void prvInsertBlockIntoFreeList(BlockLink_t* pxBlockToInsert);
  63. // this function is not thread-safe, so it must be called in single thread context
  64. bool prvHeapInit(void);
  65. /*-----------------------------------------------------------*/
  66. /* The size of the structure placed at the beginning of each allocated memory
  67. block must by correctly byte aligned. */
  68. static const size_t xHeapStructSize = (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) &
  69. ~((size_t)portBYTE_ALIGNMENT_MASK);
  70. /* Create a couple of list links to mark the start and end of the list. */
  71. static BlockLink_t xStart, *pxEnd = NULL;
  72. /* Keeps track of the number of free bytes remaining, but says nothing about
  73. fragmentation. */
  74. static size_t xFreeBytesRemaining = 0U;
  75. static size_t xMinimumEverFreeBytesRemaining = 0U;
  76. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  77. member of an BlockLink_t structure is set then the block belongs to the
  78. application. When the bit is free the block is still part of the free heap
  79. space. */
  80. static size_t xBlockAllocatedBit = 0;
  81. /*-----------------------------------------------------------*/
  82. void* pvPortMalloc(size_t xWantedSize) {
  83. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  84. void* pvReturn = NULL;
  85. acquire_memalloc_mutex();
  86. {
  87. /* If this is the first call to malloc then the heap will require
  88. initialisation to setup the list of free blocks. */
  89. if(pxEnd == NULL) {
  90. prvHeapInit();
  91. } else {
  92. mtCOVERAGE_TEST_MARKER();
  93. }
  94. /* Check the requested block size is not so large that the top bit is
  95. set. The top bit of the block size member of the BlockLink_t structure
  96. is used to determine who owns the block - the application or the
  97. kernel, so it must be free. */
  98. if((xWantedSize & xBlockAllocatedBit) == 0) {
  99. /* The wanted size is increased so it can contain a BlockLink_t
  100. structure in addition to the requested amount of bytes. */
  101. if(xWantedSize > 0) {
  102. xWantedSize += xHeapStructSize;
  103. /* Ensure that blocks are always aligned to the required number
  104. of bytes. */
  105. if((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) {
  106. /* Byte alignment required. */
  107. xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK));
  108. configASSERT((xWantedSize & portBYTE_ALIGNMENT_MASK) == 0);
  109. } else {
  110. mtCOVERAGE_TEST_MARKER();
  111. }
  112. } else {
  113. mtCOVERAGE_TEST_MARKER();
  114. }
  115. if((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) {
  116. /* Traverse the list from the start (lowest address) block until
  117. one of adequate size is found. */
  118. pxPreviousBlock = &xStart;
  119. pxBlock = xStart.pxNextFreeBlock;
  120. while((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) {
  121. pxPreviousBlock = pxBlock;
  122. pxBlock = pxBlock->pxNextFreeBlock;
  123. }
  124. /* If the end marker was reached then a block of adequate size
  125. was not found. */
  126. if(pxBlock != pxEnd) {
  127. /* Return the memory space pointed to - jumping over the
  128. BlockLink_t structure at its start. */
  129. pvReturn =
  130. (void*)(((uint8_t*)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize);
  131. /* This block is being returned for use so must be taken out
  132. of the list of free blocks. */
  133. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  134. /* If the block is larger than required it can be split into
  135. two. */
  136. if((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) {
  137. /* This block is to be split into two. Create a new
  138. block following the number of bytes requested. The void
  139. cast is used to prevent byte alignment warnings from the
  140. compiler. */
  141. pxNewBlockLink = (void*)(((uint8_t*)pxBlock) + xWantedSize);
  142. configASSERT((((size_t)pxNewBlockLink) & portBYTE_ALIGNMENT_MASK) == 0);
  143. /* Calculate the sizes of two blocks split from the
  144. single block. */
  145. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  146. pxBlock->xBlockSize = xWantedSize;
  147. /* Insert the new block into the list of free blocks. */
  148. prvInsertBlockIntoFreeList(pxNewBlockLink);
  149. } else {
  150. mtCOVERAGE_TEST_MARKER();
  151. }
  152. xFreeBytesRemaining -= pxBlock->xBlockSize;
  153. if(xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) {
  154. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  155. } else {
  156. mtCOVERAGE_TEST_MARKER();
  157. }
  158. /* The block is being returned - it is allocated and owned
  159. by the application and has no "next" block. */
  160. pxBlock->xBlockSize |= xBlockAllocatedBit;
  161. pxBlock->pxNextFreeBlock = NULL;
  162. } else {
  163. mtCOVERAGE_TEST_MARKER();
  164. }
  165. } else {
  166. mtCOVERAGE_TEST_MARKER();
  167. }
  168. } else {
  169. mtCOVERAGE_TEST_MARKER();
  170. }
  171. traceMALLOC(pvReturn, xWantedSize);
  172. }
  173. release_memalloc_mutex();
  174. #if(configUSE_MALLOC_FAILED_HOOK == 1)
  175. {
  176. if(pvReturn == NULL) {
  177. extern void vApplicationMallocFailedHook(void);
  178. vApplicationMallocFailedHook();
  179. } else {
  180. mtCOVERAGE_TEST_MARKER();
  181. }
  182. }
  183. #endif
  184. configASSERT((((size_t)pvReturn) & (size_t)portBYTE_ALIGNMENT_MASK) == 0);
  185. return pvReturn;
  186. }
  187. /*-----------------------------------------------------------*/
  188. void vPortFree(void* pv) {
  189. uint8_t* puc = (uint8_t*)pv;
  190. BlockLink_t* pxLink;
  191. if(pv != NULL) {
  192. /* The memory being freed will have an BlockLink_t structure immediately
  193. before it. */
  194. puc -= xHeapStructSize;
  195. /* This casting is to keep the compiler from issuing warnings. */
  196. pxLink = (void*)puc;
  197. /* Check the block is actually allocated. */
  198. configASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0);
  199. configASSERT(pxLink->pxNextFreeBlock == NULL);
  200. if((pxLink->xBlockSize & xBlockAllocatedBit) != 0) {
  201. if(pxLink->pxNextFreeBlock == NULL) {
  202. /* The block is being returned to the heap - it is no longer
  203. allocated. */
  204. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  205. acquire_memalloc_mutex();
  206. {
  207. /* Add this block to the list of free blocks. */
  208. xFreeBytesRemaining += pxLink->xBlockSize;
  209. traceFREE(pv, pxLink->xBlockSize);
  210. prvInsertBlockIntoFreeList(((BlockLink_t*)pxLink));
  211. }
  212. release_memalloc_mutex();
  213. } else {
  214. mtCOVERAGE_TEST_MARKER();
  215. }
  216. } else {
  217. mtCOVERAGE_TEST_MARKER();
  218. }
  219. }
  220. }
  221. /*-----------------------------------------------------------*/
  222. size_t xPortGetFreeHeapSize(void) {
  223. return xFreeBytesRemaining;
  224. }
  225. /*-----------------------------------------------------------*/
  226. size_t xPortGetMinimumEverFreeHeapSize(void) {
  227. return xMinimumEverFreeBytesRemaining;
  228. }
  229. /*-----------------------------------------------------------*/
  230. void vPortInitialiseBlocks(void) {
  231. /* This just exists to keep the linker quiet. */
  232. }
  233. /*-----------------------------------------------------------*/
  234. bool prvHeapInit(void) {
  235. BlockLink_t* pxFirstFreeBlock;
  236. uint8_t* pucAlignedHeap;
  237. size_t uxAddress;
  238. size_t xTotalHeapSize = configTOTAL_HEAP_SIZE;
  239. /* Ensure the heap starts on a correctly aligned boundary. */
  240. uxAddress = (size_t)ucHeap;
  241. if((uxAddress & portBYTE_ALIGNMENT_MASK) != 0) {
  242. uxAddress += (portBYTE_ALIGNMENT - 1);
  243. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  244. xTotalHeapSize -= uxAddress - (size_t)ucHeap;
  245. }
  246. pucAlignedHeap = (uint8_t*)uxAddress;
  247. /* xStart is used to hold a pointer to the first item in the list of free
  248. blocks. The void cast is used to prevent compiler warnings. */
  249. xStart.pxNextFreeBlock = (void*)pucAlignedHeap;
  250. xStart.xBlockSize = (size_t)0;
  251. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  252. at the end of the heap space. */
  253. uxAddress = ((size_t)pucAlignedHeap) + xTotalHeapSize;
  254. uxAddress -= xHeapStructSize;
  255. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  256. pxEnd = (void*)uxAddress;
  257. pxEnd->xBlockSize = 0;
  258. pxEnd->pxNextFreeBlock = NULL;
  259. /* To start with there is a single free block that is sized to take up the
  260. entire heap space, minus the space taken by pxEnd. */
  261. pxFirstFreeBlock = (void*)pucAlignedHeap;
  262. pxFirstFreeBlock->xBlockSize = uxAddress - (size_t)pxFirstFreeBlock;
  263. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  264. /* Only one block exists - and it covers the entire usable heap space. */
  265. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  266. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  267. /* Work out the position of the top bit in a size_t variable. */
  268. xBlockAllocatedBit = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1);
  269. // now we can use malloc, so we init heap managment mutex
  270. const osMutexAttr_t heap_managment_mutext_attr = {
  271. .name = NULL, .attr_bits = 0, .cb_mem = NULL, .cb_size = 0U};
  272. heap_managment_mutex = osMutexNew(&heap_managment_mutext_attr);
  273. return heap_managment_mutex != NULL;
  274. }
  275. /*-----------------------------------------------------------*/
  276. static void prvInsertBlockIntoFreeList(BlockLink_t* pxBlockToInsert) {
  277. BlockLink_t* pxIterator;
  278. uint8_t* puc;
  279. /* Iterate through the list until a block is found that has a higher address
  280. than the block being inserted. */
  281. for(pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert;
  282. pxIterator = pxIterator->pxNextFreeBlock) {
  283. /* Nothing to do here, just iterate to the right position. */
  284. }
  285. /* Do the block being inserted, and the block it is being inserted after
  286. make a contiguous block of memory? */
  287. puc = (uint8_t*)pxIterator;
  288. if((puc + pxIterator->xBlockSize) == (uint8_t*)pxBlockToInsert) {
  289. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  290. pxBlockToInsert = pxIterator;
  291. } else {
  292. mtCOVERAGE_TEST_MARKER();
  293. }
  294. /* Do the block being inserted, and the block it is being inserted before
  295. make a contiguous block of memory? */
  296. puc = (uint8_t*)pxBlockToInsert;
  297. if((puc + pxBlockToInsert->xBlockSize) == (uint8_t*)pxIterator->pxNextFreeBlock) {
  298. if(pxIterator->pxNextFreeBlock != pxEnd) {
  299. /* Form one big block from the two blocks. */
  300. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  301. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  302. } else {
  303. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  304. }
  305. } else {
  306. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  307. }
  308. /* If the block being inserted plugged a gab, so was merged with the block
  309. before and the block after, then it's pxNextFreeBlock pointer will have
  310. already been set, and should not be set here as that would make it point
  311. to itself. */
  312. if(pxIterator != pxBlockToInsert) {
  313. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  314. } else {
  315. mtCOVERAGE_TEST_MARKER();
  316. }
  317. }
  318. /*
  319. at first run (heap init) it not work properly and prvHeapInit
  320. is not thread-safe. But then we init mutex or die
  321. */
  322. void acquire_memalloc_mutex() {
  323. if(heap_managment_mutex != NULL) {
  324. osMutexAcquire(heap_managment_mutex, osWaitForever);
  325. }
  326. }
  327. void release_memalloc_mutex() {
  328. if(heap_managment_mutex != NULL) {
  329. osMutexRelease(heap_managment_mutex);
  330. }
  331. }