nRF9151: nonblocking UDP send waits for seconds when shared TX memory is full

Hi Nordic team,

On our nRF9151, a nonblocking UDP send sometimes takes several seconds when the modem runs out of transmit buffers. We expected nrf_send() to return -1 with EAGAIN or EWOULDBLOCK so our sending thread could do other work and retry later.

Is this expected? Could it be related to the older nRF9160 issue NCSDK-6073?

Setup

Tested on hardware: nRF9151, LTE-M, custom RTOS, calling the Nordic modem socket API directly. We linked the nrfxlib v2.8.0 cellular nrf9120/soft-float/libmodem.a archive. Modem firmware version 2.0.1.

Later versions checked: We inspected the cellular binaries from nrfxlib v3.4.0 and v3.4.1. Both contain the same ordering on the allocation-failure path described below. Our hardware timings are from v2.8.0.

Memory and traffic: 12 KiB of modem shared TX memory. Our allocator puts an 825-byte payload in a 1,072-byte size class and returns NULL on exhaustion in the test build. We sent 825-byte UDP datagrams to a PC. The sender did not wait for a reply to each packet.

What we measured

We set NRF_O_NONBLOCK on a connected UDP socket and called nrf_send(fd, data, 825, 0). We recorded the time spent in the OS wait hook and when the first matching modem notification arrived.

Default socket send timeout:

In four 35-second phases, the longest allocation wait in each phase was 2.658 s, 2.049 s, 1.049 s, and 2.905 s. In all four cases, the modem library passed context 1 and timeout -1 to nrf_modem_os_timedwait().

20 ms socket send timeout (NRF_SO_SNDTIMEO):

The longest wait was 20.78 ms. We counted 2,681 failed shared TX allocations across the same four offered rates. The sender kept up with its schedule and could handle the failed sends itself.

For the 2.905 s example, the first matching notification arrived 2.904236 s after the wait started. The hook returned successfully 0.336 ms later.

An earlier run recorded a single 10.59 s wait inside a send. We didn’t record the caller or notification timing in that earlier run, so we can only attribute the 1.05–2.90 s waits to this specific allocation path.

The call sequence may help locate it. When rpc_client_msg_alloc() returns NULL, nrf_sendto() calls nrf_modem_os_timedwait(1, &timeout). Only after a successful wake does that branch check the nonblocking flag and return EAGAIN.

In the v3.4.0 cellular binary, the wait call is at nrf_sendto+0x12c, and the flag check is at +0x132.

How to reproduce

  1. Start a UDP receiver on a host reachable from the SIM. A receiver that just drains incoming packets is sufficient. Our receiver used port 45125.

  2. After LTE registration and data connectivity are established, run the sender below from a normal application thread. Pass the receiver’s IPv4 address and use false for the first run. Use a 12 KiB shared TX region to match our setup.

  3. Repeat on a fresh socket with true to set the 20 ms timeout. The rate sequence is 8, 64, 256, 256, 64 kbit/s, 35 seconds each. The first phase warms up the link. Missed send slots are skipped to avoid a catch-up burst.

  4. For attribution, count failures in nrf_modem_os_shm_tx_alloc(). On the sending thread, record the caller, context, input timeout and elapsed time in nrf_modem_os_timedwait(), plus the time of the first matching nrf_modem_os_event_notify(). Buffer the measurements and print them after the phase. If the allocator never runs out of buffers, the run hasn’t exercised this branch.

Example Python receiver

The following Python receiver can run on the PC. Set receiver_ip to the PC's SIM-reachable address when calling the sender.

import socket

with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as receiver:
    receiver.bind(("", 45125))
    while True:
        receiver.recvfrom(2048)

Example UDP sender

The sender below is a shortened example for an nRF Connect SDK application with an already-connected modem. Call test_udp_send(receiver_ip, false) and then test_udp_send(receiver_ip, true).

It uses Zephyr timing calls in place of our RTOS clock. The measurements above came from our instrumented bench application.

#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <nrf_socket.h>
#include <zephyr/kernel.h>
#include <zephyr/sys/printk.h>

void test_udp_send(const char *receiver_ip, bool use_20_ms_timeout)
{
    static uint8_t packet[825];
    static const unsigned rates[] = {8, 64, 256, 256, 64};

    struct nrf_sockaddr_in peer = {
        .sin_family = NRF_AF_INET,
        .sin_port = nrf_htons(45125),
    };

    if (nrf_inet_pton(NRF_AF_INET, receiver_ip, &peer.sin_addr) != 1) {
        printk("Invalid receiver IPv4 address\n");
        return;
    }

    int fd = nrf_socket(NRF_AF_INET, NRF_SOCK_DGRAM, NRF_IPPROTO_UDP);

    if (fd < 0) {
        printk("Socket creation failed, errno %d\n", errno);
        return;
    }

    if (use_20_ms_timeout) {
        struct nrf_timeval tv = {
            .tv_sec = 0,
            .tv_usec = 20000
        };

        if (nrf_setsockopt(fd, NRF_SOL_SOCKET, NRF_SO_SNDTIMEO,
                          &tv, sizeof(tv)) < 0)
            goto error;
    }

    int flags = nrf_fcntl(fd, NRF_F_GETFL, 0);

    if (flags < 0 ||
        nrf_fcntl(fd, NRF_F_SETFL, flags | NRF_O_NONBLOCK) < 0)
        goto error;

    if (nrf_connect(fd, (const struct nrf_sockaddr *)&peer,
                    sizeof(peer)) < 0)
        goto error;

    for (unsigned phase = 0;
         phase < sizeof(rates) / sizeof(rates[0]);
         ++phase) {

        uint32_t start = k_uptime_get_32();
        unsigned next_slot = 0, accepted = 0, busy = 0;
        uint32_t longest_ms = 0;

        for (;;) {
            uint32_t now = k_uptime_get_32();
            uint32_t elapsed_ms = now - start;

            if (elapsed_ms >= 35000U)
                break;

            unsigned slot =
                elapsed_ms * rates[phase] / (8U * sizeof(packet));

            if (slot < next_slot) {
                k_sleep(K_MSEC(1));
                continue;
            }

            next_slot = slot + 1;

            int n = nrf_send(fd, packet, sizeof(packet), 0);
            int err = n < 0 ? errno : 0;

            uint32_t duration_ms = k_uptime_get_32() - now;

            if (duration_ms > longest_ms)
                longest_ms = duration_ms;

            if (n == (int)sizeof(packet)) {
                ++accepted;
            } else if (n < 0 &&
                       (err == EAGAIN || err == EWOULDBLOCK ||
                        err == ENOMEM || err == ENOBUFS)) {
                ++busy;
            } else {
                printk("Unexpected send result %d, errno %d\n", n, err);
                nrf_close(fd);
                return;
            }
        }

        printk("%u kbit/s: %u accepted, %u busy, longest send %u ms\n",
               rates[phase], accepted, busy, (unsigned)longest_ms);

        k_sleep(K_SECONDS(5));
    }

    nrf_close(fd);
    return;

error:
    printk("Socket setup failed, errno %d\n", errno);
    nrf_close(fd);
}

Questions

Should the library check the nonblocking flag before waiting for a transmit buffer?

If the current behavior is intentional, is setting a short NRF_SO_SNDTIMEO the recommended way to keep this allocation wait bounded on the nRF9151?

Thanks!

Related