From 88853f9fb47cd3002b28a621e702e3ab69d71b49 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 22 Nov 2026 13:49:05 -0700 Subject: [PATCH 1/5] test(rtps): QEMU firmware logs internal RAM per endpoint and over the first 3 s Diagnostic for the restart case's thin internal-RAM headroom: a RTPSTEST dram marker (byte-addressable internal free / min / largest + task count) after each endpoint is created, every 100 ms for 3 s after the endpoints exist, and the task names at both ends of that window, on every participant (the first and the one after the restart), so their costs can be compared. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- .../rtps/interop/qemu/main/rtps_qemu.cpp | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index 6bd4839852..c6eee0192d 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -71,6 +71,25 @@ void log_mem_heap(espp::Logger &logger, const char *stage) { heap_caps_get_free_size(kDramCaps), heap_caps_get_minimum_free_size(kDramCaps), heap_caps_get_largest_free_block(kDramCaps)); } +// Byte-addressable internal RAM (what a task stack comes from) and the task +// count, at a named point: where a stage's internal-RAM cost goes (diagnostic). +void log_dram(espp::Logger &logger, const char *point) { + logger.info("RTPSTEST dram {} free={} min={} largest={} tasks={}", point, + heap_caps_get_free_size(kDramCaps), heap_caps_get_minimum_free_size(kDramCaps), + heap_caps_get_largest_free_block(kDramCaps), uxTaskGetNumberOfTasks()); +} +// The task names, to compare a participant's tasks with the next one's. +void log_task_names(espp::Logger &logger, const char *point) { + std::vector tasks(uxTaskGetNumberOfTasks() + 4); + const auto n = uxTaskGetSystemState(tasks.data(), tasks.size(), nullptr); + std::string names; + for (UBaseType_t i = 0; i < n; ++i) { + if (!names.empty()) + names += ','; + names += tasks[i].pcTaskName; + } + logger.info("RTPSTEST task names {} n={} {}", point, n, names); +} // The restart case calls /qemu_add_two_ints with this magic request to ask the // device to recreate its participant (see the service handler in run_participant). constexpr int64_t kRestartMagicA = 424242; @@ -199,6 +218,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a return; } log_mem_heap(logger, "started"); + log_dram(logger, "started"); using Reliability = espp::RtpsParticipant::Reliability; constexpr const char *type_name = "std_msgs::msg::dds_::String_"; @@ -208,6 +228,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a .type_name = type_name, .reliability = Reliability::RELIABLE, }); + log_dram(logger, "publisher"); espp::Subscriber subscriber(participant, { .topic = "rt/qemu_rx", .type_name = type_name, @@ -219,11 +240,13 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a msg.data); }, }); + log_dram(logger, "subscriber"); espp::Publisher be_publisher(participant, { .topic = "rt/qemu_be_tx", .type_name = type_name, .reliability = Reliability::BEST_EFFORT, }); + log_dram(logger, "be_publisher"); espp::Subscriber be_subscriber(participant, { .topic = "rt/qemu_be_rx", @@ -237,6 +260,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a }); // Samples larger than one UDP datagram arrive as DATA_FRAG and are // reassembled (CONFIG_RTPS_ENABLE_FRAGMENTATION); only the length is logged. + log_dram(logger, "be_subscriber"); espp::Subscriber big_subscriber( participant, { .topic = "rt/qemu_big", @@ -254,6 +278,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a return; } + log_dram(logger, "big_subscriber"); #ifdef RTPS_WITH_RPC espp::ServiceServer add_service( participant, { @@ -290,6 +315,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a } // The action server's execute worker is a task created with the server (its // stack is part of the "endpoints" stage); a goal runs on it. + log_dram(logger, "service"); espp::ActionServer fib_action( participant, { .action = "/qemu_fibonacci", @@ -328,6 +354,17 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a #endif log_mem_heap(logger, "endpoints"); + log_dram(logger, "endpoints"); + log_task_names(logger, "endpoints"); + // Diagnostic: internal RAM over the first 3 s after the endpoints exist (on + // a busy domain, discovery of every live peer happens here): where the + // restart case's internal-RAM low point comes from. + for (int i = 1; i <= 30; ++i) { + std::this_thread::sleep_for(100ms); + const std::string point = "t+" + std::to_string(i * 100) + "ms"; + log_dram(logger, point.c_str()); + } + log_task_names(logger, "t+3s"); // Periodic publishers: one reliable, one best-effort uint32_t counter = 0; From 3de05bbe64466671c1ec8986632a968003235ff3 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 22 Nov 2026 14:30:16 -0700 Subject: [PATCH 2/5] test(rtps): QEMU experiment - small allocations PSRAM-first (ALWAYSINTERNAL 512) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/interop/qemu/sdkconfig.defaults | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/components/rtps/interop/qemu/sdkconfig.defaults b/components/rtps/interop/qemu/sdkconfig.defaults index 5f45a705df..097da0247e 100644 --- a/components/rtps/interop/qemu/sdkconfig.defaults +++ b/components/rtps/interop/qemu/sdkconfig.defaults @@ -14,7 +14,11 @@ CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_SPIRAM=y CONFIG_SPIRAM_USE_MALLOC=y -CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=4096 +# EXPERIMENT (draft #923): small allocations go to PSRAM first too, to test +# whether the engine's per-match small heap allocations (payload vectors and +# the like, all under the old 4096 threshold) are what drains internal RAM +# when a new participant matches a busy domain at once. +CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=512 # Keep internal RAM for what must live there. The restart case tears the # participant down and builds a new one while a dozen peers from the earlier # cases are still announcing: the new participant discovers them all at once, From fbd803efa0e89ab23dd14e634e09873772b853e0 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 22 Nov 2026 15:08:59 -0700 Subject: [PATCH 3/5] fix(rtps): keep payload buffers in PSRAM first (RTPS_PAYLOAD_PREFER_PSRAM) The QEMU restart case showed a participant recreated next to a dozen live ROS 2 peers spending 8-12 KB of internal RAM per endpoint (about 1 KB on an empty domain) until creating the action server's FreeRTOS lock failed and the device aborted. The cost is the engine's payload bytes - history-cache samples, the messages it builds and the datagrams it parses: a few hundred bytes each, below CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL, so malloc() put them in internal RAM, and the new endpoints match every peer at once. Lowering ALWAYSINTERNAL to 512 in the QEMU firmware brought the per-endpoint cost after the restart back to ~1 KB and the post-restart low point from 10 KB to 60 KB, confirming it. PayloadBuffer::bytes and PacketInfo::payload now use rtps::PayloadAllocator, which allocates from PSRAM first (heap_caps_malloc_prefer, internal RAM as the fallback) when CONFIG_RTPS_PAYLOAD_PREFER_PSRAM is set - default on whenever PSRAM is enabled - and is plain operator new elsewhere (host, no PSRAM, option off). Applications get it without changing a global heap setting. The QEMU firmware is back on the default ALWAYSINTERNAL to exercise the engine fix and keeps a per-endpoint internal-RAM marker (the timeline and task-name dumps are removed). README + docs: the option, and a section on internal RAM on a busy domain (RESERVE_INTERNAL, lwIP in PSRAM, which free-size figure to watch). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/Kconfig | 16 +++ components/rtps/README.md | 24 +++++ .../include/rtps/communication/PacketInfo.hpp | 3 +- .../rtps/storages/PayloadAllocator.hpp | 101 ++++++++++++++++++ .../include/rtps/storages/PayloadBuffer.hpp | 3 +- .../rtps/interop/qemu/main/rtps_qemu.cpp | 26 +---- .../rtps/interop/qemu/sdkconfig.defaults | 6 +- doc/en/protocols/rtps.rst | 7 ++ 8 files changed, 156 insertions(+), 30 deletions(-) create mode 100644 components/rtps/include/rtps/storages/PayloadAllocator.hpp diff --git a/components/rtps/Kconfig b/components/rtps/Kconfig index 3c8c5ca531..a2f015a99b 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -433,6 +433,22 @@ menu "RTPS" firmware share it. 0 is the DDS default and matches a ROS 2 host with no ROS_DOMAIN_ID set. + config RTPS_PAYLOAD_PREFER_PSRAM + bool "Keep payload buffers in PSRAM first" + depends on SPIRAM_USE_MALLOC || SPIRAM_USE_CAPS_ALLOC + default y + help + Allocate the engine's payload bytes (history-cache samples, the + messages it builds, the datagrams it parses) from PSRAM first, and + from internal RAM only when PSRAM cannot satisfy them. They are + mostly below CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL, so a plain + malloc() would put them in internal RAM, and on a busy domain they + add up: a participant that joins (or restarts into) a domain with + many live peers receives all of their discovery announcements at + once, and the internal RAM a task stack or a FreeRTOS lock needs + runs out. Disable to keep them in internal RAM (slightly faster + access, at that cost). + config RTPS_STORAGE_DYNAMIC bool "Use dynamic (heap) history/queue storage" default n diff --git a/components/rtps/README.md b/components/rtps/README.md index 4a387a3185..8cb5f5b223 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -183,6 +183,7 @@ via `include/rtps/config.hpp`. | `RTPS_LIMITS_PROFILE` | `embedded` (default) / `host` / `host_large` | Compile-time endpoint/history capacity caps (`config_esp32.hpp` / `config_desktop.hpp` / `config_host_large.hpp`). Wire-neutral. | | `RTPS_STORAGE_DYNAMIC` | off on ESP32 / on host | Static `std::array` history (zero-heap, drop-oldest) vs heap-backed `std::deque` (grows). Orthogonal to the profile. | | `RTPS_ENABLE_FRAGMENTATION` | off on ESP32 / on host | DATA_FRAG for samples > ~64 KB (interoperates with FastDDS/ROS 2). | +| `RTPS_PAYLOAD_PREFER_PSRAM` | on when PSRAM is enabled | Allocate payload bytes (history-cache samples, built messages, parsed datagrams) from PSRAM first, internal RAM only as a fallback. See [Internal RAM on a busy domain](#internal-ram-on-a-busy-domain). | | `RTPS_ENABLE_RPC` | on (default) | Compile in services + actions (RMI/AMI). Disable to drop that code + its threads on a pure-pub/sub device. | | `RTPS_DOMAIN_ID` | 0 | DDS domain id (the `ROS_DOMAIN_ID` equivalent, 0..232). Derives the port base `7400 + 250 * id` and GUID prefix byte 9, so every participant on a domain must use the same value. Compile-time. | | `RTPS_THREAD_POOL_READER_PRIO` | 0 = profile default (5 on ESP32) | FreeRTOS priority of the transport's worker pool and reactor tasks, which send and receive all traffic (see [Priority scheduling](#priority-scheduling-bands-dedicated-ports-dscp)). | @@ -221,6 +222,29 @@ a stack that derives its prefix from stable hardware identifiers would - is recognised by the sequence number of its announcements falling far below what it had reached, and rediscovered on the spot. +### Internal RAM on a busy domain + +On an ESP32 with PSRAM, what runs out first is the byte-addressable internal +RAM (`MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT`). Every new task's stack and +every FreeRTOS lock behind a `std::mutex` / `std::condition_variable` comes +from it. A participant that joins, or is recreated on, a domain with many live +peers receives all of their discovery announcements at once. Each one becomes a +payload of a few hundred bytes, below `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` +(4096 by default), so a plain `malloc()` puts it in internal RAM. + +In the QEMU interop suite, a participant recreated next to a dozen ROS 2 peers +spent 8-12 KB of internal RAM per endpoint, against about 1 KB on an empty +domain, until creating the next task failed and the device aborted. +`RTPS_PAYLOAD_PREFER_PSRAM` (on by default with PSRAM) keeps those payloads +in PSRAM. Beyond it, an application on a busy domain should: + +- keep `CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL` large enough for the tasks and + locks it creates at runtime (the QEMU firmware reserves 64 KB); +- let lwIP allocate from PSRAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP`); +- watch `heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)` + rather than the `MALLOC_CAP_INTERNAL` total, which on the ESP32 includes IRAM + that neither stacks nor byte accesses can use. + ### Per-limit capacity overrides Every capacity cap in the profile headers can be raised (or lowered) diff --git a/components/rtps/include/rtps/communication/PacketInfo.hpp b/components/rtps/include/rtps/communication/PacketInfo.hpp index 1ed8947427..9ab16c4aea 100644 --- a/components/rtps/include/rtps/communication/PacketInfo.hpp +++ b/components/rtps/include/rtps/communication/PacketInfo.hpp @@ -33,6 +33,7 @@ Author: i11 - Embedded Software, RWTH Aachen University #include #include "rtps/common/types.hpp" +#include "rtps/storages/PayloadAllocator.hpp" namespace rtps { @@ -40,7 +41,7 @@ struct PacketInfo { Ip4Port_t srcPort; // TODO Do we need that? std::array destAddr = {0, 0, 0, 0}; Ip4Port_t destPort; - std::vector payload; + PayloadBytes payload; ///< PSRAM first where configured (PayloadAllocator) void copyTriviallyCopyable(const PacketInfo &other) { this->srcPort = other.srcPort; diff --git a/components/rtps/include/rtps/storages/PayloadAllocator.hpp b/components/rtps/include/rtps/storages/PayloadAllocator.hpp new file mode 100644 index 0000000000..76f5caf805 --- /dev/null +++ b/components/rtps/include/rtps/storages/PayloadAllocator.hpp @@ -0,0 +1,101 @@ +/* +The MIT License +Copyright (c) 2026 ATDev +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE + +This file is part of the espp embeddedRTPS port. +*/ + +#ifndef RTPS_PAYLOADALLOCATOR_H +#define RTPS_PAYLOADALLOCATOR_H + +#include +#include +#include +#include +#include + +#if defined(ESP_PLATFORM) +#include "esp_heap_caps.h" +#include "sdkconfig.h" +#endif + +namespace rtps { + +/// Allocator for the engine's payload bytes: the history caches' samples, the +/// messages it builds to send and the datagrams it parses. +/// +/// Those buffers are mostly a few hundred bytes to a datagram, below the usual +/// CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL threshold, so a plain malloc() puts +/// them in internal RAM first. On a busy domain they add up: a participant +/// that joins (or restarts into) a domain with a dozen live peers takes every +/// peer's discovery announcements at once, and the internal RAM a task stack +/// or a FreeRTOS lock needs runs out. With CONFIG_RTPS_PAYLOAD_PREFER_PSRAM +/// (default on when PSRAM is enabled) they are allocated from PSRAM first and +/// from internal RAM only when PSRAM cannot satisfy them. Elsewhere (no PSRAM, +/// the option off, the host) this is plain operator new / delete. +template struct PayloadAllocator { + using value_type = T; + + PayloadAllocator() noexcept = default; + template constexpr PayloadAllocator(const PayloadAllocator &) noexcept {} + + T *allocate(std::size_t n) { +#if defined(ESP_PLATFORM) && CONFIG_RTPS_PAYLOAD_PREFER_PSRAM + if (n > static_cast(-1) / sizeof(T)) { + allocation_failed(); + } + void *p = heap_caps_malloc_prefer(n * sizeof(T), 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT, + MALLOC_CAP_DEFAULT); + if (p == nullptr) { + allocation_failed(); + } + return static_cast(p); +#else + return static_cast(::operator new(n * sizeof(T))); +#endif + } + + void deallocate(T *p, std::size_t) noexcept { +#if defined(ESP_PLATFORM) && CONFIG_RTPS_PAYLOAD_PREFER_PSRAM + heap_caps_free(p); +#else + ::operator delete(p); +#endif + } + + template bool operator==(const PayloadAllocator &) const noexcept { return true; } + template bool operator!=(const PayloadAllocator &) const noexcept { return false; } + +private: + [[noreturn]] static void allocation_failed() { + // what operator new does when it cannot allocate: bad_alloc, or (built + // without exceptions) the program ends +#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) + throw std::bad_alloc(); +#else + std::abort(); +#endif + } +}; + +/// The byte vector the engine keeps payloads in (see PayloadAllocator). +using PayloadBytes = std::vector>; + +} // namespace rtps + +#endif // RTPS_PAYLOADALLOCATOR_H diff --git a/components/rtps/include/rtps/storages/PayloadBuffer.hpp b/components/rtps/include/rtps/storages/PayloadBuffer.hpp index 581aa8007d..513b707c9a 100644 --- a/components/rtps/include/rtps/storages/PayloadBuffer.hpp +++ b/components/rtps/include/rtps/storages/PayloadBuffer.hpp @@ -26,11 +26,12 @@ This file is part of the espp embeddedRTPS port. #include #include "rtps/common/types.hpp" +#include "rtps/storages/PayloadAllocator.hpp" namespace rtps { struct PayloadBuffer { - std::vector bytes; + PayloadBytes bytes; ///< PSRAM first where configured (PayloadAllocator) bool isValid() const { return true; } diff --git a/components/rtps/interop/qemu/main/rtps_qemu.cpp b/components/rtps/interop/qemu/main/rtps_qemu.cpp index c6eee0192d..92ca38c367 100644 --- a/components/rtps/interop/qemu/main/rtps_qemu.cpp +++ b/components/rtps/interop/qemu/main/rtps_qemu.cpp @@ -72,24 +72,14 @@ void log_mem_heap(espp::Logger &logger, const char *stage) { heap_caps_get_largest_free_block(kDramCaps)); } // Byte-addressable internal RAM (what a task stack comes from) and the task -// count, at a named point: where a stage's internal-RAM cost goes (diagnostic). +// count at a named point, after each endpoint is created: what each endpoint +// costs in internal RAM, on the first participant and on the one after the +// restart (which matches a busy domain at once). void log_dram(espp::Logger &logger, const char *point) { logger.info("RTPSTEST dram {} free={} min={} largest={} tasks={}", point, heap_caps_get_free_size(kDramCaps), heap_caps_get_minimum_free_size(kDramCaps), heap_caps_get_largest_free_block(kDramCaps), uxTaskGetNumberOfTasks()); } -// The task names, to compare a participant's tasks with the next one's. -void log_task_names(espp::Logger &logger, const char *point) { - std::vector tasks(uxTaskGetNumberOfTasks() + 4); - const auto n = uxTaskGetSystemState(tasks.data(), tasks.size(), nullptr); - std::string names; - for (UBaseType_t i = 0; i < n; ++i) { - if (!names.empty()) - names += ','; - names += tasks[i].pcTaskName; - } - logger.info("RTPSTEST task names {} n={} {}", point, n, names); -} // The restart case calls /qemu_add_two_ints with this magic request to ask the // device to recreate its participant (see the service handler in run_participant). constexpr int64_t kRestartMagicA = 424242; @@ -355,16 +345,6 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a log_mem_heap(logger, "endpoints"); log_dram(logger, "endpoints"); - log_task_names(logger, "endpoints"); - // Diagnostic: internal RAM over the first 3 s after the endpoints exist (on - // a busy domain, discovery of every live peer happens here): where the - // restart case's internal-RAM low point comes from. - for (int i = 1; i <= 30; ++i) { - std::this_thread::sleep_for(100ms); - const std::string point = "t+" + std::to_string(i * 100) + "ms"; - log_dram(logger, point.c_str()); - } - log_task_names(logger, "t+3s"); // Periodic publishers: one reliable, one best-effort uint32_t counter = 0; diff --git a/components/rtps/interop/qemu/sdkconfig.defaults b/components/rtps/interop/qemu/sdkconfig.defaults index 097da0247e..5f45a705df 100644 --- a/components/rtps/interop/qemu/sdkconfig.defaults +++ b/components/rtps/interop/qemu/sdkconfig.defaults @@ -14,11 +14,7 @@ CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_SPIRAM=y CONFIG_SPIRAM_USE_MALLOC=y -# EXPERIMENT (draft #923): small allocations go to PSRAM first too, to test -# whether the engine's per-match small heap allocations (payload vectors and -# the like, all under the old 4096 threshold) are what drains internal RAM -# when a new participant matches a busy domain at once. -CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=512 +CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=4096 # Keep internal RAM for what must live there. The restart case tears the # participant down and builds a new one while a dozen peers from the earlier # cases are still announcing: the new participant discovers them all at once, diff --git a/doc/en/protocols/rtps.rst b/doc/en/protocols/rtps.rst index 3cd2de38a1..0074d1016c 100644 --- a/doc/en/protocols/rtps.rst +++ b/doc/en/protocols/rtps.rst @@ -281,6 +281,13 @@ menuconfig under ``RTPS`` on ESP32; ``include/rtps/config.hpp`` defaults on host - on (default) - Compile in services + actions (RMI/AMI). Disable to drop that code and its threads on a pure-pub/sub device. + * - ``RTPS_PAYLOAD_PREFER_PSRAM`` + - on when PSRAM is enabled + - Allocate payload bytes (history-cache samples, built messages, parsed + datagrams) from PSRAM first, internal RAM only as a fallback, so a + participant joining a busy domain does not exhaust the internal RAM that + task stacks and FreeRTOS locks need. See the component README, + *Internal RAM on a busy domain*. Relevant Specifications ----------------------- From 28ac9e4e5d4661285f59cb50c7f2820866480b82 Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 22 Nov 2026 17:12:43 -0700 Subject: [PATCH 4/5] fix(rtps): QEMU firmware puts received Ethernet frames in PSRAM; revert the payload allocator The payload allocator did not move the restart case's internal-RAM cost (after the restart the endpoints still left 8.7 KB, matrix 11/33): the engine's payloads were not it. The cost is the openeth driver's receive buffers: it mallocs a full frame (~1.5 KB) per packet and lwIP holds it until the engine reads the datagram, up to LWIP_UDP_RECVMBOX_SIZE (64) per socket. Below the 4096 ALWAYSINTERNAL threshold they landed in internal RAM, and a participant recreated next to a dozen live peers gets all of their answers while it creates its endpoints. The ALWAYSINTERNAL=512 experiment moved exactly these. QEMU firmware: ALWAYSINTERNAL 1024, below a frame, so smaller allocations (FreeRTOS objects, small engine state) stay internal. PayloadAllocator and RTPS_PAYLOAD_PREFER_PSRAM are removed (the engine is unchanged). The README's busy-domain section now names the driver's frames and lwIP's queue depth as the cost and what to configure. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/rtps/Kconfig | 16 --- components/rtps/README.md | 41 ++++--- .../include/rtps/communication/PacketInfo.hpp | 3 +- .../rtps/storages/PayloadAllocator.hpp | 101 ------------------ .../include/rtps/storages/PayloadBuffer.hpp | 3 +- .../rtps/interop/qemu/sdkconfig.defaults | 8 +- doc/en/protocols/rtps.rst | 7 -- 7 files changed, 33 insertions(+), 146 deletions(-) delete mode 100644 components/rtps/include/rtps/storages/PayloadAllocator.hpp diff --git a/components/rtps/Kconfig b/components/rtps/Kconfig index a2f015a99b..3c8c5ca531 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -433,22 +433,6 @@ menu "RTPS" firmware share it. 0 is the DDS default and matches a ROS 2 host with no ROS_DOMAIN_ID set. - config RTPS_PAYLOAD_PREFER_PSRAM - bool "Keep payload buffers in PSRAM first" - depends on SPIRAM_USE_MALLOC || SPIRAM_USE_CAPS_ALLOC - default y - help - Allocate the engine's payload bytes (history-cache samples, the - messages it builds, the datagrams it parses) from PSRAM first, and - from internal RAM only when PSRAM cannot satisfy them. They are - mostly below CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL, so a plain - malloc() would put them in internal RAM, and on a busy domain they - add up: a participant that joins (or restarts into) a domain with - many live peers receives all of their discovery announcements at - once, and the internal RAM a task stack or a FreeRTOS lock needs - runs out. Disable to keep them in internal RAM (slightly faster - access, at that cost). - config RTPS_STORAGE_DYNAMIC bool "Use dynamic (heap) history/queue storage" default n diff --git a/components/rtps/README.md b/components/rtps/README.md index 8cb5f5b223..758e8be73b 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -183,7 +183,6 @@ via `include/rtps/config.hpp`. | `RTPS_LIMITS_PROFILE` | `embedded` (default) / `host` / `host_large` | Compile-time endpoint/history capacity caps (`config_esp32.hpp` / `config_desktop.hpp` / `config_host_large.hpp`). Wire-neutral. | | `RTPS_STORAGE_DYNAMIC` | off on ESP32 / on host | Static `std::array` history (zero-heap, drop-oldest) vs heap-backed `std::deque` (grows). Orthogonal to the profile. | | `RTPS_ENABLE_FRAGMENTATION` | off on ESP32 / on host | DATA_FRAG for samples > ~64 KB (interoperates with FastDDS/ROS 2). | -| `RTPS_PAYLOAD_PREFER_PSRAM` | on when PSRAM is enabled | Allocate payload bytes (history-cache samples, built messages, parsed datagrams) from PSRAM first, internal RAM only as a fallback. See [Internal RAM on a busy domain](#internal-ram-on-a-busy-domain). | | `RTPS_ENABLE_RPC` | on (default) | Compile in services + actions (RMI/AMI). Disable to drop that code + its threads on a pure-pub/sub device. | | `RTPS_DOMAIN_ID` | 0 | DDS domain id (the `ROS_DOMAIN_ID` equivalent, 0..232). Derives the port base `7400 + 250 * id` and GUID prefix byte 9, so every participant on a domain must use the same value. Compile-time. | | `RTPS_THREAD_POOL_READER_PRIO` | 0 = profile default (5 on ESP32) | FreeRTOS priority of the transport's worker pool and reactor tasks, which send and receive all traffic (see [Priority scheduling](#priority-scheduling-bands-dedicated-ports-dscp)). | @@ -224,23 +223,31 @@ it had reached, and rediscovered on the spot. ### Internal RAM on a busy domain -On an ESP32 with PSRAM, what runs out first is the byte-addressable internal -RAM (`MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT`). Every new task's stack and -every FreeRTOS lock behind a `std::mutex` / `std::condition_variable` comes -from it. A participant that joins, or is recreated on, a domain with many live -peers receives all of their discovery announcements at once. Each one becomes a -payload of a few hundred bytes, below `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` -(4096 by default), so a plain `malloc()` puts it in internal RAM. - -In the QEMU interop suite, a participant recreated next to a dozen ROS 2 peers -spent 8-12 KB of internal RAM per endpoint, against about 1 KB on an empty -domain, until creating the next task failed and the device aborted. -`RTPS_PAYLOAD_PREFER_PSRAM` (on by default with PSRAM) keeps those payloads -in PSRAM. Beyond it, an application on a busy domain should: - +On an ESP32 with PSRAM, the first thing to run out is the byte-addressable +internal RAM (`MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT`). Every new task's stack +and every FreeRTOS lock behind a `std::mutex` / `std::condition_variable` +comes from it. A participant that joins, or is recreated on, a domain with many +live peers creates its endpoints while all of those peers answer at once. The +answers queue in lwIP until the engine's receive workers read them: up to +`CONFIG_LWIP_UDP_RECVMBOX_SIZE` datagrams per socket. + +Where each queued datagram's memory comes from depends on the network driver. +The Ethernet drivers `malloc()` a full frame (about 1.5 KB) per received +packet. That is below `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` (4096 by default), +so the frames land in internal RAM. In the QEMU interop suite, a participant +recreated next to a dozen ROS 2 peers lost 8-12 KB of internal RAM per endpoint +this way, against about 1 KB on an empty domain. Eventually creating a task +failed and the device aborted. + +On a busy domain: + +- with PSRAM, set `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` below the frame size + (the QEMU firmware uses 1024) so received frames go to PSRAM; without PSRAM, + keep `CONFIG_LWIP_UDP_RECVMBOX_SIZE` x sockets x 1.5 KB within budget; - keep `CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL` large enough for the tasks and - locks it creates at runtime (the QEMU firmware reserves 64 KB); -- let lwIP allocate from PSRAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP`); + locks the application creates at runtime (the QEMU firmware reserves 64 KB); +- let lwIP allocate from PSRAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP`); on + Wi-Fi it also moves the driver's dynamic receive buffers there; - watch `heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)` rather than the `MALLOC_CAP_INTERNAL` total, which on the ESP32 includes IRAM that neither stacks nor byte accesses can use. diff --git a/components/rtps/include/rtps/communication/PacketInfo.hpp b/components/rtps/include/rtps/communication/PacketInfo.hpp index 9ab16c4aea..1ed8947427 100644 --- a/components/rtps/include/rtps/communication/PacketInfo.hpp +++ b/components/rtps/include/rtps/communication/PacketInfo.hpp @@ -33,7 +33,6 @@ Author: i11 - Embedded Software, RWTH Aachen University #include #include "rtps/common/types.hpp" -#include "rtps/storages/PayloadAllocator.hpp" namespace rtps { @@ -41,7 +40,7 @@ struct PacketInfo { Ip4Port_t srcPort; // TODO Do we need that? std::array destAddr = {0, 0, 0, 0}; Ip4Port_t destPort; - PayloadBytes payload; ///< PSRAM first where configured (PayloadAllocator) + std::vector payload; void copyTriviallyCopyable(const PacketInfo &other) { this->srcPort = other.srcPort; diff --git a/components/rtps/include/rtps/storages/PayloadAllocator.hpp b/components/rtps/include/rtps/storages/PayloadAllocator.hpp deleted file mode 100644 index 76f5caf805..0000000000 --- a/components/rtps/include/rtps/storages/PayloadAllocator.hpp +++ /dev/null @@ -1,101 +0,0 @@ -/* -The MIT License -Copyright (c) 2026 ATDev -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE - -This file is part of the espp embeddedRTPS port. -*/ - -#ifndef RTPS_PAYLOADALLOCATOR_H -#define RTPS_PAYLOADALLOCATOR_H - -#include -#include -#include -#include -#include - -#if defined(ESP_PLATFORM) -#include "esp_heap_caps.h" -#include "sdkconfig.h" -#endif - -namespace rtps { - -/// Allocator for the engine's payload bytes: the history caches' samples, the -/// messages it builds to send and the datagrams it parses. -/// -/// Those buffers are mostly a few hundred bytes to a datagram, below the usual -/// CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL threshold, so a plain malloc() puts -/// them in internal RAM first. On a busy domain they add up: a participant -/// that joins (or restarts into) a domain with a dozen live peers takes every -/// peer's discovery announcements at once, and the internal RAM a task stack -/// or a FreeRTOS lock needs runs out. With CONFIG_RTPS_PAYLOAD_PREFER_PSRAM -/// (default on when PSRAM is enabled) they are allocated from PSRAM first and -/// from internal RAM only when PSRAM cannot satisfy them. Elsewhere (no PSRAM, -/// the option off, the host) this is plain operator new / delete. -template struct PayloadAllocator { - using value_type = T; - - PayloadAllocator() noexcept = default; - template constexpr PayloadAllocator(const PayloadAllocator &) noexcept {} - - T *allocate(std::size_t n) { -#if defined(ESP_PLATFORM) && CONFIG_RTPS_PAYLOAD_PREFER_PSRAM - if (n > static_cast(-1) / sizeof(T)) { - allocation_failed(); - } - void *p = heap_caps_malloc_prefer(n * sizeof(T), 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT, - MALLOC_CAP_DEFAULT); - if (p == nullptr) { - allocation_failed(); - } - return static_cast(p); -#else - return static_cast(::operator new(n * sizeof(T))); -#endif - } - - void deallocate(T *p, std::size_t) noexcept { -#if defined(ESP_PLATFORM) && CONFIG_RTPS_PAYLOAD_PREFER_PSRAM - heap_caps_free(p); -#else - ::operator delete(p); -#endif - } - - template bool operator==(const PayloadAllocator &) const noexcept { return true; } - template bool operator!=(const PayloadAllocator &) const noexcept { return false; } - -private: - [[noreturn]] static void allocation_failed() { - // what operator new does when it cannot allocate: bad_alloc, or (built - // without exceptions) the program ends -#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) - throw std::bad_alloc(); -#else - std::abort(); -#endif - } -}; - -/// The byte vector the engine keeps payloads in (see PayloadAllocator). -using PayloadBytes = std::vector>; - -} // namespace rtps - -#endif // RTPS_PAYLOADALLOCATOR_H diff --git a/components/rtps/include/rtps/storages/PayloadBuffer.hpp b/components/rtps/include/rtps/storages/PayloadBuffer.hpp index 513b707c9a..581aa8007d 100644 --- a/components/rtps/include/rtps/storages/PayloadBuffer.hpp +++ b/components/rtps/include/rtps/storages/PayloadBuffer.hpp @@ -26,12 +26,11 @@ This file is part of the espp embeddedRTPS port. #include #include "rtps/common/types.hpp" -#include "rtps/storages/PayloadAllocator.hpp" namespace rtps { struct PayloadBuffer { - PayloadBytes bytes; ///< PSRAM first where configured (PayloadAllocator) + std::vector bytes; bool isValid() const { return true; } diff --git a/components/rtps/interop/qemu/sdkconfig.defaults b/components/rtps/interop/qemu/sdkconfig.defaults index 5f45a705df..f55eeeeaf1 100644 --- a/components/rtps/interop/qemu/sdkconfig.defaults +++ b/components/rtps/interop/qemu/sdkconfig.defaults @@ -14,7 +14,13 @@ CONFIG_PARTITION_TABLE_OFFSET=0x8000 CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv" CONFIG_SPIRAM=y CONFIG_SPIRAM_USE_MALLOC=y -CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=4096 +# Below an Ethernet frame (~1.5 KB): the openeth driver mallocs one per +# received packet and lwIP holds it until the engine reads the datagram (up to +# LWIP_UDP_RECVMBOX_SIZE per socket). With 4096 those frames sat in internal +# RAM, and a participant recreated next to a dozen live peers (the restart +# case) dropped to ~5 KB of internal RAM while creating its endpoints. Smaller +# allocations (FreeRTOS objects, small engine state) stay internal. +CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=1024 # Keep internal RAM for what must live there. The restart case tears the # participant down and builds a new one while a dozen peers from the earlier # cases are still announcing: the new participant discovers them all at once, diff --git a/doc/en/protocols/rtps.rst b/doc/en/protocols/rtps.rst index 0074d1016c..3cd2de38a1 100644 --- a/doc/en/protocols/rtps.rst +++ b/doc/en/protocols/rtps.rst @@ -281,13 +281,6 @@ menuconfig under ``RTPS`` on ESP32; ``include/rtps/config.hpp`` defaults on host - on (default) - Compile in services + actions (RMI/AMI). Disable to drop that code and its threads on a pure-pub/sub device. - * - ``RTPS_PAYLOAD_PREFER_PSRAM`` - - on when PSRAM is enabled - - Allocate payload bytes (history-cache samples, built messages, parsed - datagrams) from PSRAM first, internal RAM only as a fallback, so a - participant joining a busy domain does not exhaust the internal RAM that - task stacks and FreeRTOS locks need. See the component README, - *Internal RAM on a busy domain*. Relevant Specifications ----------------------- From 276547dae29ee3ecd3483cd05642fabb8a117eed Mon Sep 17 00:00:00 2001 From: William Emfinger Date: Sun, 22 Nov 2026 17:22:56 -0700 Subject: [PATCH 5/5] docs(qemu, rtps): receive buffers, internal RAM and busy-domain considerations QEMU board (README, its docs page, the QEMU guide): how the emulated MAC's driver holds received frames - the DMA receive ring (4 x 1600 B internal by default; a burst longer than it is dropped, RX frame dropped (0x14)) and one malloc()ed 1522-byte buffer per frame until the application reads it, queued up to LWIP_UDP_RECVMBOX_SIZE per socket - why that lands in internal RAM with PSRAM (below ALWAYSINTERNAL), how it fails (a task or lock that cannot be created), what to configure, and that IP reassembly is off by default. RTPS (README and docs page): the busy-domain section now explains the mechanism - four sockets plus dedicated ports, every live peer answering each new endpoint at once, worst when joining or recreating on a running domain - with the symptoms, the options, where to measure, and the per-endpoint RTPSTEST dram markers the QEMU firmware logs. The QEMU firmware's RESERVE_INTERNAL comment no longer blames the proxies (discovery uses fixed pools; it was the queued frames). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01DFjjnq3XCTRAXENSxsCxJU --- components/qemu/README.md | 43 +++++++++++++++ components/rtps/README.md | 52 +++++++++++++------ .../rtps/interop/qemu/sdkconfig.defaults | 12 ++--- doc/en/dev_boards/other/qemu.rst | 5 +- doc/en/protocols/rtps.rst | 31 +++++++++++ doc/en/qemu.rst | 37 +++++++++++++ 6 files changed, 158 insertions(+), 22 deletions(-) diff --git a/components/qemu/README.md b/components/qemu/README.md index 90a7ca80cf..6f1c708941 100644 --- a/components/qemu/README.md +++ b/components/qemu/README.md @@ -68,6 +68,49 @@ MAC has no multicast address filter, so ESP-IDF logs `add mac address to filter not supported` when lwIP joins a group; the frames are received regardless. +### Receive buffers and memory + +The emulated MAC's driver keeps received frames in two places, and both +matter to an application that receives bursts or listens on a busy network: + +- **The DMA receive ring.** `CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM` descriptors + (default 4) of 1600 bytes each, allocated from internal DMA-capable RAM when + the interface starts. In the emulator a burst arrives with no wire time + between frames, so anything longer than the ring is dropped + (`RX frame dropped (0x14)` in the log). A fragmented UDP datagram is one + such burst: a 30 KB datagram is 21 frames back to back. Raise the ring for + that (64 is the maximum, about 100 KB of internal RAM). +- **One heap buffer per received frame.** The driver's receive task copies + each frame out of the ring into a freshly `malloc()`ed 1522-byte buffer and + hands it to lwIP. The buffer is freed only when the application has read the + datagram. Until then it waits in the socket's receive queue: up to + `CONFIG_LWIP_UDP_RECVMBOX_SIZE` datagrams per UDP socket (default 6), + behind `CONFIG_LWIP_TCPIP_RECVMBOX_SIZE` in the lwIP task's own queue, and, + for a fragmented datagram, in IP reassembly (`CONFIG_LWIP_IP_REASS_MAX_PBUFS`). + +On a machine with PSRAM (`idf.py qemu` gives the ESP32 machine 4 MB, `-m 4M`), +1522 bytes is below the default `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` (4096), +so those buffers come from internal RAM first. A deep queue on several sockets +can then hold more internal RAM than the chip has free, and the application +fails somewhere unrelated: creating a task or a FreeRTOS lock, both of which +need internal RAM. To avoid that: + +- with PSRAM, set `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` below the frame size + (1024, for example), so the frame buffers go to PSRAM while smaller + allocations stay internal; +- without PSRAM, size the queues so that queue depth x sockets x 1.5 KB fits + what the application can spare; +- `CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP` moves lwIP's own allocations (pbufs, + reassembly) to PSRAM. It does not move the driver's frame buffers, which are + a plain `malloc()`. + +IP reassembly is off in ESP-IDF's default lwIP configuration +(`CONFIG_LWIP_IP4_REASSEMBLY`): without it, a UDP datagram larger than one +frame is dropped by the stack. The RTPS interop firmware +([`components/rtps/interop/qemu`](../rtps/interop/qemu/sdkconfig.defaults)) +sets all of these for a dozen ROS 2 peers sending fragmented samples, with +the reasoning beside each option. + ## API ```cpp diff --git a/components/rtps/README.md b/components/rtps/README.md index 758e8be73b..a10f30172f 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -226,32 +226,54 @@ it had reached, and rediscovered on the spot. On an ESP32 with PSRAM, the first thing to run out is the byte-addressable internal RAM (`MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT`). Every new task's stack and every FreeRTOS lock behind a `std::mutex` / `std::condition_variable` -comes from it. A participant that joins, or is recreated on, a domain with many -live peers creates its endpoints while all of those peers answer at once. The -answers queue in lwIP until the engine's receive workers read them: up to -`CONFIG_LWIP_UDP_RECVMBOX_SIZE` datagrams per socket. - -Where each queued datagram's memory comes from depends on the network driver. -The Ethernet drivers `malloc()` a full frame (about 1.5 KB) per received -packet. That is below `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` (4096 by default), -so the frames land in internal RAM. In the QEMU interop suite, a participant -recreated next to a dozen ROS 2 peers lost 8-12 KB of internal RAM per endpoint -this way, against about 1 KB on an empty domain. Eventually creating a task -failed and the device aborted. +comes from it, so when it runs out the device fails creating one of those, +far from the cause: `pthread: Failed to create task!` and an abort, or an +abort inside `pthread_cond_init`. + +The cause to look for is received datagrams waiting in lwIP. The engine +listens on four sockets (metatraffic and user traffic, multicast and unicast, +plus one per dedicated endpoint port; see +[Priority scheduling](#priority-scheduling-bands-dedicated-ports-dscp)), +and lwIP holds up to `CONFIG_LWIP_UDP_RECVMBOX_SIZE` datagrams per socket +until the engine's receive workers read them. Where a waiting datagram's +memory comes from depends on the network driver. The Ethernet driver of +QEMU's emulated MAC allocates a 1522-byte buffer per received frame with plain +`malloc()` (see the [QEMU board component](../qemu/README.md#receive-buffers-and-memory)). +That is below `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` (4096 by default), so the +frames land in internal RAM. + +The traffic comes in bursts when a participant creates endpoints on a busy +domain. Every new endpoint is announced to every live peer, and they all +answer at once with discovery data, HEARTBEATs and their history. A +participant that boots before its peers spreads this out, but one that joins, +or is recreated on, a running domain takes it all while it builds its +endpoints. In the QEMU interop suite, a participant recreated next to a dozen +ROS 2 peers lost 8-12 KB of internal RAM per endpoint this way, against about +1 KB on an empty domain. Eventually creating a task failed and the device +aborted. On a busy domain: - with PSRAM, set `CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL` below the frame size - (the QEMU firmware uses 1024) so received frames go to PSRAM; without PSRAM, - keep `CONFIG_LWIP_UDP_RECVMBOX_SIZE` x sockets x 1.5 KB within budget; + (the QEMU firmware uses 1024) so received frames go to PSRAM while small + allocations stay internal; without PSRAM, keep + `CONFIG_LWIP_UDP_RECVMBOX_SIZE` x sockets x 1.5 KB within budget; - keep `CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL` large enough for the tasks and locks the application creates at runtime (the QEMU firmware reserves 64 KB); - let lwIP allocate from PSRAM (`CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP`); on - Wi-Fi it also moves the driver's dynamic receive buffers there; + Wi-Fi this also moves the driver's dynamic receive buffers there; +- create the endpoints right after the participant starts, as one batch, and + measure there: that is where the low point is; - watch `heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)` rather than the `MALLOC_CAP_INTERNAL` total, which on the ESP32 includes IRAM that neither stacks nor byte accesses can use. +The QEMU interop firmware (`interop/qemu`) logs this figure after each +endpoint it creates (`RTPSTEST dram free= min= largest= tasks=`), +on first boot and after its in-process restart, so a regression shows up in +the CI device log. Its `sdkconfig.defaults` explains each of the memory and +lwIP options it sets. + ### Per-limit capacity overrides Every capacity cap in the profile headers can be raised (or lowered) diff --git a/components/rtps/interop/qemu/sdkconfig.defaults b/components/rtps/interop/qemu/sdkconfig.defaults index f55eeeeaf1..b315268248 100644 --- a/components/rtps/interop/qemu/sdkconfig.defaults +++ b/components/rtps/interop/qemu/sdkconfig.defaults @@ -24,12 +24,12 @@ CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL=1024 # Keep internal RAM for what must live there. The restart case tears the # participant down and builds a new one while a dozen peers from the earlier # cases are still announcing: the new participant discovers them all at once, -# and the proxies (small allocations: internal first, see ALWAYSINTERNAL) plus -# lwIP's receive / reassembly buffers (internal-only by default) took the data -# RAM a task stack needs, so creating the publish timer's task failed and the -# device aborted ("pthread: Failed to create task!"; every later case then -# failed with it). lwIP now allocates from PSRAM first, and twice the default -# is reserved for allocations that need internal RAM (FreeRTOS stacks, DMA). +# and the frames queued for it (see ALWAYSINTERNAL above) plus lwIP's +# receive / reassembly buffers (internal-only by default) took the data RAM a +# task stack needs, so creating the publish timer's task failed and the device +# aborted ("pthread: Failed to create task!"; every later case then failed +# with it). lwIP now allocates from PSRAM first, and twice the default is +# reserved for allocations that need internal RAM (FreeRTOS stacks, DMA). CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP=y CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL=65536 diff --git a/doc/en/dev_boards/other/qemu.rst b/doc/en/dev_boards/other/qemu.rst index db5b5c2506..e58a4b1522 100644 --- a/doc/en/dev_boards/other/qemu.rst +++ b/doc/en/dev_boards/other/qemu.rst @@ -17,7 +17,10 @@ three targets the emulator supports (``esp32``, ``esp32c3``, ``esp32s3``). with ``-display none`` the panel driver's first flush waits forever. - **Ethernet**: the OpenCores Ethernet MAC (``initialize_ethernet()``), a real lwIP interface on QEMU's user-mode NAT or on a tap device. Needs - ``CONFIG_ETH_USE_OPENETH``. + ``CONFIG_ETH_USE_OPENETH``. Its driver drops what overflows its small + receive ring and keeps every received frame in a 1522-byte heap buffer until + the application reads it, which matters for bursts and busy networks: see + :ref:`qemu-receive-buffers`. - **SD card** (ESP32 machine only): the SD/MMC host (``initialize_sdcard()``), a FAT volume on the image file passed with ``-drive file=...,if=sd``. diff --git a/doc/en/protocols/rtps.rst b/doc/en/protocols/rtps.rst index 3cd2de38a1..37f6e3d304 100644 --- a/doc/en/protocols/rtps.rst +++ b/doc/en/protocols/rtps.rst @@ -282,6 +282,37 @@ menuconfig under ``RTPS`` on ESP32; ``include/rtps/config.hpp`` defaults on host - Compile in services + actions (RMI/AMI). Disable to drop that code and its threads on a pure-pub/sub device. +Internal RAM on a busy domain +----------------------------- + +On an ESP32 with PSRAM, the byte-addressable internal RAM +(``MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT``) runs out first. Task stacks and +the FreeRTOS locks behind ``std::mutex`` / ``std::condition_variable`` come +from it, so the failure shows up as a task or lock that cannot be created, +far from the cause. + +The cause to look for is received datagrams waiting in lwIP: up to +``CONFIG_LWIP_UDP_RECVMBOX_SIZE`` per socket, on each of the engine's four +sockets (plus one per dedicated port). The Ethernet driver of QEMU's emulated +MAC keeps each frame in a 1522-byte buffer from ``malloc()`` (see +:ref:`qemu-receive-buffers`). That is below +``CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL``, so the frames land in internal RAM. +The traffic peaks when a participant creates its endpoints on a running +domain, because every live peer answers every new endpoint at once. In the +QEMU interop suite, a participant recreated next to a dozen ROS 2 peers lost +8-12 KB of internal RAM per endpoint, against about 1 KB on an empty domain, +until creating a task failed. + +On a busy domain, with PSRAM set ``CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL`` +below the frame size (the QEMU firmware uses 1024); without it, keep queue +depth x sockets x 1.5 KB within budget. Reserve internal RAM for runtime +tasks (``CONFIG_SPIRAM_MALLOC_RESERVE_INTERNAL``) and let lwIP use PSRAM +(``CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP``). Measure +``heap_caps_get_minimum_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT)`` +right after the endpoints are created; the ``MALLOC_CAP_INTERNAL`` total +includes IRAM that stacks cannot use. The QEMU interop firmware logs that +figure after each endpoint, on first boot and after its restart. + Relevant Specifications ----------------------- diff --git a/doc/en/qemu.rst b/doc/en/qemu.rst index 9c64c5bcd1..f01cc6c2f2 100644 --- a/doc/en/qemu.rst +++ b/doc/en/qemu.rst @@ -121,6 +121,43 @@ using a static address on that subnet. The emulated MAC has no multicast address filter (ESP-IDF logs ``add mac address to filter not supported`` when lwIP joins a group); multicast frames are received regardless. +.. _qemu-receive-buffers: + +Receive buffers and memory +-------------------------- + +The emulated MAC's driver keeps received frames in two places: + +- **The DMA receive ring**: ``CONFIG_ETH_OPENETH_DMA_RX_BUFFER_NUM`` + descriptors (default 4) of 1600 bytes, in internal DMA-capable RAM. The + emulator delivers a burst with no wire time between frames, so a burst + longer than the ring is dropped (``RX frame dropped (0x14)`` in the log). A + fragmented UDP datagram is such a burst (30 KB is 21 frames). Raise the ring + for it; the maximum, 64, costs about 100 KB of internal RAM. +- **A heap buffer per frame**: the driver's receive task copies each frame + into a 1522-byte buffer from ``malloc()`` and hands it to lwIP, which frees + it only once the application has read the datagram. Until then it waits in + the socket's receive queue (up to ``CONFIG_LWIP_UDP_RECVMBOX_SIZE`` per UDP + socket, default 6), in the lwIP task's queue + (``CONFIG_LWIP_TCPIP_RECVMBOX_SIZE``) or in IP reassembly. + +With PSRAM (``idf.py qemu`` gives the ESP32 machine 4 MB), 1522 bytes is below +the default ``CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL`` of 4096, so those buffers +come from internal RAM. Deep queues on several sockets can then hold more +internal RAM than is free, and the failure shows up elsewhere: creating a task +or a FreeRTOS lock. With PSRAM, set ``CONFIG_SPIRAM_MALLOC_ALWAYSINTERNAL`` +below the frame size (1024, say); without it, keep queue depth x sockets x +1.5 KB within budget. ``CONFIG_SPIRAM_TRY_ALLOCATE_WIFI_LWIP`` moves lwIP's +own pbufs to PSRAM but not the driver's buffers. IP reassembly +(``CONFIG_LWIP_IP4_REASSEMBLY``) is off by default; without it a UDP datagram +larger than one frame never reaches the application. + +The RTPS interop firmware hit both limits. Fragmented 30 KB samples +overflowed the default ring. After an in-process restart, a dozen live ROS 2 +peers answered every new endpoint at once, and their queued frames used up the +internal RAM until creating a task failed. Its ``sdkconfig.defaults`` sets +each option with the reasoning beside it. + Debugging =========