* net/udp/udp_sendto_buffered.c
*
* SPDX-License-Identifier: Apache-2.0
*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership. The
* ASF licenses this file to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#if defined(CONFIG_NET) && defined(CONFIG_NET_UDP) && \
defined(CONFIG_NET_UDP_WRITE_BUFFERS)
#if defined(CONFIG_DEBUG_FEATURES) && defined(CONFIG_NET_UDP_WRBUFFER_DEBUG)
# undef CONFIG_DEBUG_NET
# define CONFIG_DEBUG_NET 1
#endif
#include <sys/types.h>
#include <sys/socket.h>
#include <stdint.h>
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <errno.h>
#include <debug.h>
#include <arch/irq.h>
#include <nuttx/net/net.h>
#include <nuttx/mm/iob.h>
#include <nuttx/net/netdev.h>
#include <nuttx/net/udp.h>
#include "netdev/netdev.h"
#include "socket/socket.h"
#include "inet/inet.h"
#include "arp/arp.h"
#include "icmpv6/icmpv6.h"
#include "neighbor/neighbor.h"
#include "udp/udp.h"
#include "devif/devif.h"
#include "utils/utils.h"
* Pre-processor Definitions
****************************************************************************/
* in some additional domain selection support.
*/
#if defined(CONFIG_NET_IPv4) && defined(CONFIG_NET_IPv6)
# define NEED_IPDOMAIN_SUPPORT 1
#endif
#ifdef CONFIG_NET_UDP_WRBUFFER_DUMP
# define BUF_DUMP(msg,buf,len) lib_dumpbuffer(msg,buf,len)
#else
# define BUF_DUMP(msg,buf,len)
# undef UDP_WBDUMP
# define UDP_WBDUMP(msg,wrb,len,offset)
#endif
* Private Function Prototypes
****************************************************************************/
#ifdef NEED_IPDOMAIN_SUPPORT
static inline void sendto_ipselect(FAR struct net_driver_s *dev,
FAR struct udp_conn_s *conn);
#endif
static int sendto_next_transfer(FAR struct udp_conn_s *conn);
static uint32_t sendto_eventhandler(FAR struct net_driver_s *dev,
FAR void *pvpriv, uint32_t flags);
* Private Functions
****************************************************************************/
* Name: sendto_writebuffer_release
*
* Description:
* Release the write buffer at the head of the write buffer queue.
*
* Input Parameters:
* conn - The UDP connection of interest
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked
*
****************************************************************************/
static void sendto_writebuffer_release(FAR struct udp_conn_s *conn,
FAR struct udp_wrbuffer_s *wrb)
{
int ret = OK;
do
{
if (wrb == NULL && sq_empty(&conn->write_q))
{
* enqueued.
*/
conn->sndcb->flags = 0;
conn->sndcb->priv = NULL;
conn->sndcb->event = NULL;
ret = OK;
if (conn->txdrain_sem != NULL)
{
* has been drained.
*/
nxsem_post(conn->txdrain_sem);
}
}
else
{
* and release it.
*/
if (wrb == NULL)
{
wrb = (FAR struct udp_wrbuffer_s *)sq_remfirst(&conn->write_q);
}
DEBUGASSERT(wrb != NULL);
udp_wrbuffer_release(wrb);
wrb = NULL;
* address to the address of the next packet now at the header of
* the write buffer queue.
*/
ret = sendto_next_transfer(conn);
}
}
while (ret < 0);
#if CONFIG_NET_SEND_BUFSIZE > 0
udp_sendbuffer_notify(conn);
#endif
}
* Name: sendto_ipselect
*
* Description:
* If both IPv4 and IPv6 support are enabled, then we will need to select
* which one to use when generating the outgoing packet. If only one
* domain is selected, then the setup is already in place and we need do
* nothing.
*
* Input Parameters:
* dev - The structure of the network driver that caused the event
* conn - The UDP connection of interest
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked
*
****************************************************************************/
#ifdef NEED_IPDOMAIN_SUPPORT
static inline void sendto_ipselect(FAR struct net_driver_s *dev,
FAR struct udp_conn_s *conn)
{
if (conn->domain == PF_INET ||
(conn->domain == PF_INET6 &&
ip6_is_ipv4addr((FAR struct in6_addr *)conn->u.ipv6.raddr)))
{
udp_ipv4_select(dev);
}
else
{
udp_ipv6_select(dev);
}
}
#endif
* Name: sendto_next_transfer
*
* Description:
* Setup for the next packet transfer. That function is called (1)
* psock_udp_sendto() by when the new UDP packet is buffered at the head of
* the write queue and (2) by sendto_writebuffer_release() when that
* previously queued write buffer was sent and a new write buffer lies at
* the head of the write queue.
*
* Input Parameters:
* conn - The UDP connection structure
*
* Returned Value:
* None
*
****************************************************************************/
static int sendto_next_transfer(FAR struct udp_conn_s *conn)
{
FAR struct udp_wrbuffer_s *wrb;
FAR struct net_driver_s *dev;
int ret = OK;
* at the head of the queue.
*/
wrb = (FAR struct udp_wrbuffer_s *)sq_peek(&conn->write_q);
if (wrb == NULL)
{
ninfo("Write buffer queue is empty\n");
return -ENOENT;
}
if (!conn->lport)
{
* connection structure.
*/
conn->lport = HTONS(udp_select_port(conn->domain, &conn->u));
if (!conn->lport)
{
nerr("ERROR: Failed to get a local port!\n");
return -EADDRINUSE;
}
}
* should never be NULL.
*
* REVISIT: There is a logical error here for the case where there are
* multiple network devices. In that case, the packets may need to be sent
* in a different order than they were queued. Forcing FIFO packet
* transmission could harm performance.
*/
dev = udp_find_raddr_device(conn, &wrb->wb_dest);
if (dev == NULL)
{
nerr("ERROR: udp_find_raddr_device failed\n");
return -ENETUNREACH;
}
if (IFF_IS_RUNNING(dev->d_flags) == 0)
{
nwarn("WARNING: device is not RUNNING\n");
return -EHOSTUNREACH;
}
#ifndef CONFIG_NET_IPFRAG
if (wrb->wb_iob->io_pktlen > devif_get_mtu(dev))
{
nerr("ERROR: Packet too long to send!\n");
return -EMSGSIZE;
}
#endif
conn_unlock(&conn->sconn);
* udp_callback_alloc(), then we need to release and reallocate the old
* callback instance.
*/
if (conn->sndcb != NULL && conn->dev != dev)
{
conn_dev_lock(&conn->sconn, conn->dev);
udp_callback_free(conn->dev, conn, conn->sndcb);
conn->sndcb = NULL;
conn_dev_unlock(&conn->sconn, conn->dev);
}
* callback is not already in place.
*/
conn_dev_lock(&conn->sconn, dev);
if (conn->sndcb == NULL)
{
conn->sndcb = udp_callback_alloc(dev, conn);
}
if (conn->sndcb == NULL)
{
nerr("ERROR: Failed to allocate callback\n");
ret = -ENOMEM;
goto out;
}
conn->dev = dev;
conn->sndcb->flags = (UDP_POLL | NETDEV_DOWN);
conn->sndcb->priv = (FAR void *)conn;
conn->sndcb->event = sendto_eventhandler;
netdev_txnotify_dev(dev, UDP_POLL);
out:
conn_dev_unlock(&conn->sconn, dev);
conn_lock(&conn->sconn);
return ret;
}
* Name: sendto_eventhandler
*
* Description:
* This function is called to perform the actual send operation when
* polled by the lower, device interfacing layer.
*
* Input Parameters:
* dev The structure of the network driver that caused the event
* conn The connection structure associated with the socket
* flags Set of events describing why the callback was invoked
*
* Returned Value:
* None
*
* Assumptions:
* The network is locked
*
****************************************************************************/
static uint32_t sendto_eventhandler(FAR struct net_driver_s *dev,
FAR void *pvpriv, uint32_t flags)
{
FAR struct udp_conn_s *conn = pvpriv;
DEBUGASSERT(dev != NULL && conn != NULL);
ninfo("flags: %" PRIx32 "\n", flags);
if ((flags & NETDEV_DOWN) != 0)
{
ninfo("Device down: %" PRIx32 "\n", flags);
* the next transfer.
*/
sendto_writebuffer_release(conn, NULL);
return flags;
}
* device is the one that we are bound to.
*
* REVISIT: There is a logical error here for the case where there are
* multiple network devices. In that case, the packets may need to be sent
* in a different order than they were queued. The packet we may need to
* send on this device may not be at the head of the list. Forcing FIFO
* packet transmission could degrade performance!
*/
DEBUGASSERT(conn != NULL);
DEBUGASSERT(conn->dev != NULL);
if (dev != conn->dev)
{
return flags;
}
* available. It would not be available if it has been claimed by a send
* event serving a different thread -OR- if the output buffer currently
* contains unprocessed incoming data. In these cases we will just have
* to wait for the next polling cycle.
*
* And, of course, we can do nothing if we have no data in the write
* buffers to send.
*/
if (dev->d_sndlen <= 0 && (flags & UDP_NEWDATA) == 0 &&
(flags & UDP_POLL) != 0 && !sq_empty(&conn->write_q))
{
uint16_t udpiplen = udpip_hdrsize(conn);
FAR struct udp_wrbuffer_s *wrb;
* from the write queue yet). We know from the above test that
* the write_q is not empty.
*/
wrb = (FAR struct udp_wrbuffer_s *)sq_remfirst(&conn->write_q);
DEBUGASSERT(wrb != NULL);
* multi-different destination address in each iob entry,
* update the remote address every time to avoid sent to the
* incorrect destination.
*/
udp_connect(conn, (FAR const struct sockaddr *)&wrb->wb_dest);
* corresponding to the size of the IP-dependent address structure.
*/
netdev_iob_replace(dev, wrb->wb_iob);
* We will send either the remaining data in the buffer I/O
* buffer chain, or as much as will fit given the MSS and current
* window size.
*/
dev->d_sndlen = wrb->wb_iob->io_pktlen - udpiplen;
ninfo("wrb=%p sndlen=%d\n", wrb, dev->d_sndlen);
* handed over to the network device
*/
wrb->wb_iob = NULL;
#ifdef NEED_IPDOMAIN_SUPPORT
* select which one to use when generating the outgoing packet.
* If only one domain is selected, then the setup is already in
* place and we need do nothing.
*/
sendto_ipselect(dev, conn);
#endif
* setup the next transfer.
*/
sendto_writebuffer_release(conn, wrb);
* tell the caller stop polling the other connections.
*/
flags &= ~UDP_POLL;
}
return flags;
}
* Name: udp_send_gettimeout
*
* Description:
* Calculate the send timeout
*
****************************************************************************/
static unsigned int udp_send_gettimeout(clock_t start, unsigned int timeout)
{
unsigned int elapse;
if (timeout != UINT_MAX)
{
elapse = TICK2MSEC(clock_systime_ticks() - start);
if (elapse >= timeout)
{
timeout = 0;
}
else
{
timeout -= elapse;
}
}
return timeout;
}
* Public Functions
****************************************************************************/
* Name: psock_udp_sendto
*
* Description:
* This function implements the UDP-specific logic of the standard
* sendto() socket operation.
*
* Input Parameters:
* psock A pointer to a NuttX-specific, internal socket structure
* buf Data to send
* len Length of data to send
* flags Send flags
* to Address of recipient
* tolen The length of the address structure
*
* NOTE: All input parameters were verified by sendto() before this
* function was called.
*
* Returned Value:
* On success, returns the number of characters sent. On error,
* a negated errno value is returned. See the description in
* net/socket/sendto.c for the list of appropriate return value.
*
****************************************************************************/
ssize_t psock_udp_sendto(FAR struct socket *psock, FAR const void *buf,
size_t len, int flags,
FAR const struct sockaddr *to, socklen_t tolen)
{
FAR struct udp_wrbuffer_s *wrb;
FAR struct udp_conn_s *conn;
unsigned int timeout;
uint16_t udpiplen;
bool nonblock;
bool empty;
int ret = OK;
clock_t start;
conn = psock->s_conn;
if (len > 65535)
{
return -EMSGSIZE;
}
* connect(), then as with connection-mode socket, sendto() may not be
* used with a non-NULL destination address. Normally send() would be
* used with such connected UDP sockets.
*/
if (to != NULL && _SS_ISCONNECTED(conn->sconn.s_flags))
{
* already connected.
*/
return -EISCONN;
}
* must be provided.
*/
else if (to == NULL && !_SS_ISCONNECTED(conn->sconn.s_flags))
{
* address is set.
*/
return -EDESTADDRREQ;
}
#if defined(CONFIG_NET_ARP_SEND) || defined(CONFIG_NET_ICMPv6_NEIGHBOR)
#ifdef CONFIG_NET_ARP_SEND
* the ARP table.
*/
if (psock->s_domain == PF_INET)
{
in_addr_t destipaddr;
if (_SS_ISCONNECTED(conn->sconn.s_flags))
{
* null).
*/
destipaddr = conn->u.ipv4.raddr;
}
else
{
FAR const struct sockaddr_in *into;
* argument.
*/
into = (FAR const struct sockaddr_in *)to;
destipaddr = into->sin_addr.s_addr;
}
ret = arp_send(destipaddr);
}
#endif
#ifdef CONFIG_NET_ICMPv6_NEIGHBOR
* the neighbor table.
*/
if (psock->s_domain == PF_INET6)
{
FAR const uint16_t *destipaddr;
if (_SS_ISCONNECTED(conn->sconn.s_flags))
{
* null).
*/
destipaddr = conn->u.ipv6.raddr;
}
else
{
FAR const struct sockaddr_in6 *into;
* argument.
*/
into = (FAR const struct sockaddr_in6 *)to;
destipaddr = into->sin6_addr.s6_addr16;
}
ret = icmpv6_neighbor(NULL, destipaddr);
}
#endif
if (ret < 0)
{
nerr("ERROR: Not reachable\n");
return -ENETUNREACH;
}
#endif
nonblock = _SS_ISNONBLOCK(conn->sconn.s_flags) ||
(flags & MSG_DONTWAIT) != 0;
start = clock_systime_ticks();
timeout = _SO_TIMEOUT(conn->sconn.s_sndtimeo);
BUF_DUMP("psock_udp_sendto", buf, len);
#if CONFIG_NET_SEND_BUFSIZE > 0
* wait for the write buffer to be released
*/
conn_lock(&conn->sconn);
while (udp_wrbuffer_inqueue_size(conn) + len > conn->sconn.s_sndbufs)
{
if (nonblock)
{
conn_unlock(&conn->sconn);
return -EAGAIN;
}
ret = conn_dev_sem_timedwait(&conn->sconn.s_sndsem, false,
udp_send_gettimeout(start, timeout),
&conn->sconn, NULL);
if (ret < 0)
{
if (ret == -ETIMEDOUT)
{
ret = -EAGAIN;
}
conn_unlock(&conn->sconn);
return ret;
}
}
conn_unlock(&conn->sconn);
#endif
* unlocked here.
*/
#ifdef CONFIG_NET_JUMBO_FRAME
wrb = udp_wrbuffer_tryalloc(len + udpip_hdrsize(conn) +
CONFIG_NET_LL_GUARDSIZE);
#else
if (nonblock)
{
wrb = udp_wrbuffer_tryalloc();
}
else
{
wrb = udp_wrbuffer_timedalloc(udp_send_gettimeout(start, timeout));
}
#endif
if (wrb == NULL)
{
nerr("ERROR: Failed to allocate write buffer\n");
if (nonblock || timeout != UINT_MAX)
{
ret = -EAGAIN;
}
else
{
ret = -ENOMEM;
}
return ret;
}
*
* Check if the socket is connected
*/
if (_SS_ISCONNECTED(conn->sconn.s_flags))
{
#ifdef CONFIG_NET_IPv4
#ifdef CONFIG_NET_IPv6
if (conn->domain == PF_INET)
#endif
{
FAR struct sockaddr_in *addr4 =
(FAR struct sockaddr_in *)&wrb->wb_dest;
addr4->sin_family = AF_INET;
addr4->sin_port = conn->rport;
net_ipv4addr_copy(addr4->sin_addr.s_addr, conn->u.ipv4.raddr);
memset(addr4->sin_zero, 0, sizeof(addr4->sin_zero));
}
#endif
#ifdef CONFIG_NET_IPv6
#ifdef CONFIG_NET_IPv4
else
#endif
{
FAR struct sockaddr_in6 *addr6 =
(FAR struct sockaddr_in6 *)&wrb->wb_dest;
addr6->sin6_family = AF_INET6;
addr6->sin6_port = conn->rport;
net_ipv6addr_copy(addr6->sin6_addr.s6_addr, conn->u.ipv6.raddr);
}
#endif
}
else
{
memcpy(&wrb->wb_dest, to, tolen);
udp_connect(conn, to);
}
udpiplen = udpip_hdrsize(conn);
iob_reserve(wrb->wb_iob, CONFIG_NET_LL_GUARDSIZE);
iob_update_pktlen(wrb->wb_iob, udpiplen, false);
* buffer space if the socket was opened non-blocking.
*/
if (len > 0)
{
if (nonblock)
{
ret = iob_trycopyin(wrb->wb_iob, (FAR uint8_t *)buf, len, udpiplen,
false);
}
else
{
ret = iob_copyin(wrb->wb_iob, (FAR uint8_t *)buf, len, udpiplen,
false);
}
if (ret < 0)
{
goto errout_with_wrb;
}
}
UDP_WBDUMP("I/O buffer chain", wrb, wrb->wb_iob->io_pktlen, 0);
* conn->write_q.
*
* REVISIT: Why FIFO order? Because it is easy. In a real world
* environment where there are multiple network devices this might
* be inefficient because we could be sending data to different
* device out-of-queued-order to optimize performance. Sending
* data to different networks from a single UDP socket is probably
* not a very common use case, however.
*/
conn_lock(&conn->sconn);
empty = sq_empty(&conn->write_q);
sq_addlast(&wrb->wb_node, &conn->write_q);
ninfo("Queued WRB=%p pktlen=%u write_q(%p,%p)\n", wrb,
wrb->wb_iob->io_pktlen, conn->write_q.head, conn->write_q.tail);
if (empty)
{
* up for the next packet transfer by setting the connection
* address to the address of the next packet now at the header of
* the write buffer queue.
*/
ret = sendto_next_transfer(conn);
if (ret < 0)
{
sq_remlast(&conn->write_q);
conn_unlock(&conn->sconn);
goto errout_with_wrb;
}
}
conn_unlock(&conn->sconn);
return len;
errout_with_wrb:
udp_wrbuffer_release(wrb);
return ret;
}
* Name: psock_udp_cansend
*
* Description:
* psock_udp_cansend() returns a value indicating if a write to the socket
* would block. No space in the buffer is actually reserved, so it is
* possible that the write may still block if the buffer is filled by
* another means.
*
* Input Parameters:
* conn A reference to UDP connection structure.
*
* Returned Value:
* OK
* At least one byte of data could be successfully written.
* -EWOULDBLOCK
* There is no room in the output buffer.
* -EBADF
* An invalid descriptor was specified.
*
****************************************************************************/
int psock_udp_cansend(FAR struct udp_conn_s *conn)
{
if (conn == NULL)
{
nerr("ERROR: Invalid socket\n");
return -EBADF;
}
* buffer head and at least one free IOB to initialize the write buffer
* head.
*
* REVISIT: The send will still block if we are unable to buffer the
* entire user-provided buffer which may be quite large. We will almost
* certainly need to have more than one free IOB, but we don't know how
* many more.
*/
if (udp_wrbuffer_test() < 0 || iob_navail(false) <= 0
#if CONFIG_NET_SEND_BUFSIZE > 0
|| udp_wrbuffer_inqueue_size(conn) >= conn->sconn.s_sndbufs
#endif
)
{
return -EWOULDBLOCK;
}
return OK;
}
* Name: udp_sendbuffer_notify
*
* Description:
* Notify the send buffer semaphore
*
* Input Parameters:
* conn - The UDP connection of interest
*
* Assumptions:
* Called from user logic with the network locked.
*
****************************************************************************/
#if CONFIG_NET_SEND_BUFSIZE > 0
void udp_sendbuffer_notify(FAR struct udp_conn_s *conn)
{
int val = 0;
nxsem_get_value(&conn->sconn.s_sndsem, &val);
if (val < 0)
{
nxsem_post(&conn->sconn.s_sndsem);
}
}
#endif
#endif