diff --git a/.github/workflows/host_sanitizers.yml b/.github/workflows/host_sanitizers.yml index a30794b15e..4d1f3d6e6b 100644 --- a/.github/workflows/host_sanitizers.yml +++ b/.github/workflows/host_sanitizers.yml @@ -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" @@ -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" @@ -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 diff --git a/components/rtps/CMakeLists.txt b/components/rtps/CMakeLists.txt index 68b933aac7..14409898fa 100644 --- a/components/rtps/CMakeLists.txt +++ b/components/rtps/CMakeLists.txt @@ -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() + # 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) diff --git a/components/rtps/Kconfig b/components/rtps/Kconfig index 3c8c5ca531..cd828d0aac 100644 --- a/components/rtps/Kconfig +++ b/components/rtps/Kconfig @@ -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 diff --git a/components/rtps/README.md b/components/rtps/README.md index a10f30172f..3336d31aaf 100644 --- a/components/rtps/README.md +++ b/components/rtps/README.md @@ -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. | diff --git a/components/rtps/include/rtps/communication/EsppTransport.hpp b/components/rtps/include/rtps/communication/EsppTransport.hpp index 311278e750..307d0df113 100644 --- a/components/rtps/include/rtps/communication/EsppTransport.hpp +++ b/components/rtps/include/rtps/communication/EsppTransport.hpp @@ -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 m_pendingWork{false}; + /// Datagrams dropped because they did not fit Config::RECEIVE_BUFFER_SIZE. + mutable std::atomic m_truncatedDatagrams{0}; static constexpr std::chrono::milliseconds RETRY_PERIOD{20}; std::unique_ptr m_retryTask; bool m_retryTaskRunning{false}; ///< start() succeeded; else rejected jobs are dropped diff --git a/components/rtps/include/rtps/config.hpp b/components/rtps/include/rtps/config.hpp index 30dfc3c2d3..c2c0279c5b 100644 --- a/components/rtps/include/rtps/config.hpp +++ b/components/rtps/include/rtps/config.hpp @@ -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 -> diff --git a/components/rtps/src/communication/EsppTransport.cpp b/components/rtps/src/communication/EsppTransport.cpp index a459b93bbd..96278de712 100644 --- a/components/rtps/src/communication/EsppTransport.cpp +++ b/components/rtps/src/communication/EsppTransport.cpp @@ -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 &data, const espp::Socket::Info &sender) -> std::optional> { @@ -291,6 +289,17 @@ void EsppTransport::onReceive(Ip4Port_t receivePort, std::vector &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)) { diff --git a/components/socket/include/socket.hpp b/components/socket/include/socket.hpp index 72133fe05c..2281ed61bd 100644 --- a/components/socket/include/socket.hpp +++ b/components/socket/include/socket.hpp @@ -18,6 +18,7 @@ typedef SOCKET sock_type_t; typedef int sock_type_t; #endif +#include #include #include #include @@ -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 socket_; }; } // namespace espp diff --git a/components/socket/include/socket_reactor.hpp b/components/socket/include/socket_reactor.hpp index 1a44bbd509..119ffb8105 100644 --- a/components/socket/include/socket_reactor.hpp +++ b/components/socket/include/socket_reactor.hpp @@ -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 / @@ -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; @@ -286,12 +294,15 @@ class SocketReactor : public BaseComponent { struct Entry { sock_type_t fd{static_cast(-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 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() @@ -325,6 +336,43 @@ class SocketReactor : public BaseComponent { mutable std::mutex mutex_; ///< Guards entries_ and next_id_. std::map 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> 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> acquire_buffer(size_t capacity); + /// Return a buffer to the pool (its capacity is kept). + void release_buffer(std::unique_ptr> 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 &data() { return *buffer_; } + + private: + SocketReactor &reactor_; + std::unique_ptr> 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>> free_buffers_; + size_t buffer_count_{0}; ///< buffers in existence (free or checked out) std::atomic wakeup_recv_{ static_cast(-1)}; ///< Loopback UDP socket in the select set. Atomic so wake() diff --git a/components/socket/include/tcp_socket.hpp b/components/socket/include/tcp_socket.hpp index 5a5aca2d30..c7dbbd994d 100644 --- a/components/socket/include/tcp_socket.hpp +++ b/components/socket/include/tcp_socket.hpp @@ -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. */ diff --git a/components/socket/include/udp_socket.hpp b/components/socket/include/udp_socket.hpp index 60dd413cb2..76bafb2262 100644 --- a/components/socket/include/udp_socket.hpp +++ b/components/socket/include/udp_socket.hpp @@ -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. @@ -219,5 +223,7 @@ class UdpSocket : public Socket { std::unique_ptr task_; receive_callback_fn server_receive_callback_; + std::vector 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 diff --git a/components/socket/src/socket.cpp b/components/socket/src/socket.cpp index b178d6bc68..bd7454c30e 100644 --- a/components/socket/src/socket.cpp +++ b/components/socket/src/socket.cpp @@ -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(); @@ -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; diff --git a/components/socket/src/socket_reactor.cpp b/components/socket/src/socket_reactor.cpp index 24a5140ed2..35ed398395 100644 --- a/components/socket/src/socket_reactor.cpp +++ b/components/socket/src/socket_reactor.cpp @@ -2,6 +2,7 @@ #include #include +#include #include #include @@ -170,10 +171,58 @@ SocketReactor::Id SocketReactor::allocate_id() { return next_id_; } +std::unique_ptr> SocketReactor::acquire_buffer(size_t capacity) { + std::unique_ptr> buffer; + { + std::lock_guard lock(buffers_mutex_); + if (!free_buffers_.empty()) { + buffer = std::move(free_buffers_.back()); + free_buffers_.pop_back(); + } else { + // More handlers are running at once than ever before: one more buffer + // (and room to return it), the only time a dispatch allocates. + ++buffer_count_; + free_buffers_.reserve(buffer_count_); + } + } + if (!buffer) { + buffer = std::make_unique>(); + } + if (buffer->capacity() < capacity) { + buffer->reserve(capacity); + } + return buffer; +} + +void SocketReactor::release_buffer(std::unique_ptr> buffer) { + buffer->clear(); // keeps the capacity + std::lock_guard lock(buffers_mutex_); + free_buffers_.push_back(std::move(buffer)); // capacity reserved in acquire_buffer +} + +void SocketReactor::reserve_buffers(size_t capacity) { + // As many buffers as handlers can run at once (one per pool worker), each + // able to hold `capacity` bytes. A buffer checked out right now is grown the + // next time it is acquired instead. + const size_t wanted = std::max(1, pool_ ? pool_->worker_count() : 1); + std::lock_guard lock(buffers_mutex_); + while (buffer_count_ < wanted) { + free_buffers_.push_back(std::make_unique>()); + ++buffer_count_; + } + free_buffers_.reserve(buffer_count_); + for (auto &buffer : free_buffers_) { + if (buffer->capacity() < capacity) { + buffer->reserve(capacity); + } + } +} + void SocketReactor::insert_entry(Id id, sock_type_t fd, ReadHandler handler, QosBand band) { { std::lock_guard lock(mutex_); - entries_[id] = Entry{.fd = fd, .handler = std::move(handler), .band = band}; + entries_[id] = Entry{ + .fd = fd, .handler = std::make_shared(std::move(handler)), .band = band}; } wake(); // interrupt select() so the new fd is picked up } @@ -235,8 +284,14 @@ SocketReactor::add_udp_receiver(espp::UdpSocket &socket, static_cast(receive_config.dscp.value()), receive_config.port); } } + // Every datagram is read into a buffer checked out of the reactor's pool and + // returned after the callback, so steady-state receive allocates nothing + // (issue #969). Size the pool now, at registration, rather than in a worker + // in the middle of traffic. + reserve_buffers(buffer_size); auto handler = [this, &socket, callback, buffer_size]() { - std::vector data; + BufferLease lease(*this, buffer_size); + auto &data = lease.data(); Socket::Info sender; if (!socket.receive(buffer_size, data, sender)) { // Transient (e.g. spurious wakeup) - the socket will be re-armed and we @@ -287,8 +342,11 @@ SocketReactor::Id SocketReactor::add_tcp_stream(espp::TcpSocket &connection, } // Reserve the id first so the handler can unregister itself on disconnect. Id id = allocate_id(); + // Reads go into a pooled buffer (see add_udp_receiver). + reserve_buffers(buffer_size); auto handler = [this, &connection, on_data, on_close, buffer_size, id]() { - std::vector data; + BufferLease lease(*this, buffer_size); + auto &data = lease.data(); if (connection.receive(data, buffer_size)) { if (on_data) { on_data(connection, data); @@ -385,25 +443,25 @@ void SocketReactor::dispatch(SocketReactor::Id id) { ~CountGuard() { --count; } } count_guard{in_flight_count_}; - ReadHandler handler; + std::shared_ptr handler; { std::lock_guard lock(mutex_); auto it = entries_.find(id); if (it == entries_.end()) { return; // removed before we got here } - handler = it->second.handler; // copy so we can run it unlocked + handler = it->second.handler; // share (not copy) so we can run it unlocked } // Run the user handler without holding the lock (it may call back into the // reactor, block on a mutex, etc.). Mark the thread so a stop() invoked from // within the handler is detected rather than deadlocking, and never let a // handler exception escape into the pool worker (it would kill the worker and // leave the entry stuck in_flight). - if (handler) { + if (handler && *handler) { DispatchGuard guard; #if defined(__cpp_exceptions) && __cpp_exceptions try { - handler(); + (*handler)(); } catch (const std::exception &e) { logger_.error("Exception in reactor handler: {}", e.what()); } catch (...) { @@ -413,7 +471,7 @@ void SocketReactor::dispatch(SocketReactor::Id id) { // C++ exceptions are disabled (e.g. the ESP-IDF default), so a throwing // handler would abort regardless; call it directly. The RAII CountGuard // still keeps in_flight_count_ consistent for normal returns. - handler(); + (*handler)(); #endif } bool wake_needed = false; @@ -491,10 +549,15 @@ bool SocketReactor::loop_iteration(std::mutex &, std::condition_variable &, bool } // Collect readable entries, disarming each so it is not dispatched again - // until its handler completes. - std::vector> ready; + // until its handler completes. ready_ is reused (loop thread only) and only + // grows when the number of registrations does. + auto &ready = ready_; + ready.clear(); { std::lock_guard lock(mutex_); + if (ready.capacity() < entries_.size()) { + ready.reserve(entries_.size()); + } for (auto &[id, entry] : entries_) { if (entry.armed && !entry.in_flight && Socket::is_valid_fd(entry.fd) && (FD_ISSET(entry.fd, &readfds) || FD_ISSET(entry.fd, &exceptfds))) { @@ -505,11 +568,14 @@ bool SocketReactor::loop_iteration(std::mutex &, std::condition_variable &, bool } } - // Dispatch in band order (most urgent first; stable, so same-band sockets - // keep their registration order). Submitting urgent sockets first also means - // they win the remaining pool slots when the pool is nearly saturated. - std::stable_sort(ready.begin(), ready.end(), - [](const auto &a, const auto &b) { return a.second < b.second; }); + // Dispatch in band order (most urgent first; same-band sockets keep their + // registration order, i.e. id order - entries_ is ordered by id, so this is + // the order stable_sort by band gave). std::sort, unlike std::stable_sort, + // never allocates a temporary buffer. Submitting urgent sockets first also + // means they win the remaining pool slots when the pool is nearly saturated. + std::sort(ready.begin(), ready.end(), [](const auto &a, const auto &b) { + return a.second != b.second ? a.second < b.second : a.first < b.first; + }); for (const auto &[id, band] : ready) { ++in_flight_count_; @@ -557,6 +623,19 @@ void SocketReactor::wake() { } bool SocketReactor::create_wakeup_socket() { +#if defined(_WIN32) + // The wakeup socket is a raw ::socket(), and a reactor may be started before + // any espp::Socket exists, so Winsock may not be started yet (Socket's + // constructor starts it). WSAStartup is reference-counted: calling it here + // as well is harmless. + static std::once_flag winsock_once; + std::call_once(winsock_once, [this]() { + WSADATA wsa_data; + if (int err = WSAStartup(MAKEWORD(2, 2), &wsa_data); err != 0) { + logger_.error("WSAStartup failed: {}", err); + } + }); +#endif const sock_type_t fd = ::socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); if (!Socket::is_valid_fd(fd)) { logger_.error("Could not create wakeup socket"); diff --git a/components/socket/src/tcp_socket.cpp b/components/socket/src/tcp_socket.cpp index 26473de6ed..83263dc1b4 100644 --- a/components/socket/src/tcp_socket.cpp +++ b/components/socket/src/tcp_socket.cpp @@ -79,7 +79,11 @@ bool TcpSocket::transmit(std::span data, const TransmitConfig &tr } // write logger_.info("Client sending {} bytes", data.size()); - int num_bytes_sent = write(socket_, data.data(), data.size()); + // send(), not write(): on Windows write() is the C runtime's file-descriptor + // write, which rejects a Winsock SOCKET as an invalid parameter and aborts. + int num_bytes_sent = + ::send(socket_.load(std::memory_order_relaxed), reinterpret_cast(data.data()), + static_cast(data.size()), 0); if (num_bytes_sent < 0) { logger_.error("Error occurred during sending: {}", error_string()); // update our connection state here since remote end was likely closed... @@ -114,14 +118,14 @@ bool TcpSocket::transmit(std::span data, const TransmitConfig &tr } bool TcpSocket::receive(std::vector &data, size_t max_num_bytes) { - // make some space for received data - put it on the heap so that our - // stack usage doesn't change depending on max_num_bytes - std::unique_ptr receive_buffer(new uint8_t[max_num_bytes]()); - int num_bytes_received = receive(receive_buffer.get(), max_num_bytes); + // Receive straight into the caller's vector, then shrink it to what arrived: + // no separate buffer and no copy, and a vector reused across calls keeps its + // capacity, so it allocates nothing once it holds max_num_bytes. + data.resize(max_num_bytes); + size_t num_bytes_received = receive(data.data(), max_num_bytes); + data.resize(num_bytes_received); if (num_bytes_received > 0) { - logger_.info("Received {} bytes", num_bytes_received); - uint8_t *data_ptr = receive_buffer.get(); - data.assign(data_ptr, data_ptr + num_bytes_received); + logger_.debug("Received {} bytes", num_bytes_received); return true; } return false; @@ -136,13 +140,17 @@ size_t TcpSocket::receive(uint8_t *data, size_t max_num_bytes) { logger_.error("Socket not connected, cannot receive."); return 0; } - logger_.info("Receiving up to {} bytes", max_num_bytes); + logger_.debug("Receiving up to {} bytes", max_num_bytes); // now actually read data from the socket - int num_bytes_received = ::recv(socket_, reinterpret_cast(data), max_num_bytes, 0); + int num_bytes_received = ::recv(socket_.load(std::memory_order_relaxed), + reinterpret_cast(data), max_num_bytes, 0); // if we didn't receive anything return false and don't do anything else if (num_bytes_received < 0) { - // if we got an error, log it and return 0 - logger_.debug("Receive failed: {}", error_string()); + // if we got an error, log it and return 0 (error_string() allocates: only + // build it when it would be printed) + if (logger_.get_verbosity() <= espp::Logger::Verbosity::DEBUG) { + logger_.debug("Receive failed: {}", error_string()); + } return 0; } else if (num_bytes_received == 0) { logger_.warn("Remote socket closed!"); diff --git a/components/socket/src/udp_socket.cpp b/components/socket/src/udp_socket.cpp index b0b38cbfdb..c94252f689 100644 --- a/components/socket/src/udp_socket.cpp +++ b/components/socket/src/udp_socket.cpp @@ -2,9 +2,36 @@ #include +#if !defined(_WIN32) && !defined(ESP_PLATFORM) +#include +#endif + using namespace espp; namespace { +// Wait up to `timeout` for `fd` to become readable: > 0 readable (or in error, +// which the following receive reports), 0 timed out, < 0 the wait failed. +// poll() on POSIX hosts, where a valid descriptor may be >= FD_SETSIZE and +// FD_SET would write outside its fd_set; select() on Windows (an fd_set holds +// socket handles, not bits) and on ESP-IDF (lwIP descriptors are always below +// its FD_SETSIZE). +int wait_readable(sock_type_t fd, std::chrono::milliseconds timeout) { +#if defined(_WIN32) || defined(ESP_PLATFORM) + fd_set readfds; + FD_ZERO(&readfds); + FD_SET(fd, &readfds); + struct timeval tv; + tv.tv_sec = static_cast(timeout.count() / 1000); + tv.tv_usec = static_cast((timeout.count() % 1000) * 1000); + return ::select(static_cast(fd) + 1, &readfds, nullptr, nullptr, &tv); +#else + struct pollfd pfd {}; + pfd.fd = fd; + pfd.events = POLLIN; + return ::poll(&pfd, 1, static_cast(timeout.count())); +#endif +} + #ifdef _WIN32 int last_socket_error() { return WSAGetLastError(); } #else @@ -38,11 +65,15 @@ UdpSocket::UdpSocket(const UdpSocket::Config &config) UdpSocket::~UdpSocket() { stop_receiving(); } void UdpSocket::stop_receiving() { - // Close the socket first so any blocking recvfrom returns and the task can stop. - cleanup(); + // Stop the receive task first - it waits for data in bounded select() slices + // (see server_task_function), so this returns promptly - and only then close + // the socket. Closing a descriptor another thread is blocked on to wake it is + // a race (the number can be reused by the next socket opened), which + // ThreadSanitizer reports. if (task_ && task_->is_started()) { task_->stop(); } + cleanup(); } bool UdpSocket::send(const std::vector &data, const UdpSocket::SendConfig &send_config) { @@ -149,22 +180,26 @@ bool UdpSocket::receive(size_t max_num_bytes, std::vector &data, // recvfrom auto remote_address = remote_info.ipv4_ptr(); socklen_t socklen = sizeof(*remote_address); - // put it on the heap so that our stack usage doesn't change depending on - // max_num_bytes - std::unique_ptr receive_buffer(new uint8_t[max_num_bytes]()); - // now actually receive - logger_.info("Receiving up to {} bytes", max_num_bytes); + // Receive straight into the caller's vector, then shrink it to what arrived: + // no separate buffer and no copy. A vector reused across calls keeps its + // capacity, so from the second call on this allocates nothing (issue #969: + // a per-datagram allocation fails on a fragmented embedded heap, and with + // exceptions off a failed `new` aborts). + data.resize(max_num_bytes); + logger_.debug("Receiving up to {} bytes", max_num_bytes); int num_bytes_received = - recvfrom(socket_, reinterpret_cast(receive_buffer.get()), max_num_bytes, 0, + recvfrom(socket_.load(std::memory_order_relaxed), reinterpret_cast(data.data()), + static_cast(max_num_bytes), 0, reinterpret_cast(remote_address), &socklen); // if we didn't receive anything return false and don't do anything else if (num_bytes_received < 0) { - logger_.info("Receive failed: {}", error_string()); + data.clear(); + if (logger_.get_verbosity() <= espp::Logger::Verbosity::DEBUG) { + logger_.debug("Receive failed: {}", error_string()); + } return false; } - // we received data, so call the callback function if one was provided. - uint8_t *data_ptr = receive_buffer.get(); - data.assign(data_ptr, data_ptr + num_bytes_received); + data.resize(static_cast(num_bytes_received)); remote_info.update(); logger_.debug("Received {} bytes from {}", num_bytes_received, remote_info); return true; @@ -215,6 +250,20 @@ bool UdpSocket::start_receiving(Task::BaseConfig &task_config, if (!bind(receive_config)) { return false; } + // the task receives every datagram into this buffer: size it once, now + server_receive_data_.reserve(receive_config.buffer_size); + // The task waits (bounded) for data before receiving; bound the receive too, + // for a readiness reported spuriously (e.g. a datagram that fails its + // checksum and is discarded in between), so the task - and stop_receiving(), + // which stops it before closing the socket - always make progress. Without + // the bound that is not guaranteed, so refuse to start (as SocketReactor + // refuses such a registration). + if (!set_receive_timeout(std::chrono::seconds(1))) { + logger_.error("Could not set a receive timeout on port {}; not starting the receive task " + "(an unbounded blocking receive could hang stop_receiving())", + receive_config.port); + return false; + } // set the callback function using namespace std::placeholders; // start the thread @@ -229,12 +278,17 @@ bool UdpSocket::start_receiving(Task::BaseConfig &task_config, bool UdpSocket::server_task_function(size_t buffer_size, std::mutex &m, std::condition_variable &cv, bool &task_notified) { - // receive data - std::vector received_data; - Socket::Info sender_info; + // Wait (bounded) for a datagram, so the task never blocks indefinitely in + // recvfrom and stop_receiving() can stop it before closing the socket. + using namespace std::chrono_literals; + if (wait_readable(socket_.load(std::memory_order_relaxed), 100ms) == 0) { + return false; // nothing yet: give the task a chance to stop + } + // receive data, into buffers the task reuses for every datagram + auto &received_data = server_receive_data_; + auto &sender_info = server_sender_info_; if (!receive(buffer_size, received_data, sender_info)) { // if we failed to receive, then likely we should delay a little bit - using namespace std::chrono_literals; std::unique_lock lk(m); auto stop_requested = cv.wait_for(lk, 1ms, [&task_notified] { return task_notified; }); task_notified = false; @@ -253,7 +307,7 @@ bool UdpSocket::server_task_function(size_t buffer_size, std::mutex &m, std::con if (!maybe_response.has_value()) { return false; } - auto response = maybe_response.value(); + const auto &response = maybe_response.value(); // sendto logger_.info("Server responding to {} with message of length {}", sender_info, response.size()); auto sender_address = sender_info.ipv4_ptr(); diff --git a/components/task/src/task.cpp b/components/task/src/task.cpp index 227a729568..245ab4d224 100644 --- a/components/task/src/task.cpp +++ b/components/task/src/task.cpp @@ -477,14 +477,17 @@ void Task::thread_function() { #endif // ESP_PLATFORM while (started_) { bool should_stop = false; + // Call the callback by reference: copying the std::function every + // iteration allocated whenever its captures outgrew the small buffer + // (callback_ is set once, in the constructor, so the reference is stable). if (std::holds_alternative(callback_)) { - auto cb = std::get(callback_); + const auto &cb = std::get(callback_); should_stop = cb(cv_m_, cv_, notified_); } else if (std::holds_alternative(callback_)) { - auto cb = std::get(callback_); + const auto &cb = std::get(callback_); should_stop = cb(cv_m_, cv_); } else if (std::holds_alternative(callback_)) { - auto cb = std::get(callback_); + const auto &cb = std::get(callback_); should_stop = cb(); } else { started_ = false; diff --git a/components/thread_pool/include/thread_pool.hpp b/components/thread_pool/include/thread_pool.hpp index d4f0dd3145..24bcf07867 100644 --- a/components/thread_pool/include/thread_pool.hpp +++ b/components/thread_pool/include/thread_pool.hpp @@ -2,6 +2,7 @@ #include #include +#include #include #include #include @@ -251,6 +252,54 @@ class ThreadPool : public espp::BaseComponent { std::chrono::steady_clock::time_point enqueued_at{}; }; + /// @brief One band's FIFO: a ring buffer that doubles when full and never + /// shrinks, so a steady stream of submit / run never touches the heap. + /// (std::deque frees and re-allocates its blocks as entries pass + /// through - with MSVC's tiny blocks, on every push.) + class EntryQueue { + public: + bool empty() const { return size_ == 0; } + std::size_t size() const { return size_; } + Entry &front() { return slots_[head_]; } + void push_back(Entry &&entry) { + if (size_ == slots_.size()) { + grow(); + } + slots_[(head_ + size_) & mask_] = std::move(entry); + ++size_; + } + void pop_front() { + slots_[head_] = Entry{}; // release the job (and what it captured) now + head_ = (head_ + 1) & mask_; + --size_; + } + void clear() { + while (!empty()) { + pop_front(); + } + head_ = 0; + } + + private: + void grow() { + // The capacity is a power of two (8, then doubling), so an index wraps + // with `& mask_`; mask_ is only ever set here, from the new capacity. + const std::size_t capacity = slots_.empty() ? 8 : slots_.size() * 2; + assert((capacity & (capacity - 1)) == 0 && "the ring capacity must be a power of two"); + std::vector bigger(capacity); + for (std::size_t i = 0; i < size_; ++i) { + bigger[i] = std::move(slots_[(head_ + i) & mask_]); + } + slots_ = std::move(bigger); + mask_ = capacity - 1; + head_ = 0; + } + std::vector slots_; + std::size_t mask_{0}; ///< slots_.size() - 1: the capacity is a power of two + std::size_t head_{0}; + std::size_t size_{0}; + }; + bool worker_task_fn(std::size_t max_band); bool submit_impl(Job &&job, QosBand band, bool allow_blocking_when_full); @@ -267,8 +316,8 @@ class ThreadPool : public espp::BaseComponent { mutable std::mutex queue_mutex_; std::condition_variable queue_has_work_cv_; std::condition_variable queue_has_space_cv_; - std::array, kNumBands> queues_; ///< One FIFO per band; index = QosBand. - std::size_t total_queued_{0}; ///< Sum of all band queue sizes. + std::array queues_; ///< One FIFO per band; index = QosBand. + std::size_t total_queued_{0}; ///< Sum of all band queue sizes. std::vector> workers_; std::atomic running_{false}; diff --git a/lib/python_bindings/espp/_espp/__init__.pyi b/lib/python_bindings/espp/_espp/__init__.pyi index 86043cd56c..428052b6f8 100644 --- a/lib/python_bindings/espp/_espp/__init__.pyi +++ b/lib/python_bindings/espp/_espp/__init__.pyi @@ -4332,7 +4332,10 @@ class TcpSocket(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. """ @@ -4614,7 +4617,11 @@ class UdpSocket(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. diff --git a/lib/python_bindings/pybind_espp.cpp b/lib/python_bindings/pybind_espp.cpp index 69d30e9790..0d6227729a 100644 --- a/lib/python_bindings/pybind_espp.cpp +++ b/lib/python_bindings/pybind_espp.cpp @@ -2356,9 +2356,12 @@ void py_init_module_espp(py::module &m) { .def("receive", py::overload_cast &, size_t>(&espp::TcpSocket::receive), py::arg("data"), py::arg("max_num_bytes"), "*\n * @brief Call read on the socket, assuming it has already been configured\n * " - " appropriately.\n *\n * @param data Vector of bytes of received data.\n * " - "@param max_num_bytes Maximum number of bytes to receive.\n * @return True if " - "successfully received, False otherwise.\n", + " appropriately.\n *\n * @param data Vector of bytes of received data: " + "received straight into, then\n * resized to the bytes received (cleared on " + "failure). Its capacity is\n * kept, so passing the same vector to every call " + "allocates nothing\n * once it holds max_num_bytes.\n * @param max_num_bytes " + "Maximum number of bytes to receive.\n * @return True if successfully received, False " + "otherwise.\n", py::call_guard()) .def("receive", py::overload_cast(&espp::TcpSocket::receive), py::arg("data"), py::arg("max_num_bytes"), @@ -2574,10 +2577,13 @@ void py_init_module_espp(py::module &m) { py::arg("remote_info"), "*\n * @brief Call recvfrom on the socket, assuming it has already been\n * " "configured appropriately.\n *\n * @param max_num_bytes Maximum number of bytes to " - "receive.\n * @param data Vector of bytes of received data.\n * @param remote_info " - "Socket::Info containing the sender's information. This\n * will be populated " - "with the information about the sender.\n * @return True if successfully received, " - "False otherwise.\n", + "receive.\n * @param data Vector of bytes of received data: the datagram is " + "received\n * straight into it and it is then resized to the bytes received\n " + " * (cleared on failure). Its capacity is kept, so passing the same\n * " + "vector to every call allocates nothing once it holds\n * max_num_bytes.\n * " + "@param remote_info Socket::Info containing the sender's information. This\n * " + "will be populated with the information about the sender.\n * @return True if " + "successfully received, False otherwise.\n", py::call_guard()) .def("bind", &espp::UdpSocket::bind, py::arg("receive_config"), "*\n * @brief Bind the socket as a server according to \\p receive_config (bind to\n " diff --git a/pc/CMakeLists.txt b/pc/CMakeLists.txt index d1aa424bdc..020ae50244 100644 --- a/pc/CMakeLists.txt +++ b/pc/CMakeLists.txt @@ -27,7 +27,9 @@ add_compile_definitions(ODRIVE_GOLDEN_HAS_ESPP_LIB=1) # Every test is registered with ctest and labelled: # unit runs on its own, no peer needed (`ctest -L unit`); `network` also -# marks the ones that use UDP / multicast on the loopback +# marks the RTPS ones, which use multicast on the loopback (the +# socket tests - socket_reactor, socket_receive - use unicast +# loopback only, so they run everywhere, Windows included) # interop needs a ROS 2 / FastDDS / CycloneDDS peer (rtps/interop runs them) # demo an example that prints rather than checks (always exits 0), or # interactive (cli) @@ -37,7 +39,7 @@ function(espp_pc_test_labels out_var name) set(labels interop network) elseif(name MATCHES "^(cli|task|timer|udp_client|udp_server|file_system)$") set(labels demo) - elseif(name MATCHES "^(rtps_|socket_reactor$)") + elseif(name MATCHES "^rtps_") set(labels unit network) else() set(labels unit) diff --git a/pc/tests/crash_diagnostics.hpp b/pc/tests/crash_diagnostics.hpp new file mode 100644 index 0000000000..0a5887c550 --- /dev/null +++ b/pc/tests/crash_diagnostics.hpp @@ -0,0 +1,50 @@ +#pragma once + +// Make a crashing pc test say why, and keep its log. ctest pipes a test's +// output, so the C runtime buffers it fully - and a fail-fast abort (on Windows +// exit code 0xc0000409: abort(), std::terminate, a CRT invalid-parameter check) +// ends the process before that buffer is flushed, leaving no output at all. +// Call install_crash_diagnostics() first thing in main(). + +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#endif + +#include + +inline void install_crash_diagnostics() { + std::setvbuf(stdout, nullptr, _IONBF, 0); + std::setvbuf(stderr, nullptr, _IONBF, 0); + std::set_terminate([] { + if (auto e = std::current_exception()) { + try { + std::rethrow_exception(e); + } catch (const std::exception &ex) { + std::fprintf(stderr, "\n*** std::terminate: uncaught exception: %s\n", ex.what()); + } catch (...) { + std::fprintf(stderr, "\n*** std::terminate: uncaught non-std exception\n"); + } + } else { + std::fprintf(stderr, "\n*** std::terminate called without an exception\n"); + } + std::abort(); + }); + std::signal(SIGABRT, [](int) { + std::fputs("\n*** abort() called\n", stderr); + std::_Exit(3); + }); +#if defined(_WIN32) + _set_invalid_parameter_handler([](const wchar_t *expression, const wchar_t *function, + const wchar_t *file, unsigned int line, uintptr_t) { + std::fprintf(stderr, "\n*** CRT invalid parameter: %ls in %ls (%ls:%u)\n", + expression ? expression : L"?", function ? function : L"?", file ? file : L"?", + line); + std::_Exit(4); + }); +#endif +} diff --git a/pc/tests/socket_reactor.cpp b/pc/tests/socket_reactor.cpp index 62322df1dd..66a7ac616e 100644 --- a/pc/tests/socket_reactor.cpp +++ b/pc/tests/socket_reactor.cpp @@ -11,6 +11,7 @@ #include #include +#include "crash_diagnostics.hpp" #include "socket_reactor.hpp" #include "tcp_socket.hpp" #include "udp_socket.hpp" @@ -72,6 +73,7 @@ bool udp_echo_roundtrip(size_t port, const ByteVector &request) { // Mirrors python/socket_reactor_test.py, plus the TCP listener/stream paths // (which are C++-only). Exit code 0 on full pass, 1 on any failure. int main() { + install_crash_diagnostics(); // keep the log, and say why, if the test crashes espp::Logger logger({.tag = "SocketReactor Test", .level = espp::Logger::Verbosity::INFO}); int total_passed = 0; diff --git a/pc/tests/socket_receive.cpp b/pc/tests/socket_receive.cpp new file mode 100644 index 0000000000..3cae5535ea --- /dev/null +++ b/pc/tests/socket_receive.cpp @@ -0,0 +1,459 @@ +// Steady-state receive must not touch the heap: no allocation per datagram / +// stream event on UdpSocket::receive, TcpSocket::receive, the UdpSocket receive +// task, or the SocketReactor's UDP / TCP dispatch (reactor loop + pool worker). +// On a tight embedded heap a per-datagram allocation fails under fragmentation, +// and with C++ exceptions off a failed `new` aborts the chip (issue #969). +// +// Every operator new in this program is counted. Threads that only generate +// traffic (the test thread's sends) mark themselves exempt, so a window counts +// exactly what the receive side allocates. Exit code 0 on full pass, 1 on any +// failure. + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "crash_diagnostics.hpp" +#include "socket_reactor.hpp" +#include "tcp_socket.hpp" +#include "udp_socket.hpp" + +using namespace std::chrono_literals; +using ByteVector = std::vector; + +// --------------------------------------------------------------------------- +// Allocation counting +// --------------------------------------------------------------------------- +namespace alloc_count { +std::atomic enabled{false}; ///< count process-wide (non-exempt threads) +std::atomic total{0}; +thread_local std::size_t this_thread = 0; ///< always counted, per thread +thread_local bool exempt = false; ///< traffic generators set this + +inline void record() noexcept { + ++this_thread; + if (!exempt && enabled.load(std::memory_order_relaxed)) { + total.fetch_add(1, std::memory_order_relaxed); + } +} + +/// Counts process-wide allocations while alive (excluding exempt threads). +struct Window { + Window() { + total = 0; + enabled = true; + } + ~Window() { enabled = false; } + std::size_t count() const { return total.load(); } +}; + +/// Marks the current thread exempt while alive. +struct Exempt { + bool prev = exempt; + Exempt() { exempt = true; } + ~Exempt() { exempt = prev; } +}; +} // namespace alloc_count + +void *operator new(std::size_t n) { + alloc_count::record(); + if (void *p = std::malloc(n ? n : 1)) { + return p; + } + throw std::bad_alloc(); +} +void *operator new[](std::size_t n) { + alloc_count::record(); + if (void *p = std::malloc(n ? n : 1)) { + return p; + } + throw std::bad_alloc(); +} +void *operator new(std::size_t n, const std::nothrow_t &) noexcept { + alloc_count::record(); + return std::malloc(n ? n : 1); +} +void *operator new[](std::size_t n, const std::nothrow_t &) noexcept { + alloc_count::record(); + return std::malloc(n ? n : 1); +} +// The aligned forms too, so no allocation slips past the count. The block is +// over-allocated and the malloc'd pointer kept just before the aligned address. +static void *aligned_new(std::size_t n, std::align_val_t al) noexcept { + alloc_count::record(); + const std::size_t alignment = std::max(static_cast(al), sizeof(void *)); + void *raw = std::malloc(n + alignment + sizeof(void *)); + if (raw == nullptr) { + return nullptr; + } + const auto base = reinterpret_cast(raw) + sizeof(void *); + const auto aligned = (base + alignment - 1) & ~(static_cast(alignment) - 1); + reinterpret_cast(aligned)[-1] = raw; + return reinterpret_cast(aligned); +} +static void aligned_delete(void *p) noexcept { + if (p != nullptr) { + std::free(reinterpret_cast(p)[-1]); + } +} +void *operator new(std::size_t n, std::align_val_t al) { + if (void *p = aligned_new(n, al)) { + return p; + } + throw std::bad_alloc(); +} +void *operator new[](std::size_t n, std::align_val_t al) { + if (void *p = aligned_new(n, al)) { + return p; + } + throw std::bad_alloc(); +} +void *operator new(std::size_t n, std::align_val_t al, const std::nothrow_t &) noexcept { + return aligned_new(n, al); +} +void *operator new[](std::size_t n, std::align_val_t al, const std::nothrow_t &) noexcept { + return aligned_new(n, al); +} +void operator delete(void *p, std::align_val_t) noexcept { aligned_delete(p); } +void operator delete[](void *p, std::align_val_t) noexcept { aligned_delete(p); } +void operator delete(void *p, std::size_t, std::align_val_t) noexcept { aligned_delete(p); } +void operator delete[](void *p, std::size_t, std::align_val_t) noexcept { aligned_delete(p); } +void operator delete(void *p, std::align_val_t, const std::nothrow_t &) noexcept { + aligned_delete(p); +} +void operator delete[](void *p, std::align_val_t, const std::nothrow_t &) noexcept { + aligned_delete(p); +} + +void operator delete(void *p) noexcept { std::free(p); } +void operator delete[](void *p) noexcept { std::free(p); } +void operator delete(void *p, std::size_t) noexcept { std::free(p); } +void operator delete[](void *p, std::size_t) noexcept { std::free(p); } +void operator delete(void *p, const std::nothrow_t &) noexcept { std::free(p); } +void operator delete[](void *p, const std::nothrow_t &) noexcept { std::free(p); } + +// --------------------------------------------------------------------------- +namespace { +constexpr auto kLoopback = "127.0.0.1"; +constexpr auto WARN = espp::Logger::Verbosity::WARN; +constexpr size_t kMaxDatagram = 1472; // what an MTU-1500 link delivers unfragmented +constexpr int kWarmup = 4; +constexpr int kMeasured = 100; + +// A payload whose bytes encode its sequence number and length, so the receiver +// can check it without the test keeping (allocating) a copy. +ByteVector make_payload(int seq) { + // sizes cycle through small, mid and the full buffer + const size_t sizes[] = {1, 17, 200, 999, kMaxDatagram}; + const size_t n = sizes[seq % 5]; + ByteVector v(n); + for (size_t i = 0; i < n; ++i) { + v[i] = static_cast(seq * 31 + i); + } + return v; +} + +bool matches(const uint8_t *data, size_t size, int seq) { + const size_t sizes[] = {1, 17, 200, 999, kMaxDatagram}; + if (size != sizes[seq % 5]) { + return false; + } + for (size_t i = 0; i < size; ++i) { + if (data[i] != static_cast(seq * 31 + i)) { + return false; + } + } + return true; +} + +template bool wait_until(Predicate &&pred, std::chrono::milliseconds timeout) { + const auto deadline = std::chrono::steady_clock::now() + timeout; + while (std::chrono::steady_clock::now() < deadline) { + if (pred()) { + return true; + } + std::this_thread::sleep_for(1ms); + } + return pred(); +} +} // namespace + +int main() { + install_crash_diagnostics(); // keep the log, and say why, if the test crashes + espp::Logger logger({.tag = "Socket receive test", .level = espp::Logger::Verbosity::INFO}); + int passed = 0; + int total = 0; + auto check = [&](bool condition, const std::string &desc) { + ++total; + if (condition) { + ++passed; + logger.info(" PASS: {}", desc); + } else { + logger.error(" FAIL: {}", desc); + } + return condition; + }; + + // ------------------------------------------------------------------------- + // 1. UdpSocket::receive into a reused vector: no allocation per datagram + // ------------------------------------------------------------------------- + logger.info("--- UdpSocket::receive ---"); + { + constexpr size_t port = 6311; + espp::UdpSocket server({.log_level = WARN}); + check(server.bind({.port = port}), "bind the receiving socket"); + server.set_receive_timeout(1s); + espp::UdpSocket client({.log_level = WARN}); + + ByteVector data; + espp::Socket::Info from; + bool all_ok = true; + std::size_t allocations = 0; + for (int seq = 0; seq < kWarmup + kMeasured; ++seq) { + { + alloc_count::Exempt sending; + client.send(make_payload(seq), {.ip_address = kLoopback, .port = port}); + } + const auto before = alloc_count::this_thread; + const bool ok = server.receive(kMaxDatagram, data, from); + const auto used = alloc_count::this_thread - before; + all_ok = all_ok && ok && matches(data.data(), data.size(), seq); + if (seq >= kWarmup) { + allocations += used; + } + } + check(all_ok, "every datagram arrives intact, at its own size"); + check(data.capacity() >= kMaxDatagram, "the vector keeps the receive capacity"); + logger.info(" {} allocation(s) over {} receives", allocations, kMeasured); + check(allocations == 0, "no allocation per receive once the vector has capacity"); + } + + // ------------------------------------------------------------------------- + // 2. SocketReactor UDP receiver: no allocation per datagram (reactor loop, + // pool dispatch, receive, callback) + // ------------------------------------------------------------------------- + logger.info("--- SocketReactor UDP ---"); + { + constexpr size_t port = 6312; + espp::UdpSocket server({.log_level = WARN}); + espp::SocketReactor reactor({.log_level = WARN}); + std::atomic received{0}; + std::atomic all_ok{true}; + auto id = reactor.add_udp_receiver( + server, + {.port = port, + .buffer_size = kMaxDatagram, + .on_receive_callback = [&](ByteVector &data, + const espp::Socket::Info &) -> std::optional { + const int seq = received.load(); + if (!matches(data.data(), data.size(), seq)) { + all_ok = false; + } + ++received; + return std::nullopt; + }}); + check(id != espp::SocketReactor::INVALID_ID, "add_udp_receiver"); + espp::UdpSocket client({.log_level = WARN}); + auto send_and_wait = [&](int seq) { + { + alloc_count::Exempt sending; + client.send(make_payload(seq), {.ip_address = kLoopback, .port = port}); + } + return wait_until([&] { return received.load() == seq + 1; }, 2s); + }; + bool delivered = true; + alloc_count::exempt = true; // the test thread only generates traffic + for (int seq = 0; seq < kWarmup; ++seq) { + delivered = delivered && send_and_wait(seq); + } + std::size_t allocations = 0; + { + alloc_count::Window window; + for (int seq = kWarmup; seq < kWarmup + kMeasured; ++seq) { + delivered = delivered && send_and_wait(seq); + } + allocations = window.count(); + } + alloc_count::exempt = false; + check(delivered, "every datagram is dispatched"); + check(all_ok.load(), "every datagram arrives intact, at its own size"); + logger.info(" {} allocation(s) over {} datagrams", allocations, kMeasured); + check(allocations == 0, "no allocation per datagram in the reactor path"); + reactor.stop(); + } + + // ------------------------------------------------------------------------- + // 3. UdpSocket's own receive task: no allocation per datagram + // ------------------------------------------------------------------------- + logger.info("--- UdpSocket::start_receiving ---"); + { + constexpr size_t port = 6313; + espp::UdpSocket server({.log_level = WARN}); + std::atomic received{0}; + std::atomic all_ok{true}; + espp::Task::BaseConfig task_config{.name = "udp_rx_test", .stack_size_bytes = 6 * 1024}; + check(server.start_receiving( + task_config, {.port = port, + .buffer_size = kMaxDatagram, + .on_receive_callback = [&](ByteVector &data, const espp::Socket::Info &) + -> std::optional { + if (!matches(data.data(), data.size(), received.load())) { + all_ok = false; + } + ++received; + return std::nullopt; + }}), + "start_receiving"); + espp::UdpSocket client({.log_level = WARN}); + auto send_and_wait = [&](int seq) { + { + alloc_count::Exempt sending; + client.send(make_payload(seq), {.ip_address = kLoopback, .port = port}); + } + return wait_until([&] { return received.load() == seq + 1; }, 2s); + }; + bool delivered = true; + alloc_count::exempt = true; + for (int seq = 0; seq < kWarmup; ++seq) { + delivered = delivered && send_and_wait(seq); + } + std::size_t allocations = 0; + { + alloc_count::Window window; + for (int seq = kWarmup; seq < kWarmup + kMeasured; ++seq) { + delivered = delivered && send_and_wait(seq); + } + allocations = window.count(); + } + alloc_count::exempt = false; + check(delivered, "every datagram is delivered"); + check(all_ok.load(), "every datagram arrives intact, at its own size"); + logger.info(" {} allocation(s) over {} datagrams", allocations, kMeasured); + check(allocations == 0, "no allocation per datagram in the receive task"); + server.stop_receiving(); + } + + // ------------------------------------------------------------------------- + // 4. SocketReactor TCP stream: no allocation per readable event + // ------------------------------------------------------------------------- + logger.info("--- SocketReactor TCP ---"); + { + constexpr int port = 6314; + constexpr size_t kChunk = 512; + espp::TcpSocket listener({.log_level = WARN}); + check(listener.bind(port) && listener.listen(1), "listen on the loopback"); + espp::TcpSocket client({.log_level = WARN}); + std::unique_ptr connection; + std::thread acceptor([&] { connection = listener.accept(); }); + { + alloc_count::Exempt connecting; + check(client.connect({.ip_address = kLoopback, .port = static_cast(port)}), + "connect"); + } + acceptor.join(); + check(connection != nullptr, "accept"); + if (connection) { + espp::SocketReactor reactor({.log_level = WARN}); + std::atomic bytes{0}; + std::atomic all_ok{true}; + auto id = reactor.add_tcp_stream( + *connection, + [&](espp::TcpSocket &, ByteVector &data) { + // the stream carries 0, 1, 2, ... (mod 251): check it in place + size_t at = bytes.load(); + for (uint8_t b : data) { + if (b != static_cast(at++ % 251)) { + all_ok = false; + } + } + bytes += data.size(); + }, + kChunk); + check(id != espp::SocketReactor::INVALID_ID, "add_tcp_stream"); + ByteVector chunk(kChunk); + size_t sent = 0; + auto send_and_wait = [&]() { + { + alloc_count::Exempt sending; + for (auto &b : chunk) { + b = static_cast(sent++ % 251); + } + client.transmit(chunk); + } + return wait_until([&] { return bytes.load() == sent; }, 2s); + }; + bool delivered = true; + alloc_count::exempt = true; + for (int i = 0; i < kWarmup; ++i) { + delivered = delivered && send_and_wait(); + } + std::size_t allocations = 0; + { + alloc_count::Window window; + for (int i = 0; i < kMeasured; ++i) { + delivered = delivered && send_and_wait(); + } + allocations = window.count(); + } + alloc_count::exempt = false; + check(delivered, "every chunk is delivered"); + check(all_ok.load(), "the stream arrives intact and in order"); + logger.info(" {} allocation(s) over {} chunks", allocations, kMeasured); + check(allocations == 0, "no allocation per readable event in the reactor TCP path"); + reactor.stop(); + } + } + + // ------------------------------------------------------------------------- + // 5. espp::Task's loop: no allocation per iteration, even for a callback too + // large for std::function's small buffer (the loop used to copy it every + // iteration; UdpSocket's receive task is one such callback) + // ------------------------------------------------------------------------- + logger.info("--- Task loop ---"); + { + std::atomic iterations{0}; + std::array ballast{}; // captured by value: forces heap storage + ballast[0] = 1; + auto task = espp::Task::make_unique( + {.callback = + [&iterations, ballast](std::mutex &m, std::condition_variable &cv, bool ¬ified) { + iterations += ballast[0]; + std::unique_lock lock(m); + cv.wait_for(lock, 1ms, [¬ified] { return notified; }); + notified = false; + return false; + }, + .task_config = {.name = "alloc_test_task", .stack_size_bytes = 4096}, + .log_level = WARN}); + task->start(); + alloc_count::exempt = true; + const bool warmed_up = wait_until([&] { return iterations.load() >= kWarmup; }, 2s); + std::size_t allocations = 0; + int looped = 0; + { + alloc_count::Window window; + const int start = iterations.load(); + wait_until([&] { return iterations.load() >= start + kMeasured; }, 5s); + looped = iterations.load() - start; + allocations = window.count(); + } + alloc_count::exempt = false; + task->stop(); + check(warmed_up && looped >= kMeasured, "the task loops"); + logger.info(" {} allocation(s) over {} iterations", allocations, looped); + check(allocations == 0, "no allocation per Task loop iteration"); + } + + logger.info("{} / {} checks passed", passed, total); + return passed == total ? 0 : 1; +} diff --git a/pc/tests/thread_pool.cpp b/pc/tests/thread_pool.cpp index dbcc5697f1..1e3bb97596 100644 --- a/pc/tests/thread_pool.cpp +++ b/pc/tests/thread_pool.cpp @@ -2,6 +2,7 @@ #include #include #include +#include #include #include #include @@ -804,6 +805,110 @@ int main() { } // --------------------------------------------------------------------------- + // --------------------------------------------------------------------------- + // Band queue ring buffer: FIFO across wrap-around and growth, captures + // released once a job has run, queued jobs dropped (and counted) on stop() + // --------------------------------------------------------------------------- + logger.info("--- queue ring: wrap-around + growth ---"); + { + std::mutex gate_mtx; + std::condition_variable gate_cv; + int gate = 0; // jobs wait for `gate` to reach their number + auto wait_gate = [&](int n) { + std::unique_lock lk(gate_mtx); + gate_cv.wait(lk, [&] { return gate >= n; }); + }; + auto open_gate = [&](int n) { + { + std::lock_guard lk(gate_mtx); + gate = n; + } + gate_cv.notify_all(); + }; + std::mutex order_mtx; + std::vector order; + auto record = [&](int id) { + std::lock_guard lk(order_mtx); + order.push_back(id); + }; + + espp::ThreadPool pool({.worker_count = 1, + .auto_start = true, + .worker_task_config = {.name = "tp_ring", .stack_size_bytes = 4096}}); + // the one worker parks on a gate, so everything below stays queued + std::atomic parked{false}; + pool.submit([&] { + parked = true; + wait_gate(1); + }); + wait_until([&] { return parked.load(); }, 2s); + // 0..5 queued; 3 parks the worker again once 0..2 have run, which moves the + // ring's head forward (to slot 4 of the initial 8) + for (int i = 0; i < 6; ++i) { + pool.submit([&, i] { + record(i); + if (i == 3) { + wait_gate(2); + } + }); + } + open_gate(1); + wait_until( + [&] { + std::lock_guard lk(order_mtx); + return order.size() == 4; + }, + 2s); + // 4 and 5 are still queued at the back of the ring: 30 more wrap the tail + // past the end and then grow the ring (twice) while it is wrapped + for (int i = 6; i < 36; ++i) { + pool.submit([&, i] { record(i); }); + } + check(pool.queue_size() == 32, "32 jobs queued across a wrapped, grown ring"); + // a job's captures are released as soon as it has run + auto token = std::make_shared(7); + std::weak_ptr watch = token; + pool.submit([&, token = std::move(token)] { record(*token == 7 ? 36 : -1); }); + open_gate(2); + const bool drained = wait_until([&] { return pool.queue_size() == 0; }, 2s); + wait_until( + [&] { + std::lock_guard lk(order_mtx); + return order.size() == 37; + }, + 2s); + std::vector expected(37); + for (int i = 0; i < 37; ++i) { + expected[i] = i; + } + { + std::lock_guard lk(order_mtx); + check(drained && order == expected, "every job ran once, in FIFO order"); + } + check(wait_until([&] { return watch.expired(); }, 1s), + "a finished job's captures are released, not held by the queue"); + + // jobs still queued at stop() are dropped and counted as rejected + std::atomic parked_again{false}; + pool.submit([&] { + parked_again = true; + wait_gate(3); + }); + wait_until([&] { return parked_again.load(); }, 2s); + const auto rejected_before = pool.stats().rejected; + for (int i = 0; i < 10; ++i) { + pool.submit([] {}); + } + std::thread opener([&] { + std::this_thread::sleep_for(50ms); + open_gate(3); + }); + pool.stop(); + opener.join(); + check(pool.stats().rejected - rejected_before == 10, + "the 10 jobs still queued at stop() are dropped and counted"); + } + // Summary // --------------------------------------------------------------------------- logger.info("==================== Results ====================");