memmgr_heap.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 "memmgr_heap.h"
  36. #include "check.h"
  37. #include <stdlib.h>
  38. #include <cmsis_os2.h>
  39. #include <stm32wbxx.h>
  40. #include <furi_hal_console.h>
  41. #include <furi/common_defines.h>
  42. /* Defining MPU_WRAPPERS_INCLUDED_FROM_API_FILE prevents task.h from redefining
  43. all the API functions to use the MPU wrappers. That should only be done when
  44. task.h is included from an application file. */
  45. #define MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  46. #include "FreeRTOS.h"
  47. #include "task.h"
  48. #undef MPU_WRAPPERS_INCLUDED_FROM_API_FILE
  49. #if(configSUPPORT_DYNAMIC_ALLOCATION == 0)
  50. #error This file must not be used if configSUPPORT_DYNAMIC_ALLOCATION is 0
  51. #endif
  52. /* Block sizes must not get too small. */
  53. #define heapMINIMUM_BLOCK_SIZE ((size_t)(xHeapStructSize << 1))
  54. /* Assumes 8bit bytes! */
  55. #define heapBITS_PER_BYTE ((size_t)8)
  56. /* Heap start end symbols provided by linker */
  57. extern const void __heap_start__;
  58. extern const void __heap_end__;
  59. uint8_t* ucHeap = (uint8_t*)&__heap_start__;
  60. /* Define the linked list structure. This is used to link free blocks in order
  61. of their memory address. */
  62. typedef struct A_BLOCK_LINK {
  63. struct A_BLOCK_LINK* pxNextFreeBlock; /*<< The next free block in the list. */
  64. size_t xBlockSize; /*<< The size of the free block. */
  65. } BlockLink_t;
  66. /*-----------------------------------------------------------*/
  67. /*
  68. * Inserts a block of memory that is being freed into the correct position in
  69. * the list of free memory blocks. The block being freed will be merged with
  70. * the block in front it and/or the block behind it if the memory blocks are
  71. * adjacent to each other.
  72. */
  73. static void prvInsertBlockIntoFreeList(BlockLink_t* pxBlockToInsert);
  74. /*
  75. * Called automatically to setup the required heap structures the first time
  76. * pvPortMalloc() is called.
  77. */
  78. static void prvHeapInit(void);
  79. /*-----------------------------------------------------------*/
  80. /* The size of the structure placed at the beginning of each allocated memory
  81. block must by correctly byte aligned. */
  82. static const size_t xHeapStructSize = (sizeof(BlockLink_t) + ((size_t)(portBYTE_ALIGNMENT - 1))) &
  83. ~((size_t)portBYTE_ALIGNMENT_MASK);
  84. /* Create a couple of list links to mark the start and end of the list. */
  85. static BlockLink_t xStart, *pxEnd = NULL;
  86. /* Keeps track of the number of free bytes remaining, but says nothing about
  87. fragmentation. */
  88. static size_t xFreeBytesRemaining = 0U;
  89. static size_t xMinimumEverFreeBytesRemaining = 0U;
  90. /* Gets set to the top bit of an size_t type. When this bit in the xBlockSize
  91. member of an BlockLink_t structure is set then the block belongs to the
  92. application. When the bit is free the block is still part of the free heap
  93. space. */
  94. static size_t xBlockAllocatedBit = 0;
  95. /* Furi heap extension */
  96. #include <m-dict.h>
  97. /* Allocation tracking types */
  98. DICT_DEF2(MemmgrHeapAllocDict, uint32_t, uint32_t)
  99. DICT_DEF2(
  100. MemmgrHeapThreadDict,
  101. uint32_t,
  102. M_DEFAULT_OPLIST,
  103. MemmgrHeapAllocDict_t,
  104. DICT_OPLIST(MemmgrHeapAllocDict))
  105. /* Thread allocation tracing storage */
  106. static MemmgrHeapThreadDict_t memmgr_heap_thread_dict = {0};
  107. static volatile uint32_t memmgr_heap_thread_trace_depth = 0;
  108. /* Initialize tracing storage on start */
  109. void memmgr_heap_init() {
  110. MemmgrHeapThreadDict_init(memmgr_heap_thread_dict);
  111. }
  112. void memmgr_heap_enable_thread_trace(osThreadId_t thread_id) {
  113. vTaskSuspendAll();
  114. {
  115. memmgr_heap_thread_trace_depth++;
  116. furi_check(MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id) == NULL);
  117. MemmgrHeapAllocDict_t alloc_dict;
  118. MemmgrHeapAllocDict_init(alloc_dict);
  119. MemmgrHeapThreadDict_set_at(memmgr_heap_thread_dict, (uint32_t)thread_id, alloc_dict);
  120. MemmgrHeapAllocDict_clear(alloc_dict);
  121. memmgr_heap_thread_trace_depth--;
  122. }
  123. (void)xTaskResumeAll();
  124. }
  125. void memmgr_heap_disable_thread_trace(osThreadId_t thread_id) {
  126. vTaskSuspendAll();
  127. {
  128. memmgr_heap_thread_trace_depth++;
  129. furi_check(MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id) != NULL);
  130. MemmgrHeapThreadDict_erase(memmgr_heap_thread_dict, (uint32_t)thread_id);
  131. memmgr_heap_thread_trace_depth--;
  132. }
  133. (void)xTaskResumeAll();
  134. }
  135. size_t memmgr_heap_get_thread_memory(osThreadId_t thread_id) {
  136. size_t leftovers = MEMMGR_HEAP_UNKNOWN;
  137. vTaskSuspendAll();
  138. {
  139. memmgr_heap_thread_trace_depth++;
  140. MemmgrHeapAllocDict_t* alloc_dict =
  141. MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id);
  142. if(alloc_dict) {
  143. leftovers = 0;
  144. MemmgrHeapAllocDict_it_t alloc_dict_it;
  145. for(MemmgrHeapAllocDict_it(alloc_dict_it, *alloc_dict);
  146. !MemmgrHeapAllocDict_end_p(alloc_dict_it);
  147. MemmgrHeapAllocDict_next(alloc_dict_it)) {
  148. MemmgrHeapAllocDict_itref_t* data = MemmgrHeapAllocDict_ref(alloc_dict_it);
  149. if(data->key != 0) {
  150. uint8_t* puc = (uint8_t*)data->key;
  151. puc -= xHeapStructSize;
  152. BlockLink_t* pxLink = (void*)puc;
  153. if((pxLink->xBlockSize & xBlockAllocatedBit) != 0 &&
  154. pxLink->pxNextFreeBlock == NULL) {
  155. leftovers += data->value;
  156. }
  157. }
  158. }
  159. }
  160. memmgr_heap_thread_trace_depth--;
  161. }
  162. (void)xTaskResumeAll();
  163. return leftovers;
  164. }
  165. #undef traceMALLOC
  166. static inline void traceMALLOC(void* pointer, size_t size) {
  167. osThreadId_t thread_id = osThreadGetId();
  168. if(thread_id && memmgr_heap_thread_trace_depth == 0) {
  169. memmgr_heap_thread_trace_depth++;
  170. MemmgrHeapAllocDict_t* alloc_dict =
  171. MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id);
  172. if(alloc_dict) {
  173. MemmgrHeapAllocDict_set_at(*alloc_dict, (uint32_t)pointer, (uint32_t)size);
  174. }
  175. memmgr_heap_thread_trace_depth--;
  176. }
  177. }
  178. #undef traceFREE
  179. static inline void traceFREE(void* pointer, size_t size) {
  180. osThreadId_t thread_id = osThreadGetId();
  181. if(thread_id && memmgr_heap_thread_trace_depth == 0) {
  182. memmgr_heap_thread_trace_depth++;
  183. MemmgrHeapAllocDict_t* alloc_dict =
  184. MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id);
  185. if(alloc_dict) {
  186. MemmgrHeapAllocDict_erase(*alloc_dict, (uint32_t)pointer);
  187. }
  188. memmgr_heap_thread_trace_depth--;
  189. }
  190. }
  191. size_t memmgr_heap_get_max_free_block() {
  192. size_t max_free_size = 0;
  193. BlockLink_t* pxBlock;
  194. osKernelLock();
  195. pxBlock = xStart.pxNextFreeBlock;
  196. while(pxBlock->pxNextFreeBlock != NULL) {
  197. if(pxBlock->xBlockSize > max_free_size) {
  198. max_free_size = pxBlock->xBlockSize;
  199. }
  200. pxBlock = pxBlock->pxNextFreeBlock;
  201. }
  202. osKernelUnlock();
  203. return max_free_size;
  204. }
  205. void memmgr_heap_printf_free_blocks() {
  206. BlockLink_t* pxBlock;
  207. //TODO enable when we can do printf with a locked scheduler
  208. //osKernelLock();
  209. pxBlock = xStart.pxNextFreeBlock;
  210. while(pxBlock->pxNextFreeBlock != NULL) {
  211. printf("A %p S %lu\r\n", (void*)pxBlock, (uint32_t)pxBlock->xBlockSize);
  212. pxBlock = pxBlock->pxNextFreeBlock;
  213. }
  214. //osKernelUnlock();
  215. }
  216. #ifdef HEAP_PRINT_DEBUG
  217. char* ultoa(unsigned long num, char* str, int radix) {
  218. char temp[33]; // at radix 2 the string is at most 32 + 1 null long.
  219. int temp_loc = 0;
  220. int digit;
  221. int str_loc = 0;
  222. //construct a backward string of the number.
  223. do {
  224. digit = (unsigned long)num % ((unsigned long)radix);
  225. if(digit < 10)
  226. temp[temp_loc++] = digit + '0';
  227. else
  228. temp[temp_loc++] = digit - 10 + 'A';
  229. num = ((unsigned long)num) / ((unsigned long)radix);
  230. } while((unsigned long)num > 0);
  231. temp_loc--;
  232. //now reverse the string.
  233. while(temp_loc >= 0) { // while there are still chars
  234. str[str_loc++] = temp[temp_loc--];
  235. }
  236. str[str_loc] = 0; // add null termination.
  237. return str;
  238. }
  239. static void print_heap_init() {
  240. char tmp_str[33];
  241. size_t heap_start = (size_t)&__heap_start__;
  242. size_t heap_end = (size_t)&__heap_end__;
  243. // {PHStart|heap_start|heap_end}
  244. FURI_CRITICAL_ENTER();
  245. furi_hal_console_puts("{PHStart|");
  246. ultoa(heap_start, tmp_str, 16);
  247. furi_hal_console_puts(tmp_str);
  248. furi_hal_console_puts("|");
  249. ultoa(heap_end, tmp_str, 16);
  250. furi_hal_console_puts(tmp_str);
  251. furi_hal_console_puts("}\r\n");
  252. FURI_CRITICAL_EXIT();
  253. }
  254. static void print_heap_malloc(void* ptr, size_t size) {
  255. char tmp_str[33];
  256. const char* name = osThreadGetName(osThreadGetId());
  257. if(!name) {
  258. name = "";
  259. }
  260. // {thread name|m|address|size}
  261. FURI_CRITICAL_ENTER();
  262. furi_hal_console_puts("{");
  263. furi_hal_console_puts(name);
  264. furi_hal_console_puts("|m|0x");
  265. ultoa((unsigned long)ptr, tmp_str, 16);
  266. furi_hal_console_puts(tmp_str);
  267. furi_hal_console_puts("|");
  268. utoa(size, tmp_str, 10);
  269. furi_hal_console_puts(tmp_str);
  270. furi_hal_console_puts("}\r\n");
  271. FURI_CRITICAL_EXIT();
  272. }
  273. static void print_heap_free(void* ptr) {
  274. char tmp_str[33];
  275. const char* name = osThreadGetName(osThreadGetId());
  276. if(!name) {
  277. name = "";
  278. }
  279. // {thread name|f|address}
  280. FURI_CRITICAL_ENTER();
  281. furi_hal_console_puts("{");
  282. furi_hal_console_puts(name);
  283. furi_hal_console_puts("|f|0x");
  284. ultoa((unsigned long)ptr, tmp_str, 16);
  285. furi_hal_console_puts(tmp_str);
  286. furi_hal_console_puts("}\r\n");
  287. FURI_CRITICAL_EXIT();
  288. }
  289. #endif
  290. /*-----------------------------------------------------------*/
  291. void* pvPortMalloc(size_t xWantedSize) {
  292. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  293. void* pvReturn = NULL;
  294. size_t to_wipe = xWantedSize;
  295. #ifdef HEAP_PRINT_DEBUG
  296. BlockLink_t* print_heap_block = NULL;
  297. #endif
  298. /* If this is the first call to malloc then the heap will require
  299. initialisation to setup the list of free blocks. */
  300. if(pxEnd == NULL) {
  301. #ifdef HEAP_PRINT_DEBUG
  302. print_heap_init();
  303. #endif
  304. vTaskSuspendAll();
  305. {
  306. prvHeapInit();
  307. memmgr_heap_init();
  308. }
  309. (void)xTaskResumeAll();
  310. } else {
  311. mtCOVERAGE_TEST_MARKER();
  312. }
  313. vTaskSuspendAll();
  314. {
  315. /* Check the requested block size is not so large that the top bit is
  316. set. The top bit of the block size member of the BlockLink_t structure
  317. is used to determine who owns the block - the application or the
  318. kernel, so it must be free. */
  319. if((xWantedSize & xBlockAllocatedBit) == 0) {
  320. /* The wanted size is increased so it can contain a BlockLink_t
  321. structure in addition to the requested amount of bytes. */
  322. if(xWantedSize > 0) {
  323. xWantedSize += xHeapStructSize;
  324. /* Ensure that blocks are always aligned to the required number
  325. of bytes. */
  326. if((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) {
  327. /* Byte alignment required. */
  328. xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK));
  329. configASSERT((xWantedSize & portBYTE_ALIGNMENT_MASK) == 0);
  330. } else {
  331. mtCOVERAGE_TEST_MARKER();
  332. }
  333. } else {
  334. mtCOVERAGE_TEST_MARKER();
  335. }
  336. if((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) {
  337. /* Traverse the list from the start (lowest address) block until
  338. one of adequate size is found. */
  339. pxPreviousBlock = &xStart;
  340. pxBlock = xStart.pxNextFreeBlock;
  341. while((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) {
  342. pxPreviousBlock = pxBlock;
  343. pxBlock = pxBlock->pxNextFreeBlock;
  344. }
  345. /* If the end marker was reached then a block of adequate size
  346. was not found. */
  347. if(pxBlock != pxEnd) {
  348. /* Return the memory space pointed to - jumping over the
  349. BlockLink_t structure at its start. */
  350. pvReturn =
  351. (void*)(((uint8_t*)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize);
  352. /* This block is being returned for use so must be taken out
  353. of the list of free blocks. */
  354. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  355. /* If the block is larger than required it can be split into
  356. two. */
  357. if((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) {
  358. /* This block is to be split into two. Create a new
  359. block following the number of bytes requested. The void
  360. cast is used to prevent byte alignment warnings from the
  361. compiler. */
  362. pxNewBlockLink = (void*)(((uint8_t*)pxBlock) + xWantedSize);
  363. configASSERT((((size_t)pxNewBlockLink) & portBYTE_ALIGNMENT_MASK) == 0);
  364. /* Calculate the sizes of two blocks split from the
  365. single block. */
  366. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  367. pxBlock->xBlockSize = xWantedSize;
  368. /* Insert the new block into the list of free blocks. */
  369. prvInsertBlockIntoFreeList(pxNewBlockLink);
  370. } else {
  371. mtCOVERAGE_TEST_MARKER();
  372. }
  373. xFreeBytesRemaining -= pxBlock->xBlockSize;
  374. if(xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) {
  375. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  376. } else {
  377. mtCOVERAGE_TEST_MARKER();
  378. }
  379. /* The block is being returned - it is allocated and owned
  380. by the application and has no "next" block. */
  381. pxBlock->xBlockSize |= xBlockAllocatedBit;
  382. pxBlock->pxNextFreeBlock = NULL;
  383. #ifdef HEAP_PRINT_DEBUG
  384. print_heap_block = pxBlock;
  385. #endif
  386. } else {
  387. mtCOVERAGE_TEST_MARKER();
  388. }
  389. } else {
  390. mtCOVERAGE_TEST_MARKER();
  391. }
  392. } else {
  393. mtCOVERAGE_TEST_MARKER();
  394. }
  395. traceMALLOC(pvReturn, xWantedSize);
  396. }
  397. (void)xTaskResumeAll();
  398. #ifdef HEAP_PRINT_DEBUG
  399. print_heap_malloc(print_heap_block, print_heap_block->xBlockSize & ~xBlockAllocatedBit);
  400. #endif
  401. #if(configUSE_MALLOC_FAILED_HOOK == 1)
  402. {
  403. if(pvReturn == NULL) {
  404. extern void vApplicationMallocFailedHook(void);
  405. vApplicationMallocFailedHook();
  406. } else {
  407. mtCOVERAGE_TEST_MARKER();
  408. }
  409. }
  410. #endif
  411. configASSERT((((size_t)pvReturn) & (size_t)portBYTE_ALIGNMENT_MASK) == 0);
  412. furi_check(pvReturn);
  413. pvReturn = memset(pvReturn, 0, to_wipe);
  414. return pvReturn;
  415. }
  416. /*-----------------------------------------------------------*/
  417. void vPortFree(void* pv) {
  418. uint8_t* puc = (uint8_t*)pv;
  419. BlockLink_t* pxLink;
  420. if(pv != NULL) {
  421. /* The memory being freed will have an BlockLink_t structure immediately
  422. before it. */
  423. puc -= xHeapStructSize;
  424. /* This casting is to keep the compiler from issuing warnings. */
  425. pxLink = (void*)puc;
  426. /* Check the block is actually allocated. */
  427. configASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0);
  428. configASSERT(pxLink->pxNextFreeBlock == NULL);
  429. if((pxLink->xBlockSize & xBlockAllocatedBit) != 0) {
  430. if(pxLink->pxNextFreeBlock == NULL) {
  431. /* The block is being returned to the heap - it is no longer
  432. allocated. */
  433. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  434. #ifdef HEAP_PRINT_DEBUG
  435. print_heap_free(pxLink);
  436. #endif
  437. vTaskSuspendAll();
  438. {
  439. furi_assert((size_t)pv >= SRAM_BASE);
  440. furi_assert((size_t)pv < SRAM_BASE + 1024 * 256);
  441. furi_assert((pxLink->xBlockSize - xHeapStructSize) < 1024 * 256);
  442. furi_assert((int32_t)(pxLink->xBlockSize - xHeapStructSize) >= 0);
  443. /* Add this block to the list of free blocks. */
  444. xFreeBytesRemaining += pxLink->xBlockSize;
  445. traceFREE(pv, pxLink->xBlockSize);
  446. memset(pv, 0, pxLink->xBlockSize - xHeapStructSize);
  447. prvInsertBlockIntoFreeList(((BlockLink_t*)pxLink));
  448. }
  449. (void)xTaskResumeAll();
  450. } else {
  451. mtCOVERAGE_TEST_MARKER();
  452. }
  453. } else {
  454. mtCOVERAGE_TEST_MARKER();
  455. }
  456. } else {
  457. #ifdef HEAP_PRINT_DEBUG
  458. print_heap_free(pv);
  459. #endif
  460. }
  461. }
  462. /*-----------------------------------------------------------*/
  463. size_t xPortGetTotalHeapSize(void) {
  464. return (size_t)&__heap_end__ - (size_t)&__heap_start__;
  465. }
  466. /*-----------------------------------------------------------*/
  467. size_t xPortGetFreeHeapSize(void) {
  468. return xFreeBytesRemaining;
  469. }
  470. /*-----------------------------------------------------------*/
  471. size_t xPortGetMinimumEverFreeHeapSize(void) {
  472. return xMinimumEverFreeBytesRemaining;
  473. }
  474. /*-----------------------------------------------------------*/
  475. void vPortInitialiseBlocks(void) {
  476. /* This just exists to keep the linker quiet. */
  477. }
  478. /*-----------------------------------------------------------*/
  479. static void prvHeapInit(void) {
  480. BlockLink_t* pxFirstFreeBlock;
  481. uint8_t* pucAlignedHeap;
  482. size_t uxAddress;
  483. size_t xTotalHeapSize = (size_t)&__heap_end__ - (size_t)&__heap_start__;
  484. /* Ensure the heap starts on a correctly aligned boundary. */
  485. uxAddress = (size_t)ucHeap;
  486. if((uxAddress & portBYTE_ALIGNMENT_MASK) != 0) {
  487. uxAddress += (portBYTE_ALIGNMENT - 1);
  488. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  489. xTotalHeapSize -= uxAddress - (size_t)ucHeap;
  490. }
  491. pucAlignedHeap = (uint8_t*)uxAddress;
  492. /* xStart is used to hold a pointer to the first item in the list of free
  493. blocks. The void cast is used to prevent compiler warnings. */
  494. xStart.pxNextFreeBlock = (void*)pucAlignedHeap;
  495. xStart.xBlockSize = (size_t)0;
  496. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  497. at the end of the heap space. */
  498. uxAddress = ((size_t)pucAlignedHeap) + xTotalHeapSize;
  499. uxAddress -= xHeapStructSize;
  500. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  501. pxEnd = (void*)uxAddress;
  502. pxEnd->xBlockSize = 0;
  503. pxEnd->pxNextFreeBlock = NULL;
  504. /* To start with there is a single free block that is sized to take up the
  505. entire heap space, minus the space taken by pxEnd. */
  506. pxFirstFreeBlock = (void*)pucAlignedHeap;
  507. pxFirstFreeBlock->xBlockSize = uxAddress - (size_t)pxFirstFreeBlock;
  508. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  509. /* Only one block exists - and it covers the entire usable heap space. */
  510. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  511. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  512. /* Work out the position of the top bit in a size_t variable. */
  513. xBlockAllocatedBit = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1);
  514. }
  515. /*-----------------------------------------------------------*/
  516. static void prvInsertBlockIntoFreeList(BlockLink_t* pxBlockToInsert) {
  517. BlockLink_t* pxIterator;
  518. uint8_t* puc;
  519. /* Iterate through the list until a block is found that has a higher address
  520. than the block being inserted. */
  521. for(pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert;
  522. pxIterator = pxIterator->pxNextFreeBlock) {
  523. /* Nothing to do here, just iterate to the right position. */
  524. }
  525. /* Do the block being inserted, and the block it is being inserted after
  526. make a contiguous block of memory? */
  527. puc = (uint8_t*)pxIterator;
  528. if((puc + pxIterator->xBlockSize) == (uint8_t*)pxBlockToInsert) {
  529. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  530. pxBlockToInsert = pxIterator;
  531. } else {
  532. mtCOVERAGE_TEST_MARKER();
  533. }
  534. /* Do the block being inserted, and the block it is being inserted before
  535. make a contiguous block of memory? */
  536. puc = (uint8_t*)pxBlockToInsert;
  537. if((puc + pxBlockToInsert->xBlockSize) == (uint8_t*)pxIterator->pxNextFreeBlock) {
  538. if(pxIterator->pxNextFreeBlock != pxEnd) {
  539. /* Form one big block from the two blocks. */
  540. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  541. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  542. } else {
  543. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  544. }
  545. } else {
  546. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  547. }
  548. /* If the block being inserted plugged a gab, so was merged with the block
  549. before and the block after, then it's pxNextFreeBlock pointer will have
  550. already been set, and should not be set here as that would make it point
  551. to itself. */
  552. if(pxIterator != pxBlockToInsert) {
  553. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  554. } else {
  555. mtCOVERAGE_TEST_MARKER();
  556. }
  557. }