psram.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432
  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. return psram_reserve_shared_tmp_image_memory(static_cast<size_t>(IMAGE_SIZE));
  230. }
  231. void *psram_reserve_shared_tmp_image_memory(size_t requiredSize) {
  232. size_t regionSize = 0;
  233. if (requiredSize == 0 || !getSharedRegionSize(&regionSize) || requiredSize > regionSize) {
  234. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "tmpImage does not fit in the reserved shared PSRAM region (" +
  235. std::to_string(requiredSize) + " bytes requested)");
  236. return nullptr;
  237. }
  238. SharedMemoryUser currentUser;
  239. void* result = nullptr;
  240. portENTER_CRITICAL(&sharedMemoryMux);
  241. currentUser = sharedMemoryUser;
  242. if (sharedRegion != nullptr && sharedMemoryUser == SharedMemoryUser::None) {
  243. sharedMemoryUser = SharedMemoryUser::Aligning;
  244. result = sharedRegion;
  245. }
  246. portEXIT_CRITICAL(&sharedMemoryMux);
  247. if (result == nullptr) {
  248. LogFile.WriteToFile(ESP_LOG_WARN, TAG, "Shared PSRAM unavailable for tmpImage (" +
  249. std::to_string(requiredSize) + " bytes requested; owner: " +
  250. std::string(sharedMemoryUserName(currentUser)) + ")");
  251. return nullptr;
  252. }
  253. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating tmpImage (" + std::to_string(requiredSize) + " bytes, shared PSRAM)...");
  254. return result;
  255. }
  256. void psram_free_shared_temp_image_memory(void) {
  257. bool released = false;
  258. portENTER_CRITICAL(&sharedMemoryMux);
  259. if (sharedMemoryUser == SharedMemoryUser::Aligning) { sharedMemoryUser = SharedMemoryUser::None; released = true; }
  260. portEXIT_CRITICAL(&sharedMemoryMux);
  261. if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for tmpImage is free again");
  262. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched tmpImage shared-memory release");
  263. }
  264. /*******************************************************************
  265. * Memory used in Digitization Steps
  266. *******************************************************************/
  267. void *psram_get_shared_tensor_arena_memory(void) {
  268. bool unavailable = false, duplicateClaim = false;
  269. void* result = nullptr;
  270. SharedMemoryUser currentUser;
  271. portENTER_CRITICAL(&sharedMemoryMux);
  272. currentUser = sharedMemoryUser;
  273. if (sharedRegion == nullptr || (sharedMemoryUser != SharedMemoryUser::None && sharedMemoryUser != SharedMemoryUser::Digitization)) unavailable = true;
  274. else if (tensorArenaClaimed) duplicateClaim = true;
  275. else { sharedMemoryUser = SharedMemoryUser::Digitization; tensorArenaClaimed = true; result = sharedRegion; }
  276. portEXIT_CRITICAL(&sharedMemoryMux);
  277. if (result == nullptr) {
  278. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Tensor Arena shared memory was claimed more than once" :
  279. (unavailable ? "Shared PSRAM is unavailable for Tensor Arena (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Tensor Arena allocation failed"));
  280. return nullptr;
  281. }
  282. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Tensor Arena (" + std::to_string(TENSOR_ARENA_SIZE) + " bytes in shared PSRAM)...");
  283. return result;
  284. }
  285. void *psram_get_shared_model_memory(void) {
  286. bool unavailable = false, duplicateClaim = false;
  287. void* result = nullptr;
  288. size_t modelOffset = 0;
  289. if (!getAlignedTensorArenaSize(&modelOffset)) {
  290. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Invalid Tensor Arena size for model placement");
  291. return nullptr;
  292. }
  293. SharedMemoryUser currentUser;
  294. portENTER_CRITICAL(&sharedMemoryMux);
  295. currentUser = sharedMemoryUser;
  296. if (sharedRegion == nullptr || !tensorArenaClaimed ||
  297. sharedMemoryUser != SharedMemoryUser::Digitization) unavailable = true;
  298. else if (modelMemoryClaimed) duplicateClaim = true;
  299. else { sharedMemoryUser = SharedMemoryUser::Digitization; modelMemoryClaimed = true; result = sharedRegion + modelOffset; }
  300. portEXIT_CRITICAL(&sharedMemoryMux);
  301. if (result == nullptr) {
  302. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, duplicateClaim ? "Model shared memory was claimed more than once" :
  303. (unavailable ? "Shared PSRAM is unavailable for Model (owner: " + std::string(sharedMemoryUserName(currentUser)) + ")" : "Model allocation failed"));
  304. return nullptr;
  305. }
  306. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocating Model memory (" + std::to_string(MAX_MODEL_SIZE) + " bytes in shared PSRAM)...");
  307. return result;
  308. }
  309. void psram_free_shared_tensor_arena_and_model_memory(void) {
  310. bool released = false;
  311. portENTER_CRITICAL(&sharedMemoryMux);
  312. if (sharedMemoryUser == SharedMemoryUser::Digitization) {
  313. tensorArenaClaimed = false; modelMemoryClaimed = false;
  314. sharedMemoryUser = SharedMemoryUser::None; released = true;
  315. }
  316. portEXIT_CRITICAL(&sharedMemoryMux);
  317. if (released) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Shared memory used for Tensor Arena and model is free again");
  318. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Ignoring mismatched Tensor Arena/Model shared-memory release");
  319. }
  320. /*******************************************************************
  321. * General PSRAM heap wrappers
  322. *******************************************************************/
  323. void *malloc_psram_heap(std::string name, size_t size, uint32_t caps) {
  324. if (size == 0) {
  325. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM allocation for '" + name + "'");
  326. return nullptr;
  327. }
  328. void* ptr = heap_caps_malloc(size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  329. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
  330. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
  331. return ptr;
  332. }
  333. void *realloc_psram_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
  334. void* resized = heap_caps_realloc(ptr, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  335. if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in PSRAM for '" + name + "'");
  336. else if (size != 0) LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in PSRAM for '" + name + "'!");
  337. return resized;
  338. }
  339. void *calloc_psram_heap(std::string name, size_t n, size_t size, uint32_t caps) {
  340. if (size != 0 && n > SIZE_MAX / size) {
  341. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "PSRAM calloc size overflow for '" + name + "'");
  342. return nullptr;
  343. }
  344. const size_t totalSize = n * size;
  345. if (totalSize == 0) {
  346. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte PSRAM calloc for '" + name + "'");
  347. return nullptr;
  348. }
  349. void* ptr = heap_caps_calloc(n, size, caps | MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT);
  350. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'");
  351. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in PSRAM for '" + name + "'!");
  352. return ptr;
  353. }
  354. void free_psram_heap(std::string name, void *ptr) {
  355. if (ptr == nullptr) return;
  356. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing memory in PSRAM used for '" + name + "'...");
  357. heap_caps_free(ptr);
  358. }
  359. /*******************************************************************
  360. * Internal SRAM heap wrappers
  361. *******************************************************************/
  362. void *malloc_internal_heap(std::string name, size_t size, uint32_t caps) {
  363. if (size == 0) {
  364. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal allocation for '" + name + "'");
  365. return nullptr;
  366. }
  367. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  368. void* ptr = heap_caps_malloc(size, internalCaps);
  369. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  370. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  371. return ptr;
  372. }
  373. void *realloc_internal_heap(std::string name, void *ptr, size_t size, uint32_t caps) {
  374. if (size == 0) {
  375. if (ptr != nullptr) {
  376. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
  377. heap_caps_free(ptr);
  378. }
  379. return nullptr;
  380. }
  381. if (ptr == nullptr) return malloc_internal_heap(name, size, caps);
  382. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  383. void* resized = heap_caps_realloc(ptr, size, internalCaps);
  384. if (resized != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Reallocated " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  385. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to reallocate " + std::to_string(size) + " bytes in internal SRAM for '" + name + "'");
  386. return resized;
  387. }
  388. void *calloc_internal_heap(std::string name, size_t n, size_t size, uint32_t caps) {
  389. if (size != 0 && n > SIZE_MAX / size) {
  390. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Internal calloc size overflow for '" + name + "'");
  391. return nullptr;
  392. }
  393. if (n == 0 || size == 0) {
  394. LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Refusing zero-byte internal calloc for '" + name + "'");
  395. return nullptr;
  396. }
  397. const uint32_t internalCaps = (caps | MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT) & ~MALLOC_CAP_SPIRAM;
  398. void* ptr = heap_caps_calloc(n, size, internalCaps);
  399. const size_t totalSize = n * size;
  400. if (ptr != nullptr) LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Allocated and cleared " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
  401. else LogFile.WriteToFile(ESP_LOG_ERROR, TAG, "Failed to allocate " + std::to_string(totalSize) + " bytes in internal SRAM for '" + name + "'");
  402. return ptr;
  403. }
  404. void free_internal_heap(std::string name, void *ptr) {
  405. if (ptr == nullptr) return;
  406. LogFile.WriteToFile(ESP_LOG_DEBUG, TAG, "Freeing internal SRAM used for '" + name + "'...");
  407. heap_caps_free(ptr);
  408. }