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
5 changes: 4 additions & 1 deletion .github/workflows/host_sanitizers.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ on:
- "lib/include/espp.hpp"
- "pc/tests/rtps_*"
- "pc/tests/socket_reactor.cpp"
- "pc/tests/socket_receive.cpp"
- "pc/tests/thread_pool.cpp"
- "pc/tests/event_manager.cpp"
- "pc/tests/battery.cpp"
Expand Down Expand Up @@ -64,6 +65,7 @@ on:
- "lib/include/espp.hpp"
- "pc/tests/rtps_*"
- "pc/tests/socket_reactor.cpp"
- "pc/tests/socket_receive.cpp"
- "pc/tests/thread_pool.cpp"
- "pc/tests/event_manager.cpp"
- "pc/tests/battery.cpp"
Expand Down Expand Up @@ -126,7 +128,8 @@ jobs:

- name: Run the unit tests under ${{ matrix.sanitizer }} sanitizer
# Every pc/ test labelled `unit` (pc/CMakeLists.txt): the rtps loopback
# tests, socket_reactor, thread_pool, event_manager, battery, odrive
# tests, socket_reactor, socket_receive (no allocation per received
# datagram / event), thread_pool, event_manager, battery, odrive
# golden. The interop ones need a FastDDS / ROS 2 peer (the docker
# matrix covers them). One at a time (the rtps tests share ports); each
# has a 300 s ctest timeout, generous for the sanitizer's slowdown, so a
Expand Down
19 changes: 19 additions & 0 deletions components/rtps/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,25 @@ foreach(knob ${RTPS_TUNING_KNOBS})
endif()
endforeach()

# Receive buffer per datagram (Kconfig "Receive buffer size"): a nonzero value
# is used as is; 0 (automatic) leaves the profile default (65507 bytes with
# fragmentation, 8 KB otherwise) except when lwIP cannot reassemble IPv4
# fragments, where no datagram longer than one MTU-1500 frame (1472 bytes of
# UDP payload) can arrive from the network - so 1472 (issue #969: each receive
# worker holds one buffer of this size).
if(DEFINED CONFIG_RTPS_RECEIVE_BUFFER_SIZE AND NOT "${CONFIG_RTPS_RECEIVE_BUFFER_SIZE}" STREQUAL ""
AND NOT "${CONFIG_RTPS_RECEIVE_BUFFER_SIZE}" STREQUAL "0")
if(CONFIG_RTPS_RECEIVE_BUFFER_SIZE LESS 1472)
message(WARNING
"CONFIG_RTPS_RECEIVE_BUFFER_SIZE=${CONFIG_RTPS_RECEIVE_BUFFER_SIZE} is below 1472 bytes (one "
"unfragmented datagram on an MTU-1500 link): longer peer messages will be truncated")
endif()
target_compile_definitions(${COMPONENT_LIB} PUBLIC
"RTPS_CFG_RECEIVE_BUFFER_SIZE=${CONFIG_RTPS_RECEIVE_BUFFER_SIZE}")
elseif(NOT CONFIG_RTPS_ENABLE_FRAGMENTATION AND NOT CONFIG_LWIP_IP4_REASSEMBLY)
target_compile_definitions(${COMPONENT_LIB} PUBLIC "RTPS_CFG_RECEIVE_BUFFER_SIZE=1472")
endif()
Comment thread
finger563 marked this conversation as resolved.
Resolved

# Eviction of an unused remote participant on a full pool (Kconfig bool,
# default on): only the off state is passed through, the profiles default to on.
if(DEFINED CONFIG_RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS AND NOT CONFIG_RTPS_SPDP_EVICT_UNUSED_PARTICIPANTS)
Expand Down
20 changes: 20 additions & 0 deletions components/rtps/Kconfig
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,26 @@ menu "RTPS"
bounded by RTPS_MAX_SAMPLE_SIZE (256 KB on the embedded profile) and
the participant's max payload size rises accordingly.

config RTPS_RECEIVE_BUFFER_SIZE
int "Receive buffer size, bytes (0 = automatic)"
default 0
range 0 65507
help
The most of one UDP datagram the transport reads. The socket
reactor keeps one buffer of this size per receive worker (reused,
never allocated per datagram); a longer datagram is truncated, so
it must cover the largest datagram a peer can deliver.

0 picks it automatically: 65507 bytes (the largest UDP payload)
with fragmentation enabled (a peer's DATA_FRAG datagrams); otherwise 1472 bytes when lwIP IPv4
reassembly (LWIP_IP4_REASSEMBLY) is off - the largest datagram an
MTU-1500 link delivers unfragmented - and 8 KB when it is on.

Set it larger only if this device receives unfragmented samples
bigger than one link MTU: with IPv4 reassembly on, or from another
participant on the same chip (lwIP loops those back without
fragmenting them). Each receive worker holds one such buffer.

config RTPS_ENABLE_RPC
bool "Enable RPC: services + actions (RMI/AMI)"
default y
Expand Down
1 change: 1 addition & 0 deletions components/rtps/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@ via `include/rtps/config.hpp`.
| `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_ENABLE_RPC` | on (default) | Compile in services + actions (RMI/AMI). Disable to drop that code + its threads on a pure-pub/sub device. |
| `RTPS_RECEIVE_BUFFER_SIZE` | 0 = automatic (1472 on ESP32 without lwIP IPv4 reassembly; 8 KB with it; 65507 bytes, the largest UDP payload, with fragmentation) | The most of one UDP datagram the transport reads. The socket reactor keeps one buffer of this size per receive worker and reuses it, so receiving never allocates per datagram. A longer datagram is truncated: raise it only for unfragmented samples bigger than one MTU (IPv4 reassembly on, or another participant on the same chip). |
| `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)). |
| `RTPS_THREAD_POOL_READER_STACKSIZE` | 0 = profile default (8192 on ESP32) | Stack of those tasks (they also run every reader and matched callback). ESP only: a host `std::thread` uses the platform default stack. |
Expand Down
2 changes: 2 additions & 0 deletions components/rtps/include/rtps/communication/EsppTransport.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,8 @@ class EsppTransport : public espp::BaseComponent {
/// Set under m_pendingMutex whenever m_pendingByKey is non-empty; the retry
/// task waits for it (through its own mutex/cv, published below).
std::atomic<bool> m_pendingWork{false};
/// Datagrams dropped because they did not fit Config::RECEIVE_BUFFER_SIZE.
mutable std::atomic<uint32_t> m_truncatedDatagrams{0};
static constexpr std::chrono::milliseconds RETRY_PERIOD{20};
std::unique_ptr<espp::Task> m_retryTask;
bool m_retryTaskRunning{false}; ///< start() succeeded; else rejected jobs are dropped
Expand Down
24 changes: 24 additions & 0 deletions components/rtps/include/rtps/config.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,30 @@ Author: i11 - Embedded Software, RWTH Aachen University
#endif
#endif

// Receive buffer per datagram (bytes): the most of one UDP datagram the
// transport reads (into a buffer pooled by the socket reactor: one per receive
// worker, reused, never allocated per datagram). A longer datagram is
// truncated, so this must cover the largest datagram a peer can deliver. With
// fragmentation a peer (e.g. FastDDS / ROS 2) sends DATA_FRAG datagrams of up
// to the largest UDP payload (65507 bytes); without it the default stays 8 KB. On ESP-IDF the
// component sets RTPS_CFG_RECEIVE_BUFFER_SIZE: menuconfig RTPS -> Receive buffer size, whose
// automatic value (0) is 1472 when lwIP cannot reassemble IPv4 fragments (the
// largest datagram an MTU-1500 link then delivers) - issue #969.
#ifndef RTPS_CFG_RECEIVE_BUFFER_SIZE
#if defined(RTPS_ENABLE_FRAGMENTATION)
#define RTPS_CFG_RECEIVE_BUFFER_SIZE 65507u // the largest UDP payload over IPv4
#else
#define RTPS_CFG_RECEIVE_BUFFER_SIZE (8u * 1024u)
#endif
#endif
namespace rtps {
namespace Config {
inline constexpr unsigned int RECEIVE_BUFFER_SIZE = RTPS_CFG_RECEIVE_BUFFER_SIZE; // byte
static_assert(RECEIVE_BUFFER_SIZE > 0 && RECEIVE_BUFFER_SIZE <= 65507,
"RTPS_CFG_RECEIVE_BUFFER_SIZE must be 1..65507 bytes (one IPv4 UDP datagram)");
} // namespace Config
} // namespace rtps

// Storage POLICY, orthogonal to the limits profile selected above. Dynamic
// (heap-backed, grow-on-full std::deque) storage is the default on host/PC
// builds; on ESP it is an explicit opt-in (Kconfig RTPS_STORAGE_DYNAMIC ->
Expand Down
29 changes: 19 additions & 10 deletions components/rtps/src/communication/EsppTransport.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -212,16 +212,14 @@ bool EsppTransport::startReceiver(Channel &channel, Ip4Port_t receivePort,
// for traffic sent from this socket (dedicated endpoint ports).
receive_config.band = options.band;
receive_config.dscp = options.dscp;
#ifdef RTPS_ENABLE_FRAGMENTATION
// With fragmentation enabled a peer (e.g. FastDDS/ROS 2) may send DATA_FRAG
// fragments as large as a full UDP datagram (~64 KB), so the per-datagram read
// buffer must accept any single datagram or large fragments get truncated on
// receive. The ESP32 default build (fragmentation off) keeps the small 8 KB
// buffer, paying nothing for this.
receive_config.buffer_size = 64 * 1024;
#else
receive_config.buffer_size = 1024 * 8;
#endif
// The most of one datagram to read (Config::RECEIVE_BUFFER_SIZE): 65507 bytes
// (the largest UDP payload) with fragmentation (a peer's DATA_FRAG datagrams), 8 KB without, and
// on ESP-IDF 1472 by default when lwIP cannot reassemble IPv4 fragments (menuconfig RTPS ->
// Receive buffer size). The reactor reads into pooled buffers of this size - one per receive
// worker, sized at registration - so receiving does not allocate per datagram (issue #969). One
// spare byte: a datagram that fills it was longer than RECEIVE_BUFFER_SIZE and arrived truncated,
// so onReceive() drops it (and says so) rather than parse a cut-off message.
receive_config.buffer_size = Config::RECEIVE_BUFFER_SIZE + 1;
receive_config.on_receive_callback =
[this, receivePort](std::vector<uint8_t> &data,
const espp::Socket::Info &sender) -> std::optional<std::vector<uint8_t>> {
Expand Down Expand Up @@ -291,6 +289,17 @@ void EsppTransport::onReceive(Ip4Port_t receivePort, std::vector<uint8_t> &data,
if (m_rxCallback == nullptr) {
return;
}
if (data.size() > Config::RECEIVE_BUFFER_SIZE) {
// Longer than the receive buffer: the datagram was truncated. Drop it, and
// say so on the first one and every 100th after.
const auto truncated = ++m_truncatedDatagrams;
if (truncated == 1 || truncated % 100 == 0) {
logger_.warn("Dropped {} datagram(s) longer than the {}-byte receive buffer (port {}); "
"raise RTPS_RECEIVE_BUFFER_SIZE (menuconfig RTPS -> Receive buffer size)",
truncated, Config::RECEIVE_BUFFER_SIZE, receivePort);
}
return;
}

Ip4AddressBytes remoteAddress{0, 0, 0, 0};
if (!parseIp4Address(sender.address, remoteAddress)) {
Expand Down
6 changes: 5 additions & 1 deletion components/socket/include/socket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ typedef SOCKET sock_type_t;
typedef int sock_type_t;
#endif

#include <atomic>
#include <functional>
#include <optional>
#include <string>
Expand Down Expand Up @@ -361,7 +362,10 @@ class Socket : public BaseComponent {
static constexpr int address_family_{AF_INET};
static constexpr int ip_protocol_{IPPROTO_IP};

sock_type_t socket_;
/// The descriptor. Atomic because closing a socket from another thread is
/// how a blocked receive is interrupted (UdpSocket::stop_receiving() calls
/// cleanup() while its task may be inside receive()).
std::atomic<sock_type_t> socket_;
};
} // namespace espp

Expand Down
62 changes: 55 additions & 7 deletions components/socket/include/socket_reactor.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,12 @@ class SocketReactor : public BaseComponent {
* socket's handling is dispatched at, and its dscp field (if set) is
* applied to the socket via IP_TOS here (best-effort, marks
* transmitted packets - see UdpSocket::ReceiveConfig).
* @note Steady-state receive does not allocate: datagrams are read into
* buffers the reactor pools and reuses (sized here, at registration:
* one of buffer_size bytes per pool worker), and the callback is handed
* that buffer, which returns to the pool when the callback returns.
* Copy what must outlive the callback; moving out of it is allowed, but
* that buffer then has to be grown again.
* @param socket A UdpSocket to bind and receive on. Must outlive the
* registration (call remove() before destroying it).
* @param receive_config Port / multicast / buffer_size / callback / band /
Expand Down Expand Up @@ -205,7 +211,9 @@ class SocketReactor : public BaseComponent {
* automatically unregisters the stream.
* @param connection A connected TcpSocket (e.g. from add_tcp_listener's
* callback or TcpSocket::connect). Must outlive the registration.
* @param on_data Callback given the connection and the bytes read.
* @param on_data Callback given the connection and the bytes read. The bytes
* are in a pooled buffer that is reused once the callback returns
* (see add_udp_receiver): copy what must outlive the call.
* @param buffer_size Max bytes to read per readable event.
* @param on_close Optional callback fired once when the peer closes.
* @param band Priority band to dispatch read handling at (see espp::QosBand;
Expand Down Expand Up @@ -286,12 +294,15 @@ class SocketReactor : public BaseComponent {

struct Entry {
sock_type_t fd{static_cast<sock_type_t>(-1)}; ///< Watched file descriptor.
ReadHandler handler; ///< Handler run on the pool.
QosBand band{QosBand::Normal}; ///< Priority band for dispatch.
bool armed{true}; ///< In the select set (not currently dispatched).
bool in_flight{false}; ///< A pool job is currently running the handler.
bool remove_requested{false}; ///< remove() was called while in-flight.
RemovedCallback on_removed{}; ///< Fired (unlocked) when the entry is erased.
/// Handler run on the pool. Shared so dispatch() can take a reference to it
/// (an atomic count) instead of copying the std::function, which allocates
/// whenever the handler's captures outgrow its small buffer.
std::shared_ptr<const ReadHandler> handler;
QosBand band{QosBand::Normal}; ///< Priority band for dispatch.
bool armed{true}; ///< In the select set (not currently dispatched).
bool in_flight{false}; ///< A pool job is currently running the handler.
bool remove_requested{false}; ///< remove() was called while in-flight.
RemovedCallback on_removed{}; ///< Fired (unlocked) when the entry is erased.
};

/// Validate an fd for registration: must be valid and (for the select()
Expand Down Expand Up @@ -325,6 +336,43 @@ class SocketReactor : public BaseComponent {
mutable std::mutex mutex_; ///< Guards entries_ and next_id_.
std::map<Id, Entry> entries_;
Id next_id_{INVALID_ID};
/// Entries found readable by one loop iteration (loop thread only): reused,
/// so an iteration does not allocate.
std::vector<std::pair<Id, QosBand>> ready_;

/// Check a receive buffer out of the pool (allocating only when more handlers
/// run at once than ever before), with at least @p capacity bytes reserved.
std::unique_ptr<std::vector<uint8_t>> acquire_buffer(size_t capacity);
/// Return a buffer to the pool (its capacity is kept).
void release_buffer(std::unique_ptr<std::vector<uint8_t>> buffer);
/// Make the pool hold one buffer of at least @p capacity bytes per pool
/// worker. Called at registration so traffic finds them ready.
void reserve_buffers(size_t capacity);

/// A pooled receive buffer for the duration of one handler run.
class BufferLease {
public:
BufferLease(SocketReactor &reactor, size_t capacity)
: reactor_(reactor)
, buffer_(reactor.acquire_buffer(capacity)) {}
~BufferLease() { reactor_.release_buffer(std::move(buffer_)); }
BufferLease(const BufferLease &) = delete;
BufferLease &operator=(const BufferLease &) = delete;
std::vector<uint8_t> &data() { return *buffer_; }

private:
SocketReactor &reactor_;
std::unique_ptr<std::vector<uint8_t>> buffer_;
};

/// Receive buffers shared by the UDP / TCP handlers: one is checked out per
/// running handler and returned after, so the pool only ever holds as many as
/// handlers have run at once (about one per pool worker), not one per
/// registration, and their capacity only grows. Steady-state dispatch never
/// allocates.
std::mutex buffers_mutex_;
std::vector<std::unique_ptr<std::vector<uint8_t>>> free_buffers_;
size_t buffer_count_{0}; ///< buffers in existence (free or checked out)

std::atomic<sock_type_t> wakeup_recv_{
static_cast<sock_type_t>(-1)}; ///< Loopback UDP socket in the select set. Atomic so wake()
Expand Down
5 changes: 4 additions & 1 deletion components/socket/include/tcp_socket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,10 @@ class TcpSocket : public Socket {
* @brief Call read on the socket, assuming it has already been configured
* appropriately.
*
* @param data Vector of bytes of received data.
* @param data Vector of bytes of received data: received straight into, then
* resized to the bytes received (cleared on failure). Its capacity is
* kept, so passing the same vector to every call allocates nothing
* once it holds max_num_bytes.
* @param max_num_bytes Maximum number of bytes to receive.
* @return true if successfully received, false otherwise.
*/
Expand Down
8 changes: 7 additions & 1 deletion components/socket/include/udp_socket.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,11 @@ class UdpSocket : public Socket {
* configured appropriately.
*
* @param max_num_bytes Maximum number of bytes to receive.
* @param data Vector of bytes of received data.
* @param data Vector of bytes of received data: the datagram is received
* straight into it and it is then resized to the bytes received
* (cleared on failure). Its capacity is kept, so passing the same
* vector to every call allocates nothing once it holds
* max_num_bytes.
* @param remote_info Socket::Info containing the sender's information. This
* will be populated with the information about the sender.
* @return true if successfully received, false otherwise.
Expand Down Expand Up @@ -219,5 +223,7 @@ class UdpSocket : public Socket {

std::unique_ptr<Task> task_;
receive_callback_fn server_receive_callback_;
std::vector<uint8_t> server_receive_data_; ///< reused by the receive task for every datagram
Socket::Info server_sender_info_; ///< reused by the receive task for every datagram
};
} // namespace espp
12 changes: 9 additions & 3 deletions components/socket/src/socket.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -514,9 +514,12 @@ std::string Socket::error_string(int err) const {

void Socket::cleanup() {
if (is_valid()) {
auto socket_fd = socket_;
// claim the descriptor: of two threads cleaning up at once, only one closes it
#ifdef _WIN32
socket_ = INVALID_SOCKET;
const sock_type_t socket_fd = socket_.exchange(INVALID_SOCKET);
if (socket_fd == INVALID_SOCKET) {
return;
}
int status = shutdown(socket_fd, SD_BOTH);
if (status != 0) {
int err = WSAGetLastError();
Expand All @@ -528,7 +531,10 @@ void Socket::cleanup() {
logger_.debug("close failed: {}", error_string(WSAGetLastError()));
}
#else
socket_ = -1;
const sock_type_t socket_fd = socket_.exchange(-1);
if (socket_fd < 0) {
return;
}
int status = shutdown(socket_fd, SHUT_RDWR);
if (status != 0) {
int err = errno;
Expand Down
Loading
Loading