Skip to content

[Bug] Boot Failure by memory exhaustion on ESP32-S3 based devices #506

In review

Description

@t-miura

Describe the bug

Due to DRAM exhaustion, ESP32-S3 device running device-ui may not boot correctly, or enters boot-loop depends on how device is configured.

To Reproduce

Steps to reproduce the behavior:

  • Build a firmware for t-deck-tft using:
    • firmware repo's develop branch or even tagged ones(2.8.x)
    • device-ui repo's master HEAD
  • Flash and boot, either clean flash or dirty/update flash
  • It sometimes boots, sometime crashes
    • It gets worse when either SD card is inserted or Wi-Fi is enabled, even worse if both enabled.

Expected behavior

  • Device should boots normally with all functions available enabled
    • If microSD card is inserted, it should be available
    • If Wi-Fi is set correctly and enabled, it should connect and available
    • If microSD card is inserted AND Wi-Fi is set up/enabled, both should be available once it boots up.

Device (please complete the following information):

  • Type: T-Deck Plus
  • Exact version [e.g. 2.6.0.b85d9f988]
  • Firmware download source: self-built, using combination of above, also my own testing branch(which includes JP related patches and so on)
  • Other attached HW: None

Additional logs

  • Currently investigating the root cause with help of LLM, this issue will be updated once root cause and possible fixes are found.

Activity

  1. github-actions commented on Nov 27, 2026

    @github-actions
    Contributor

    Congratulations for your first issue

  2. t-miura commented on Nov 27, 2026

    @t-miura
    ContributorAuthor

    Root Cause Analysis

    Investigated serial logs and decoded ELF backtraces from a populated T-Deck Plus (t-deck-tft, ESP32-S3, 8 MB PSRAM) running with Wi-Fi enabled, a microSD card inserted, ~138–139 active nodes in NodeDB, and ~1,084 saved messages.

    • Root cause: too large max_packet_queue_size in PacketServer
      const uint32_t max_packet_queue_size = 300;
      • Currently it's set to 300
        • This will consumes ~242KB of memory when the queue is full like my case observed on t-deck-tft(ESP32-S3)
        • And it is hit-or-miss to fit in boot sequence, and becomes impossible when Wi-Fi is enabled and/or SD card is being utilized.

    (This also explains why clean bench flashes rarely hit the issue: a fresh NodeDB with few nodes and little/no message history queues only a few KB during both windows.)

    I hereby withdraw previous analysis, huge thanks @mverch67 to point me into a right direction 🙇

    1. Primary cause — DataPacket payloads stay in internal DRAM instead of PSRAM (include/util/Packet.h)

      • On ESP32-S3, ESP-IDF's default CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL (16384 bytes) routes standard new/malloc allocations <= 16 KB into internal DRAM, even when megabytes of PSRAM are free.
      • DataPacket<PacketType> allocates new PacketType(...) (~768 B for meshtastic_FromRadio).
      • With Wi-Fi enabled, free internal DRAM after Wi-Fi starts is ~88 KB. During boot, Core 1 (PacketAPI) pushes two large packet bursts into SharedQueue::serverQueue while Core 0 (DeviceUI) is busy and not calling receive():
        • Wave 1 (setupUIConfig() / updateSDCard()): While Core 0 creates screens and initializes SD storage, PacketAPI queues ~175 packets (138–139 NodeInfos + config + file manifest ≈ 135–140 KB), completely exhausting internal DRAM.
        • Wave 2 (restoreTextMessages()): Restoring 1,084 messages blocks ViewController::receive() for ~8.6 s while PacketAPI queues ~167 satellite-DB replay packets (positions/telemetry/status ≈ 134 KB), exhausting internal DRAM a second time.
    2. Crash mechanism (source/storage/FatFsStorage.cpp)

      • When microSD is inserted at boot, early SD setup leaves ~392 B less internal DRAM than no-SD. Once Wave 1 empties internal DRAM, FatFsStorage::mount() → FatFsStorage::release() attempts to lock std::mutex ioLock.
      • Under ESP-IDF, std::mutex lazily allocates its underlying FreeRTOS semaphore via pthread_mutex_lock() on first lock. With zero internal DRAM left, allocation fails and std::mutex::lock() calls std::__throw_system_error(); libgcc's unwinder (_Unwind_Find_FDE → pthread_mutex_unlock) then dereferences an uninitialized mutex handle (LoadProhibited, EXCVADDR: 0x00000003), causing a deterministic boot-loop.
      • Even with no microSD inserted, internal DRAM was still critically starved: on a "successful" boot, createStorage() barely survived by ~392 B, only for the very next mutex allocation inside FatFs f_mount() to fail with FR_INT_ERR (f_mount failed: (2) Assertion failed), and later Wave 2 starved AsyncMessageLog::start() (xTaskCreate(..., 4096) failed with Cannot start message log worker).

    Sanitized Example Logs (T-Deck Plus, ~139 nodes, 1,084 saved messages)

    Before fix — microSD inserted + Wi-Fi enabled (deterministic boot-loop)

    DEBUG | ??:??:?? 1 Free heap: 196144
    DEBUG | ??:??:?? 1 Free PSRAM: 8349848
    ...
    DEBUG | ??:??:?? 4 Free heap  :   88140 bytes
    DEBUG | ??:??:?? 4 Free PSRAM : 2528212 bytes
    ...
    DEBUG | ??:??:?? 17 [DeviceUI] TFTView_320x240 init done.
    DEBUG | ??:??:?? 17 [DeviceUI] init SDCard
    Guru Meditation Error: Core  0 panic'ed (LoadProhibited). Exception was unhandled.
    EXCCAUSE: 0x0000001c  EXCVADDR: 0x00000003
    

    Decoded call chain:

    pthread_mutex_unlock (pthread.c:795)
      <- _Unwind_Find_FDE / _Unwind_RaiseException / __cxa_throw
      <- std::__throw_system_error(int)
      <- std::mutex::lock()
      <- FatFsStorage::release() (source/storage/FatFsStorage.cpp:87)
      <- FatFsStorage::mount() (source/storage/FatFsStorage.cpp:114)
      <- TFTView_320x240::updateSDCard() (source/graphics/TFT/TFTView_320x240.cpp:9093)
      <- TFTView_320x240::setupUIConfig(...) (source/graphics/TFT/TFTView_320x240.cpp:549)
      <- ViewController::receive() (source/graphics/common/ViewController.cpp:637)
    

    Before fix — microSD removed + Wi-Fi enabled (latent DRAM OOM in Wave 1 & Wave 2)

    DEBUG | --:--:-- 17 [DeviceUI] init SDCard
    [ 17569][E][sd_diskio.cpp:838] sdcard_mount(): f_mount failed: (2) Assertion failed
    ...
    INFO  | --:--:-- 29 [DeviceUI] restoring 1084 messages completed in 8639ms.
    ERROR | --:--:-- 29 [DeviceUI] Cannot start message log worker
    ERROR | --:--:-- 29 [DeviceUI] Cannot start message log worker
    

    After fix — microSD inserted + Wi-Fi enabled (consecutive manual reboots + clean shutdown)

    TBD with proper fix(lower the max_packet_queue_size)


    Proposed Fix Summary

    • Lower the max_packet_queue_size suggested by @mverch67
      • This fix does not require any complicated modifications to the codebase, only a single-line edit
      • will start testing with suggested value: 30 from current 300, which may be a sweet spot.
        • This will consume 1/10 of memory than previous(estimated ~25KB at full), still fits even both Wi-Fi/SD card being active, solving the issue.
        • Lower bound is likely somewhere around 16(~13KB), and higher bound seems like 40(~33KB)
          • Too low might cause stutters on use, and too high will not solve this issue, needless to say.
        • Another sweet spot will be 25, which used in PacketClient: the opposite side of this
          const uint32_t max_packet_queue_size = 25;
          • If 30(~25KB) is still too big and crashes on my test, next value to try will be this(estimated ~21KB)

    below was my previous idea, which i hereby withdrawn as it does not solve the root cause:

    1. PSRAM payload allocation for DataPacket<PacketType> (include/util/Packet.h): On ARDUINO_ARCH_ESP32 builds with PSRAM (BOARD_HAS_PSRAM / CONFIG_SPIRAM), allocate packet payloads via heap_caps_aligned_alloc(..., MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT) with a MALLOC_CAP_DEFAULT fallback and placement-new, paired with a stateless PayloadDeleter calling ~PacketType() + heap_caps_free(). This eliminates both Wave 1 and Wave 2 internal-DRAM drains.
    2. Static internal-SRAM FreeRTOS mutex in FatFsStorage (include/storage/FatFsStorage.h, source/storage/FatFsStorage.cpp): Defense-in-depth replacement of std::mutex ioLock with a DRAM_ATTR StaticSemaphore_t initialized once via xSemaphoreCreateMutexStatic, avoiding dynamic internal-heap allocation on first lock while keeping the FreeRTOS spinlock strictly in internal SRAM (never PSRAM).

    Initial smoke-testing on T-Deck Plus (microSD + Wi-Fi enabled across multiple manual reboots and shutdown) passed without issues. Soak testing is now ongoing; a PR will follow soon.

  3. mverch67 commented on Nov 27, 2026

    @mverch67
    Collaborator

    It's not a good idea to move the temporary packet data into PSRAM memory. This only addresses symptoms rather than fixing a root cause and may not work on devices with little PSRAM capacity.

    Instead I would lower the packet queue size which is filled up too fast by the firmware process which consumes all the temporary memory:

    const uint32_t max_packet_queue_size = 300;

    Try lowering to 30 and test again.

  4. t-miura commented on Nov 27, 2026

    @t-miura
    ContributorAuthor

    @mverch67
    thanks for the pointing the right path! 🙇

    will try that instead of PSRAM patch anytime soon, and report back in here.

  5. t-miura commented on Nov 27, 2026

    @t-miura
    ContributorAuthor

    lowering that to 30 seems to stopped boot-looping, while also stopped updating some of status screen, hmmmmm....

    gemini found one possible bug in firmware side, PacketAPI::checkIsConnected() in src/mesh/api/PacketAPI.cpp:
    https://github.com/meshtastic/firmware/blob/eb99f95814128956ec6e708ecde9bf564fd93efb/src/mesh/api/PacketAPI.cpp#L139

    return isConnected && server->available(); should be simply return isConnected,
    as current code will mistakenly drops API connection when the queue(which is now smaller than before) is full, causing stale updates.

    Copilot (tbh i rarely use this to verify something) agrees with this, and I'm now building a firmware with that change too.

    checkIsConnected() is used by APIServerPort to decide whether to discard the current API instance.
    So if the queue is temporarily full, this returns false even though the client may still be connected;
    the caller may then reset the instance and drop its state. Queue capacity and connection status are better checked separately.
    

    if it's true and does fix all issues in here, firmware-side PR needs to be land first, and device-ui's lowering queue followed by that.

  6. t-miura commented on Nov 27, 2026

    @t-miura
    ContributorAuthor

    read the firmware side's code a bit, i think it's safe to apply that changes as:

    and, happy to report that now all issue in here seems to be solved by these two small changes, will continue to soak some more.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions