psram.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426
  1. #include "ClassLogFile.h"
  2. #include "../../include/defines.h"
  3. #include "psram.h"
  4. #include <cstring>
  5. #include <stdint.h>
  6. #include <stdio.h>
  7. #include <limits.h>
  8. #include "freertos/FreeRTOS.h"
  9. #include "freertos/portmacro.h"
  10. static const char* TAG = "PSRAM";
  11. namespace {
  12. enum class SharedMemoryUser : uint8_t { None, TakeImage, Aligning, Digitization };
  13. static const uint32_t STBI_SHARED_BLOCK_MAGIC = 0x53544249;
  14. static const size_t STBI_ALIGNMENT = 16;
  15. struct alignas(16) StbiSharedBlockHeader {
  16. size_t size;
  17. uint32_t magic;
  18. uint8_t reserved[STBI_ALIGNMENT - sizeof(size_t) - sizeof(uint32_t)];
  19. };
  20. static_assert(sizeof(StbiSharedBlockHeader) == STBI_ALIGNMENT, "STBI shared allocation header must preserve alignment");
  21. static portMUX_TYPE sharedMemoryMux = portMUX_INITIALIZER_UNLOCKED;
  22. static uint8_t* sharedRegion = nullptr;
  23. static uint8_t* sharedRegionAllocation = nullptr;
  24. static size_t allocatedBytesForSTBI = 0;
  25. static SharedMemoryUser sharedMemoryUser = SharedMemoryUser::None;
  26. static bool tensorArenaClaimed = false;
  27. static bool modelMemoryClaimed = false;
  28. static bool getAlignedTensorArenaSize(size_t* size) {
  29. if (size == nullptr) return false;
  30. const size_t arenaSize = static_cast<size_t>(TENSOR_ARENA_SIZE);
  31. if (arenaSize == 0 || arenaSize > SIZE_MAX - (STBI_ALIGNMENT - 1)) return false;
  32. *size = (arenaSize + STBI_ALIGNMENT - 1) & ~(STBI_ALIGNMENT - 1);
  33. return true;
  34. }
  35. static bool getSharedRegionSize(size_t* size) {
  36. if (size == nullptr) return false;
  37. size_t arenaSize = 0;
  38. if (!getAlignedTensorArenaSize(&arenaSize)) return false;
  39. const size_t modelSize = static_cast<size_t>(MAX_MODEL_SIZE);
  40. if (modelSize == 0 || arenaSize > SIZE_MAX - modelSize) return false;
  41. *size = arenaSize + modelSize;
  42. return true;
  43. }
  44. static const char* sharedMemoryUserName(SharedMemoryUser user) {
  45. switch (user) {
  46. case SharedMemoryUser::TakeImage: return "TakeImage";
  47. case SharedMemoryUser::Aligning: return "Aligning";
  48. case SharedMemoryUser::Digitization: return "Digitization";
  49. default: return "";
  50. }
  51. }
  52. static bool isInsideSharedRegionLocked(const void* ptr, size_t regionSize) {
  53. if (ptr == nullptr || sharedRegion == nullptr) return false;
  54. if (sharedRegionAllocation == nullptr) return false;
  55. const uintptr_t allocationBegin = reinterpret_cast<uintptr_t>(sharedRegionAllocation);
  56. const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
  57. const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
  58. if (begin < allocationBegin || begin - allocationBegin >= STBI_ALIGNMENT) return false;
  59. return address >= begin && (address - begin) < regionSize;
  60. }
  61. static bool alignStbiOffset(size_t value, size_t* aligned) {
  62. if (aligned == nullptr || value > SIZE_MAX - (STBI_ALIGNMENT - 1)) return false;
  63. *aligned = (value + STBI_ALIGNMENT - 1) & ~(STBI_ALIGNMENT - 1);
  64. return true;
  65. }
  66. } // namespace
  67. bool reserve_psram_shared_region(void) {
  68. size_t regionSize = 0;
  69. if (!getSharedRegionSize(&regionSize)) {
  70. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid shared PSRAM region size");
  71. return false;
  72. }
  73. portENTER_CRITICAL(&sharedMemoryMux);
  74. const bool alreadyReserved = (sharedRegion != nullptr);
  75. portEXIT_CRITICAL(&sharedMemoryMux);
  76. if (alreadyReserved) return true;
  77. if (regionSize > SIZE_MAX - (STBI_ALIGNMENT - 1)) {
  78. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared PSRAM region size overflows alignment padding");
  79. return false;
  80. }
  81. const size_t allocationSize = regionSize + STBI_ALIGNMENT - 1;
  82. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating shared PSRAM region (" + std::to_string(regionSize) + " usable bytes)...");
  83. uint8_t* candidateAllocation = static_cast<uint8_t*>(malloc_psram_heap(
  84. "Shared PSRAM region", allocationSize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT));
  85. if (candidateAllocation == nullptr) {
  86. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate shared PSRAM region!");
  87. return false;
  88. }
  89. const uintptr_t rawAddress = reinterpret_cast<uintptr_t>(candidateAllocation);
  90. if (rawAddress > UINTPTR_MAX - (STBI_ALIGNMENT - 1)) {
  91. free_psram_heap("Invalid shared PSRAM region", candidateAllocation);
  92. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared PSRAM region address overflows alignment");
  93. return false;
  94. }
  95. const uintptr_t alignedAddress = (rawAddress + STBI_ALIGNMENT - 1) &
  96. ~static_cast<uintptr_t>(STBI_ALIGNMENT - 1);
  97. uint8_t* candidate = reinterpret_cast<uint8_t*>(alignedAddress);
  98. portENTER_CRITICAL(&sharedMemoryMux);
  99. if (sharedRegion == nullptr) {
  100. sharedRegion = candidate;
  101. sharedRegionAllocation = candidateAllocation;
  102. candidateAllocation = nullptr;
  103. }
  104. portEXIT_CRITICAL(&sharedMemoryMux);
  105. if (candidateAllocation != nullptr) {
  106. free_psram_heap("Unused duplicate shared PSRAM region", candidateAllocation);
  107. }
  108. return true;
  109. }
  110. /*******************************************************************
  111. * Memory used in Take Image (STBI)
  112. *******************************************************************/
  113. bool psram_init_shared_memory_for_take_image_step(void) {
  114. SharedMemoryUser currentUser;
  115. bool success = false;
  116. portENTER_CRITICAL(&sharedMemoryMux);
  117. currentUser = sharedMemoryUser;
  118. if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
  119. allocatedBytesForSTBI = 0;
  120. sharedMemoryUser = SharedMemoryUser::TakeImage;
  121. success = true;
  122. }
  123. portEXIT_CRITICAL(&sharedMemoryMux);
  124. if (!success) {
  125. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, sharedRegion == nullptr ?
  126. "Shared PSRAM region is not initialized" :
  127. "Shared memory in PSRAM already in use for " + std::string(sharedMemoryUserName(currentUser)) + "!");
  128. return false;
  129. }
  130. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Init shared memory for step 'Take Image' (STBI buffers)");
  131. return true;
  132. }
  133. void psram_deinit_shared_memory_for_take_image_step(void) {
  134. bool released = false;
  135. portENTER_CRITICAL(&sharedMemoryMux);
  136. if (sharedMemoryUser == SharedMemoryUser::TakeImage) {
  137. allocatedBytesForSTBI = 0;
  138. sharedMemoryUser = SharedMemoryUser::None;
  139. released = true;
  140. }
  141. portEXIT_CRITICAL(&sharedMemoryMux);
  142. if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Deinit shared memory for step 'Take Image' (STBI buffers)");
  143. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched STBI shared-memory release");
  144. }
  145. void *psram_reserve_shared_stbi_memory(size_t size) {
  146. if (size == 0) return nullptr;
  147. if (size < 100000) return malloc_psram_heap("STBI", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  148. size_t regionSize = 0;
  149. if (!getSharedRegionSize(&regionSize)) {
  150. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared PSRAM region is unavailable; allocating STBI buffer from PSRAM heap");
  151. return malloc_psram_heap("STBI fallback", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  152. }
  153. size_t userOffset = 0, endOffset = 0, available = 0;
  154. void* result = nullptr;
  155. SharedMemoryUser currentUser = SharedMemoryUser::None;
  156. portENTER_CRITICAL(&sharedMemoryMux);
  157. currentUser = sharedMemoryUser;
  158. if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::TakeImage &&
  159. allocatedBytesForSTBI <= SIZE_MAX - sizeof(StbiSharedBlockHeader) &&
  160. alignStbiOffset(allocatedBytesForSTBI + sizeof(StbiSharedBlockHeader), &userOffset) &&
  161. userOffset <= regionSize && size <= regionSize - userOffset) {
  162. endOffset = userOffset + size;
  163. StbiSharedBlockHeader* header = reinterpret_cast<StbiSharedBlockHeader*>(sharedRegion + userOffset - sizeof(StbiSharedBlockHeader));
  164. header->size = size;
  165. header->magic = STBI_SHARED_BLOCK_MAGIC;
  166. std::memset(header->reserved, 0, sizeof(header->reserved));
  167. result = sharedRegion + userOffset;
  168. allocatedBytesForSTBI = endOffset;
  169. } else if (allocatedBytesForSTBI <= regionSize) available = regionSize - allocatedBytesForSTBI;
  170. portEXIT_CRITICAL(&sharedMemoryMux);
  171. if (result != nullptr) {
  172. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in shared PSRAM for STBI");
  173. return result;
  174. }
  175. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared STBI PSRAM unavailable for " + std::to_string(size) +
  176. " bytes (owner: " + sharedMemoryUserName(currentUser) + ", available: " + std::to_string(available) +
  177. " bytes); falling back to PSRAM heap");
  178. return malloc_psram_heap("STBI fallback", size, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  179. }
  180. void *psram_reallocate_shared_stbi_memory(void *ptr, size_t newsize) {
  181. if (ptr == nullptr) return psram_reserve_shared_stbi_memory(newsize);
  182. if (newsize == 0) { psram_free_shared_stbi_memory(ptr); return nullptr; }
  183. size_t regionSize = 0;
  184. if (!getSharedRegionSize(&regionSize))
  185. return realloc_psram_heap("STBI", ptr, newsize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  186. size_t oldSize = 0;
  187. bool sharedPointer = false, validSharedHeader = false;
  188. portENTER_CRITICAL(&sharedMemoryMux);
  189. sharedPointer = isInsideSharedRegionLocked(ptr, regionSize);
  190. if (sharedPointer) {
  191. const uintptr_t begin = reinterpret_cast<uintptr_t>(sharedRegion);
  192. const uintptr_t address = reinterpret_cast<uintptr_t>(ptr);
  193. const size_t userOffset = static_cast<size_t>(address - begin);
  194. if (userOffset >= sizeof(StbiSharedBlockHeader) &&
  195. (userOffset & (STBI_ALIGNMENT - 1)) == 0) {
  196. const StbiSharedBlockHeader* header = reinterpret_cast<const StbiSharedBlockHeader*>(
  197. static_cast<const uint8_t*>(ptr) - sizeof(StbiSharedBlockHeader));
  198. if (header->magic == STBI_SHARED_BLOCK_MAGIC &&
  199. header->size > 0 && header->size <= regionSize - userOffset) {
  200. oldSize = header->size;
  201. validSharedHeader = true;
  202. }
  203. }
  204. }
  205. portEXIT_CRITICAL(&sharedMemoryMux);
  206. if (!sharedPointer) return realloc_psram_heap("STBI", ptr, newsize, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  207. if (!validSharedHeader) {
  208. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "STBI realloc received an unknown shared-region pointer");
  209. return nullptr;
  210. }
  211. void* replacement = psram_reserve_shared_stbi_memory(newsize);
  212. if (replacement == nullptr) return nullptr;
  213. std::memcpy(replacement, ptr, oldSize < newsize ? oldSize : newsize);
  214. return replacement;
  215. }
  216. void psram_free_shared_stbi_memory(void *ptr) {
  217. if (ptr == nullptr) return;
  218. size_t regionSize = 0;
  219. if (!getSharedRegionSize(&regionSize)) { free_psram_heap("STBI", ptr); return; }
  220. portENTER_CRITICAL(&sharedMemoryMux);
  221. const bool isShared = isInsideSharedRegionLocked(ptr, regionSize);
  222. portEXIT_CRITICAL(&sharedMemoryMux);
  223. if (!isShared) free_psram_heap("STBI", ptr);
  224. }
  225. /*******************************************************************
  226. * Memory used in Aligning Step
  227. *******************************************************************/
  228. void *psram_reserve_shared_tmp_image_memory(void) {
  229. size_t regionSize = 0;
  230. if (!getSharedRegionSize(&regionSize) || static_cast<size_t>(IMAGE_SIZE) > regionSize) {
  231. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region");
  232. return nullptr;
  233. }
  234. SharedMemoryUser currentUser;
  235. void* result = nullptr;
  236. portENTER_CRITICAL(&sharedMemoryMux);
  237. currentUser = sharedMemoryUser;
  238. if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
  239. sharedMemoryUser = SharedMemoryUser::Aligning;
  240. result = sharedRegion;
  241. }
  242. portEXIT_CRITICAL(&sharedMemoryMux);
  243. if (result == nullptr) {
  244. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Shared memory in PSRAM unavailable for tmpImage (owner: " +
  245. std::string(sharedMemoryUserName(currentUser)) + ")");
  246. return nullptr;
  247. }
  248. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(IMAGE_SIZE) + " bytes, use shared memory in PSRAM)...");
  249. return result;
  250. }
  251. void psram_free_shared_temp_image_memory(void) {
  252. bool released = false;
  253. portENTER_CRITICAL(&sharedMemoryMux);
  254. if (sharedMemoryUser == SharedMemoryUser::Aligning) { sharedMemoryUser = SharedMemoryUser::None; released = true; }
  255. portEXIT_CRITICAL(&sharedMemoryMux);
  256. if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage is free again");
  257. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched tmpImage shared-memory release");
  258. }
  259. /*******************************************************************
  260. * Memory used in Digitization Steps
  261. *******************************************************************/
  262. void *psram_get_shared_tensor_arena_memory(void) {
  263. bool unavailable = false, duplicateClaim = false;
  264. void* result = nullptr;
  265. SharedMemoryUser currentUser;
  266. portENTER_CRITICAL(&sharedMemoryMux);
  267. currentUser = sharedMemoryUser;
  268. if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
  269. else if (tensorArenaClaimed) duplicateClaim = true;
  270. else { sharedMemoryUser = SharedMemoryUser::Digitization; tensorArenaClaimed = true; result = sharedRegion; }
  271. portEXIT_CRITICAL(&sharedMemoryMux);
  272. if (result == nullptr) {
  273. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Tensor Arena shared memory was claimed more than once" :
  274. (unavailable ? "Shared PSRAM is unavailable for Tensor Arena (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Tensor Arena allocation failed"));
  275. return nullptr;
  276. }
  277. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes in shared PSRAM)...");
  278. return result;
  279. }
  280. void *psram_get_shared_model_memory(void) {
  281. bool unavailable = false, duplicateClaim = false;
  282. void* result = nullptr;
  283. size_t modelOffset = 0;
  284. if (!getAlignedTensorArenaSize(&modelOffset)) {
  285. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid Tensor Arena size for model placement");
  286. return nullptr;
  287. }
  288. SharedMemoryUser currentUser;
  289. portENTER_CRITICAL(&sharedMemoryMux);
  290. currentUser = sharedMemoryUser;
  291. if (sharedRegion == nullptr || !tensorArenaClaimed ||
  292. sharedMemoryUser != SharedMemoryUser::Digitization) unavailable = true;
  293. else if (modelMemoryClaimed) duplicateClaim = true;
  294. else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + modelOffset; }
  295. portEXIT_CRITICAL(&sharedMemoryMux);
  296. if (result == nullptr) {
  297. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Model shared memory was claimed more than once" :
  298. (unavailable ? "Shared PSRAM is unavailable for Model (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Model allocation failed"));
  299. return nullptr;
  300. }
  301. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes in shared PSRAM)...");
  302. return result;
  303. }
  304. void psram_free_shared_tensor_arena_and_model_memory(void) {
  305. bool released = false;
  306. portENTER_CRITICAL(&sharedMemoryMux);
  307. if (sharedMemoryUser == SharedMemoryUser::Digitization) {
  308. tensorArenaClaimed = false; modelMemoryClaimed = false;
  309. sharedMemoryUser = SharedMemoryUser::None; released = true;
  310. }
  311. portEXIT_CRITICAL(&sharedMemoryMux);
  312. if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model is free again");
  313. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched Tensor Arena/Model shared-memory release");
  314. }
  315. /*******************************************************************
  316. * General PSRAM heap wrappers
  317. *******************************************************************/
  318. void *malloc_psram_heap(std::string name, size_t size, uint32_t caps) {
  319. if (size == 0) {
  320. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM allocation for '" + name + "'");
  321. return nullptr;
  322. }
  323. void* ptr = heap_caps_malloc(size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  324. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
  325. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
  326. return ptr;
  327. }
  328. void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
  329. void* resized = heap_caps_realloc(ptr, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  330. if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
  331. else if (size != 0) LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
  332. return resized;
  333. }
  334. void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps) {
  335. if (size != 0 && n > SIZE_MAX / size) {
  336. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM calloc size overflow for '" + name + "'");
  337. return nullptr;
  338. }
  339. const size_t totalSize = n * size;
  340. if (totalSize == 0) {
  341. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM calloc for '" + name + "'");
  342. return nullptr;
  343. }
  344. void* ptr = heap_caps_calloc(n, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  345. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'");
  346. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'!");
  347. return ptr;
  348. }
  349. void free_psram_heap(std::string name, void *ptr) {
  350. if (ptr == nullptr) return;
  351. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
  352. heap_caps_free(ptr);
  353. }
  354. /*******************************************************************
  355. * Internal SRAM heap wrappers
  356. *******************************************************************/
  357. void *malloc_internal_heap(std::string name, size_t size, uint32_t caps) {
  358. if (size == 0) {
  359. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal allocation for '" + name + "'");
  360. return nullptr;
  361. }
  362. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  363. void* ptr = heap_caps_malloc(size, internalCaps);
  364. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  365. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  366. return ptr;
  367. }
  368. void *realloc_internal_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
  369. if (size == 0) {
  370. if (ptr != nullptr) {
  371. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
  372. heap_caps_free(ptr);
  373. }
  374. return nullptr;
  375. }
  376. if (ptr == nullptr) return malloc_internal_heap(name, size, caps);
  377. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  378. void* resized = heap_caps_realloc(ptr, size, internalCaps);
  379. if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  380. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  381. return resized;
  382. }
  383. void *calloc_internal_heap(std::string name, size_t n, size_t size, uint32_t caps) {
  384. if (size != 0 && n > SIZE_MAX / size) {
  385. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Internal calloc size overflow for '" + name + "'");
  386. return nullptr;
  387. }
  388. if (n == 0 || size == 0) {
  389. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal calloc for '" + name + "'");
  390. return nullptr;
  391. }
  392. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  393. void* ptr = heap_caps_calloc(n, size, internalCaps);
  394. const size_t totalSize = n * size;
  395. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
  396. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
  397. return ptr;
  398. }
  399. void free_internal_heap(std::string name, void *ptr) {
  400. if (ptr == nullptr) return;
  401. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
  402. heap_caps_free(ptr);
  403. }