Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 43 additions & 0 deletions components/qemu/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
53 changes: 53 additions & 0 deletions components/rtps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,59 @@ 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, 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, 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 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 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 <endpoint> 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)
Expand Down
17 changes: 17 additions & 0 deletions components/rtps/interop/qemu/main/rtps_qemu.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,15 @@ 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, 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 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;
Expand Down Expand Up @@ -199,6 +208,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_";
Expand All @@ -208,6 +218,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<StringMsg> subscriber(participant, {
.topic = "rt/qemu_rx",
.type_name = type_name,
Expand All @@ -219,11 +230,13 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a
msg.data);
},
});
log_dram(logger, "subscriber");
espp::Publisher<StringMsg> be_publisher(participant, {
.topic = "rt/qemu_be_tx",
.type_name = type_name,
.reliability = Reliability::BEST_EFFORT,
});
log_dram(logger, "be_publisher");
espp::Subscriber<StringMsg> be_subscriber(participant,
{
.topic = "rt/qemu_be_rx",
Expand All @@ -237,6 +250,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<StringMsg> big_subscriber(
participant, {
.topic = "rt/qemu_big",
Expand All @@ -254,6 +268,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<AddReq, AddResp> add_service(
participant, {
Expand Down Expand Up @@ -290,6 +305,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<FibGoal, FibResult, FibFeedback> fib_action(
participant, {
.action = "/qemu_fibonacci",
Expand Down Expand Up @@ -328,6 +344,7 @@ static void run_participant(espp::Logger &logger, const std::string &interface_a
#endif

log_mem_heap(logger, "endpoints");
log_dram(logger, "endpoints");

// Periodic publishers: one reliable, one best-effort
uint32_t counter = 0;
Expand Down
20 changes: 13 additions & 7 deletions components/rtps/interop/qemu/sdkconfig.defaults
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,22 @@ 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,
# 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

Expand Down
5 changes: 4 additions & 1 deletion doc/en/dev_boards/other/qemu.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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``.

Expand Down
31 changes: 31 additions & 0 deletions doc/en/protocols/rtps.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
-----------------------

Expand Down
37 changes: 37 additions & 0 deletions doc/en/qemu.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
=========

Expand Down
Loading