From: Guus Sliepen Date: Thu, 19 Mar 2020 21:17:34 +0000 (+0100) Subject: Allocate a persistent packet buffer. X-Git-Url: https://git.meshlink.io/?a=commitdiff_plain;h=d63d8afc7a6e95965331d9cac9d4a405d8cd0e8f;p=utcp Allocate a persistent packet buffer. Instead of allocating a new packet buffer every time we generate a packet, we pre-allocate it and keep it around. We only reallocate when the MTU increases. --- diff --git a/utcp.c b/utcp.c index 5d63069..ae3b2b6 100644 --- a/utcp.c +++ b/utcp.c @@ -527,13 +527,7 @@ static void ack(struct utcp_connection *c, bool sendatleastone) { struct { struct hdr hdr; uint8_t data[]; - } *pkt; - - pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu); - - if(!pkt) { - return; - } + } *pkt = c->utcp->pkt; pkt->hdr.src = c->src; pkt->hdr.dst = c->dst; @@ -566,8 +560,6 @@ static void ack(struct utcp_connection *c, bool sendatleastone) { print_packet(c->utcp, "send", pkt, sizeof(pkt->hdr) + seglen); c->utcp->send(c->utcp, pkt, sizeof(pkt->hdr) + seglen); } while(left); - - free(pkt); } ssize_t utcp_send(struct utcp_connection *c, const void *data, size_t len) { @@ -687,13 +679,7 @@ static void retransmit(struct utcp_connection *c) { struct { struct hdr hdr; uint8_t data[]; - } *pkt; - - pkt = malloc(sizeof(pkt->hdr) + c->utcp->mtu); - - if(!pkt) { - return; - } + } *pkt = c->utcp->pkt; pkt->hdr.src = c->src; pkt->hdr.dst = c->dst; @@ -773,7 +759,7 @@ static void retransmit(struct utcp_connection *c) { c->rtt_start.tv_sec = 0; // invalidate RTT timer cleanup: - free(pkt); + return; } /* Update receive buffer and SACK entries after consuming data. @@ -1861,7 +1847,7 @@ struct utcp *utcp_init(utcp_accept_t accept, utcp_pre_accept_t pre_accept, utcp_ utcp->pre_accept = pre_accept; utcp->send = send; utcp->priv = priv; - utcp->mtu = DEFAULT_MTU; + utcp_set_mtu(utcp, DEFAULT_MTU); utcp->timeout = DEFAULT_USER_TIMEOUT; // sec utcp->rto = START_RTO; // usec @@ -1900,10 +1886,22 @@ uint16_t utcp_get_mtu(struct utcp *utcp) { } void utcp_set_mtu(struct utcp *utcp, uint16_t mtu) { - // TODO: handle overhead of the header - if(utcp) { - utcp->mtu = mtu; + if (!utcp) { + return; } + + if (mtu <= sizeof(struct hdr)) { + return; + } + + if (mtu > utcp->mtu) { + char *new = realloc(utcp->pkt, mtu); + if (!new) + return; + utcp->pkt = new; + } + + utcp->mtu = mtu; } void utcp_reset_timers(struct utcp *utcp) { diff --git a/utcp_priv.h b/utcp_priv.h index 6c5c1f8..1f72fb4 100644 --- a/utcp_priv.h +++ b/utcp_priv.h @@ -169,6 +169,10 @@ struct utcp { utcp_pre_accept_t pre_accept; utcp_send_t send; + // Packet buffer + + void *pkt; + // Global socket options uint16_t mtu;