memmgr_heap.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650
  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 <stdio.h>
  39. #include <stm32wbxx.h>
  40. #include <furi_hal_console.h>
  41. #include <core/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(FuriThreadId 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(FuriThreadId thread_id) {
  126. vTaskSuspendAll();
  127. {
  128. memmgr_heap_thread_trace_depth++;
  129. furi_check(MemmgrHeapThreadDict_erase(memmgr_heap_thread_dict, (uint32_t)thread_id));
  130. memmgr_heap_thread_trace_depth--;
  131. }
  132. (void)xTaskResumeAll();
  133. }
  134. size_t memmgr_heap_get_thread_memory(FuriThreadId thread_id) {
  135. size_t leftovers = MEMMGR_HEAP_UNKNOWN;
  136. vTaskSuspendAll();
  137. {
  138. memmgr_heap_thread_trace_depth++;
  139. MemmgrHeapAllocDict_t* alloc_dict =
  140. MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id);
  141. if(alloc_dict) {
  142. leftovers = 0;
  143. MemmgrHeapAllocDict_it_t alloc_dict_it;
  144. for(MemmgrHeapAllocDict_it(alloc_dict_it, *alloc_dict);
  145. !MemmgrHeapAllocDict_end_p(alloc_dict_it);
  146. MemmgrHeapAllocDict_next(alloc_dict_it)) {
  147. MemmgrHeapAllocDict_itref_t* data = MemmgrHeapAllocDict_ref(alloc_dict_it);
  148. if(data->key != 0) {
  149. uint8_t* puc = (uint8_t*)data->key;
  150. puc -= xHeapStructSize;
  151. BlockLink_t* pxLink = (void*)puc;
  152. if((pxLink->xBlockSize & xBlockAllocatedBit) != 0 &&
  153. pxLink->pxNextFreeBlock == NULL) {
  154. leftovers += data->value;
  155. }
  156. }
  157. }
  158. }
  159. memmgr_heap_thread_trace_depth--;
  160. }
  161. (void)xTaskResumeAll();
  162. return leftovers;
  163. }
  164. #undef traceMALLOC
  165. static inline void traceMALLOC(void* pointer, size_t size) {
  166. FuriThreadId thread_id = furi_thread_get_current_id();
  167. if(thread_id && memmgr_heap_thread_trace_depth == 0) {
  168. memmgr_heap_thread_trace_depth++;
  169. MemmgrHeapAllocDict_t* alloc_dict =
  170. MemmgrHeapThreadDict_get(memmgr_heap_thread_dict, (uint32_t)thread_id);
  171. if(alloc_dict) {
  172. MemmgrHeapAllocDict_set_at(*alloc_dict, (uint32_t)pointer, (uint32_t)size);
  173. }
  174. memmgr_heap_thread_trace_depth--;
  175. }
  176. }
  177. #undef traceFREE
  178. static inline void traceFREE(void* pointer, size_t size) {
  179. UNUSED(size);
  180. FuriThreadId thread_id = furi_thread_get_current_id();
  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. // In some cases thread may want to release memory that was not allocated by it
  187. (void)MemmgrHeapAllocDict_erase(*alloc_dict, (uint32_t)pointer);
  188. }
  189. memmgr_heap_thread_trace_depth--;
  190. }
  191. }
  192. size_t memmgr_heap_get_max_free_block() {
  193. size_t max_free_size = 0;
  194. BlockLink_t* pxBlock;
  195. vTaskSuspendAll();
  196. pxBlock = xStart.pxNextFreeBlock;
  197. while(pxBlock->pxNextFreeBlock != NULL) {
  198. if(pxBlock->xBlockSize > max_free_size) {
  199. max_free_size = pxBlock->xBlockSize;
  200. }
  201. pxBlock = pxBlock->pxNextFreeBlock;
  202. }
  203. xTaskResumeAll();
  204. return max_free_size;
  205. }
  206. void memmgr_heap_printf_free_blocks() {
  207. BlockLink_t* pxBlock;
  208. //TODO enable when we can do printf with a locked scheduler
  209. //vTaskSuspendAll();
  210. pxBlock = xStart.pxNextFreeBlock;
  211. while(pxBlock->pxNextFreeBlock != NULL) {
  212. printf("A %p S %lu\r\n", (void*)pxBlock, (uint32_t)pxBlock->xBlockSize);
  213. pxBlock = pxBlock->pxNextFreeBlock;
  214. }
  215. //xTaskResumeAll();
  216. }
  217. #ifdef HEAP_PRINT_DEBUG
  218. char* ultoa(unsigned long num, char* str, int radix) {
  219. char temp[33]; // at radix 2 the string is at most 32 + 1 null long.
  220. int temp_loc = 0;
  221. int digit;
  222. int str_loc = 0;
  223. //construct a backward string of the number.
  224. do {
  225. digit = (unsigned long)num % ((unsigned long)radix);
  226. if(digit < 10)
  227. temp[temp_loc++] = digit + '0';
  228. else
  229. temp[temp_loc++] = digit - 10 + 'A';
  230. num = ((unsigned long)num) / ((unsigned long)radix);
  231. } while((unsigned long)num > 0);
  232. temp_loc--;
  233. //now reverse the string.
  234. while(temp_loc >= 0) { // while there are still chars
  235. str[str_loc++] = temp[temp_loc--];
  236. }
  237. str[str_loc] = 0; // add null termination.
  238. return str;
  239. }
  240. static void print_heap_init() {
  241. char tmp_str[33];
  242. size_t heap_start = (size_t)&__heap_start__;
  243. size_t heap_end = (size_t)&__heap_end__;
  244. // {PHStart|heap_start|heap_end}
  245. FURI_CRITICAL_ENTER();
  246. furi_hal_console_puts("{PHStart|");
  247. ultoa(heap_start, tmp_str, 16);
  248. furi_hal_console_puts(tmp_str);
  249. furi_hal_console_puts("|");
  250. ultoa(heap_end, tmp_str, 16);
  251. furi_hal_console_puts(tmp_str);
  252. furi_hal_console_puts("}\r\n");
  253. FURI_CRITICAL_EXIT();
  254. }
  255. static void print_heap_malloc(void* ptr, size_t size) {
  256. char tmp_str[33];
  257. const char* name = furi_thread_get_name(furi_thread_get_current_id());
  258. if(!name) {
  259. name = "";
  260. }
  261. // {thread name|m|address|size}
  262. FURI_CRITICAL_ENTER();
  263. furi_hal_console_puts("{");
  264. furi_hal_console_puts(name);
  265. furi_hal_console_puts("|m|0x");
  266. ultoa((unsigned long)ptr, tmp_str, 16);
  267. furi_hal_console_puts(tmp_str);
  268. furi_hal_console_puts("|");
  269. utoa(size, tmp_str, 10);
  270. furi_hal_console_puts(tmp_str);
  271. furi_hal_console_puts("}\r\n");
  272. FURI_CRITICAL_EXIT();
  273. }
  274. static void print_heap_free(void* ptr) {
  275. char tmp_str[33];
  276. const char* name = furi_thread_get_name(furi_thread_get_current_id());
  277. if(!name) {
  278. name = "";
  279. }
  280. // {thread name|f|address}
  281. FURI_CRITICAL_ENTER();
  282. furi_hal_console_puts("{");
  283. furi_hal_console_puts(name);
  284. furi_hal_console_puts("|f|0x");
  285. ultoa((unsigned long)ptr, tmp_str, 16);
  286. furi_hal_console_puts(tmp_str);
  287. furi_hal_console_puts("}\r\n");
  288. FURI_CRITICAL_EXIT();
  289. }
  290. #endif
  291. /*-----------------------------------------------------------*/
  292. void* pvPortMalloc(size_t xWantedSize) {
  293. BlockLink_t *pxBlock, *pxPreviousBlock, *pxNewBlockLink;
  294. void* pvReturn = NULL;
  295. size_t to_wipe = xWantedSize;
  296. #ifdef HEAP_PRINT_DEBUG
  297. BlockLink_t* print_heap_block = NULL;
  298. #endif
  299. /* If this is the first call to malloc then the heap will require
  300. initialisation to setup the list of free blocks. */
  301. if(pxEnd == NULL) {
  302. #ifdef HEAP_PRINT_DEBUG
  303. print_heap_init();
  304. #endif
  305. vTaskSuspendAll();
  306. {
  307. prvHeapInit();
  308. memmgr_heap_init();
  309. }
  310. (void)xTaskResumeAll();
  311. } else {
  312. mtCOVERAGE_TEST_MARKER();
  313. }
  314. vTaskSuspendAll();
  315. {
  316. /* Check the requested block size is not so large that the top bit is
  317. set. The top bit of the block size member of the BlockLink_t structure
  318. is used to determine who owns the block - the application or the
  319. kernel, so it must be free. */
  320. if((xWantedSize & xBlockAllocatedBit) == 0) {
  321. /* The wanted size is increased so it can contain a BlockLink_t
  322. structure in addition to the requested amount of bytes. */
  323. if(xWantedSize > 0) {
  324. xWantedSize += xHeapStructSize;
  325. /* Ensure that blocks are always aligned to the required number
  326. of bytes. */
  327. if((xWantedSize & portBYTE_ALIGNMENT_MASK) != 0x00) {
  328. /* Byte alignment required. */
  329. xWantedSize += (portBYTE_ALIGNMENT - (xWantedSize & portBYTE_ALIGNMENT_MASK));
  330. configASSERT((xWantedSize & portBYTE_ALIGNMENT_MASK) == 0);
  331. } else {
  332. mtCOVERAGE_TEST_MARKER();
  333. }
  334. } else {
  335. mtCOVERAGE_TEST_MARKER();
  336. }
  337. if((xWantedSize > 0) && (xWantedSize <= xFreeBytesRemaining)) {
  338. /* Traverse the list from the start (lowest address) block until
  339. one of adequate size is found. */
  340. pxPreviousBlock = &xStart;
  341. pxBlock = xStart.pxNextFreeBlock;
  342. while((pxBlock->xBlockSize < xWantedSize) && (pxBlock->pxNextFreeBlock != NULL)) {
  343. pxPreviousBlock = pxBlock;
  344. pxBlock = pxBlock->pxNextFreeBlock;
  345. }
  346. /* If the end marker was reached then a block of adequate size
  347. was not found. */
  348. if(pxBlock != pxEnd) {
  349. /* Return the memory space pointed to - jumping over the
  350. BlockLink_t structure at its start. */
  351. pvReturn =
  352. (void*)(((uint8_t*)pxPreviousBlock->pxNextFreeBlock) + xHeapStructSize);
  353. /* This block is being returned for use so must be taken out
  354. of the list of free blocks. */
  355. pxPreviousBlock->pxNextFreeBlock = pxBlock->pxNextFreeBlock;
  356. /* If the block is larger than required it can be split into
  357. two. */
  358. if((pxBlock->xBlockSize - xWantedSize) > heapMINIMUM_BLOCK_SIZE) {
  359. /* This block is to be split into two. Create a new
  360. block following the number of bytes requested. The void
  361. cast is used to prevent byte alignment warnings from the
  362. compiler. */
  363. pxNewBlockLink = (void*)(((uint8_t*)pxBlock) + xWantedSize);
  364. configASSERT((((size_t)pxNewBlockLink) & portBYTE_ALIGNMENT_MASK) == 0);
  365. /* Calculate the sizes of two blocks split from the
  366. single block. */
  367. pxNewBlockLink->xBlockSize = pxBlock->xBlockSize - xWantedSize;
  368. pxBlock->xBlockSize = xWantedSize;
  369. /* Insert the new block into the list of free blocks. */
  370. prvInsertBlockIntoFreeList(pxNewBlockLink);
  371. } else {
  372. mtCOVERAGE_TEST_MARKER();
  373. }
  374. xFreeBytesRemaining -= pxBlock->xBlockSize;
  375. if(xFreeBytesRemaining < xMinimumEverFreeBytesRemaining) {
  376. xMinimumEverFreeBytesRemaining = xFreeBytesRemaining;
  377. } else {
  378. mtCOVERAGE_TEST_MARKER();
  379. }
  380. /* The block is being returned - it is allocated and owned
  381. by the application and has no "next" block. */
  382. pxBlock->xBlockSize |= xBlockAllocatedBit;
  383. pxBlock->pxNextFreeBlock = NULL;
  384. #ifdef HEAP_PRINT_DEBUG
  385. print_heap_block = pxBlock;
  386. #endif
  387. } else {
  388. mtCOVERAGE_TEST_MARKER();
  389. }
  390. } else {
  391. mtCOVERAGE_TEST_MARKER();
  392. }
  393. } else {
  394. mtCOVERAGE_TEST_MARKER();
  395. }
  396. traceMALLOC(pvReturn, xWantedSize);
  397. }
  398. (void)xTaskResumeAll();
  399. #ifdef HEAP_PRINT_DEBUG
  400. print_heap_malloc(print_heap_block, print_heap_block->xBlockSize & ~xBlockAllocatedBit);
  401. #endif
  402. #if(configUSE_MALLOC_FAILED_HOOK == 1)
  403. {
  404. if(pvReturn == NULL) {
  405. extern void vApplicationMallocFailedHook(void);
  406. vApplicationMallocFailedHook();
  407. } else {
  408. mtCOVERAGE_TEST_MARKER();
  409. }
  410. }
  411. #endif
  412. configASSERT((((size_t)pvReturn) & (size_t)portBYTE_ALIGNMENT_MASK) == 0);
  413. furi_check(pvReturn);
  414. pvReturn = memset(pvReturn, 0, to_wipe);
  415. return pvReturn;
  416. }
  417. /*-----------------------------------------------------------*/
  418. void vPortFree(void* pv) {
  419. uint8_t* puc = (uint8_t*)pv;
  420. BlockLink_t* pxLink;
  421. if(pv != NULL) {
  422. /* The memory being freed will have an BlockLink_t structure immediately
  423. before it. */
  424. puc -= xHeapStructSize;
  425. /* This casting is to keep the compiler from issuing warnings. */
  426. pxLink = (void*)puc;
  427. /* Check the block is actually allocated. */
  428. configASSERT((pxLink->xBlockSize & xBlockAllocatedBit) != 0);
  429. configASSERT(pxLink->pxNextFreeBlock == NULL);
  430. if((pxLink->xBlockSize & xBlockAllocatedBit) != 0) {
  431. if(pxLink->pxNextFreeBlock == NULL) {
  432. /* The block is being returned to the heap - it is no longer
  433. allocated. */
  434. pxLink->xBlockSize &= ~xBlockAllocatedBit;
  435. #ifdef HEAP_PRINT_DEBUG
  436. print_heap_free(pxLink);
  437. #endif
  438. vTaskSuspendAll();
  439. {
  440. furi_assert((size_t)pv >= SRAM_BASE);
  441. furi_assert((size_t)pv < SRAM_BASE + 1024 * 256);
  442. furi_assert((pxLink->xBlockSize - xHeapStructSize) < 1024 * 256);
  443. furi_assert((int32_t)(pxLink->xBlockSize - xHeapStructSize) >= 0);
  444. /* Add this block to the list of free blocks. */
  445. xFreeBytesRemaining += pxLink->xBlockSize;
  446. traceFREE(pv, pxLink->xBlockSize);
  447. memset(pv, 0, pxLink->xBlockSize - xHeapStructSize);
  448. prvInsertBlockIntoFreeList(((BlockLink_t*)pxLink));
  449. }
  450. (void)xTaskResumeAll();
  451. } else {
  452. mtCOVERAGE_TEST_MARKER();
  453. }
  454. } else {
  455. mtCOVERAGE_TEST_MARKER();
  456. }
  457. } else {
  458. #ifdef HEAP_PRINT_DEBUG
  459. print_heap_free(pv);
  460. #endif
  461. }
  462. }
  463. /*-----------------------------------------------------------*/
  464. size_t xPortGetTotalHeapSize(void) {
  465. return (size_t)&__heap_end__ - (size_t)&__heap_start__;
  466. }
  467. /*-----------------------------------------------------------*/
  468. size_t xPortGetFreeHeapSize(void) {
  469. return xFreeBytesRemaining;
  470. }
  471. /*-----------------------------------------------------------*/
  472. size_t xPortGetMinimumEverFreeHeapSize(void) {
  473. return xMinimumEverFreeBytesRemaining;
  474. }
  475. /*-----------------------------------------------------------*/
  476. void vPortInitialiseBlocks(void) {
  477. /* This just exists to keep the linker quiet. */
  478. }
  479. /*-----------------------------------------------------------*/
  480. static void prvHeapInit(void) {
  481. BlockLink_t* pxFirstFreeBlock;
  482. uint8_t* pucAlignedHeap;
  483. size_t uxAddress;
  484. size_t xTotalHeapSize = (size_t)&__heap_end__ - (size_t)&__heap_start__;
  485. /* Ensure the heap starts on a correctly aligned boundary. */
  486. uxAddress = (size_t)ucHeap;
  487. if((uxAddress & portBYTE_ALIGNMENT_MASK) != 0) {
  488. uxAddress += (portBYTE_ALIGNMENT - 1);
  489. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  490. xTotalHeapSize -= uxAddress - (size_t)ucHeap;
  491. }
  492. pucAlignedHeap = (uint8_t*)uxAddress;
  493. /* xStart is used to hold a pointer to the first item in the list of free
  494. blocks. The void cast is used to prevent compiler warnings. */
  495. xStart.pxNextFreeBlock = (void*)pucAlignedHeap;
  496. xStart.xBlockSize = (size_t)0;
  497. /* pxEnd is used to mark the end of the list of free blocks and is inserted
  498. at the end of the heap space. */
  499. uxAddress = ((size_t)pucAlignedHeap) + xTotalHeapSize;
  500. uxAddress -= xHeapStructSize;
  501. uxAddress &= ~((size_t)portBYTE_ALIGNMENT_MASK);
  502. pxEnd = (void*)uxAddress;
  503. pxEnd->xBlockSize = 0;
  504. pxEnd->pxNextFreeBlock = NULL;
  505. /* To start with there is a single free block that is sized to take up the
  506. entire heap space, minus the space taken by pxEnd. */
  507. pxFirstFreeBlock = (void*)pucAlignedHeap;
  508. pxFirstFreeBlock->xBlockSize = uxAddress - (size_t)pxFirstFreeBlock;
  509. pxFirstFreeBlock->pxNextFreeBlock = pxEnd;
  510. /* Only one block exists - and it covers the entire usable heap space. */
  511. xMinimumEverFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  512. xFreeBytesRemaining = pxFirstFreeBlock->xBlockSize;
  513. /* Work out the position of the top bit in a size_t variable. */
  514. xBlockAllocatedBit = ((size_t)1) << ((sizeof(size_t) * heapBITS_PER_BYTE) - 1);
  515. }
  516. /*-----------------------------------------------------------*/
  517. static void prvInsertBlockIntoFreeList(BlockLink_t* pxBlockToInsert) {
  518. BlockLink_t* pxIterator;
  519. uint8_t* puc;
  520. /* Iterate through the list until a block is found that has a higher address
  521. than the block being inserted. */
  522. for(pxIterator = &xStart; pxIterator->pxNextFreeBlock < pxBlockToInsert;
  523. pxIterator = pxIterator->pxNextFreeBlock) {
  524. /* Nothing to do here, just iterate to the right position. */
  525. }
  526. /* Do the block being inserted, and the block it is being inserted after
  527. make a contiguous block of memory? */
  528. puc = (uint8_t*)pxIterator;
  529. if((puc + pxIterator->xBlockSize) == (uint8_t*)pxBlockToInsert) {
  530. pxIterator->xBlockSize += pxBlockToInsert->xBlockSize;
  531. pxBlockToInsert = pxIterator;
  532. } else {
  533. mtCOVERAGE_TEST_MARKER();
  534. }
  535. /* Do the block being inserted, and the block it is being inserted before
  536. make a contiguous block of memory? */
  537. puc = (uint8_t*)pxBlockToInsert;
  538. if((puc + pxBlockToInsert->xBlockSize) == (uint8_t*)pxIterator->pxNextFreeBlock) {
  539. if(pxIterator->pxNextFreeBlock != pxEnd) {
  540. /* Form one big block from the two blocks. */
  541. pxBlockToInsert->xBlockSize += pxIterator->pxNextFreeBlock->xBlockSize;
  542. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock->pxNextFreeBlock;
  543. } else {
  544. pxBlockToInsert->pxNextFreeBlock = pxEnd;
  545. }
  546. } else {
  547. pxBlockToInsert->pxNextFreeBlock = pxIterator->pxNextFreeBlock;
  548. }
  549. /* If the block being inserted plugged a gab, so was merged with the block
  550. before and the block after, then it's pxNextFreeBlock pointer will have
  551. already been set, and should not be set here as that would make it point
  552. to itself. */
  553. if(pxIterator != pxBlockToInsert) {
  554. pxIterator->pxNextFreeBlock = pxBlockToInsert;
  555. } else {
  556. mtCOVERAGE_TEST_MARKER();
  557. }
  558. }