From 57d7814d3c211a46f6a6fe7dd995307cb9a6f41e Mon Sep 17 00:00:00 2001 From: Guus Sliepen Date: Sun, 11 Apr 2021 00:36:30 +0200 Subject: [PATCH] Reduce UTCP memory usage. Don't allocate a send buffer by default, since an application might only want to receive data. Also try to shrink the send and receive buffers on channel close, or even free them if the buffers are empty. --- src/utcp.c | 56 ++++++++++++++++++++++++++++++++++++------------- src/utcp_priv.h | 2 +- 2 files changed, 43 insertions(+), 15 deletions(-) diff --git a/src/utcp.c b/src/utcp.c index 46d7fd35..c21e7067 100644 --- a/src/utcp.c +++ b/src/utcp.c @@ -196,6 +196,16 @@ static bool buffer_wraps(struct buffer *buf) { } static bool buffer_resize(struct buffer *buf, uint32_t newsize) { + assert(!buf->external); + + if(!newsize) { + free(buf->data); + buf->data = NULL; + buf->size = 0; + buf->offset = 0; + return true; + } + char *newdata = realloc(buf->data, newsize); if(!newdata) { @@ -441,17 +451,40 @@ static void set_buffer_storage(struct buffer *buf, char *data, size_t size) { buf->external = true; } else if(buf->external) { // Transition from external to internal buf - size_t minsize = buf->used < DEFAULT_SNDBUFSIZE ? DEFAULT_SNDBUFSIZE : buf->used; - data = malloc(minsize); + size_t minsize = buf->used <= DEFAULT_SNDBUFSIZE ? DEFAULT_SNDBUFSIZE : buf->used; - if(!data) { - // Cannot handle this - abort(); + if(minsize) { + data = malloc(minsize); + + if(!data) { + // Cannot handle this + abort(); + } + + buffer_transfer(buf, data, minsize); + buf->data = data; + } else { + buf->data = NULL; + buf->size = 0; } - buffer_transfer(buf, data, minsize); - buf->data = data; buf->external = false; + } else { + // Realloc internal storage + size_t minsize = buf->used <= DEFAULT_SNDBUFSIZE ? DEFAULT_SNDBUFSIZE : buf->used; + + if(minsize) { + data = realloc(buf->data, minsize); + + if(data) { + buf->data = data; + buf->size = minsize; + } + } else { + free(buf->data); + buf->data = NULL; + buf->size = 0; + } } } @@ -2075,13 +2108,8 @@ static bool reset_connection(struct utcp_connection *c) { } static void set_reapable(struct utcp_connection *c) { - if(c->sndbuf.external) { - set_buffer_storage(&c->sndbuf, NULL, DEFAULT_MTU); - } - - if(c->rcvbuf.external) { - set_buffer_storage(&c->rcvbuf, NULL, DEFAULT_MTU); - } + set_buffer_storage(&c->sndbuf, NULL, DEFAULT_MTU); + set_buffer_storage(&c->rcvbuf, NULL, DEFAULT_MTU); c->recv = NULL; c->poll = NULL; diff --git a/src/utcp_priv.h b/src/utcp_priv.h index 531f2657..f96b92b5 100644 --- a/src/utcp_priv.h +++ b/src/utcp_priv.h @@ -37,7 +37,7 @@ #define AUX_TIMESTAMP 4 #define NSACKS 4 -#define DEFAULT_SNDBUFSIZE 4096 +#define DEFAULT_SNDBUFSIZE 0 #define DEFAULT_MAXSNDBUFSIZE 131072 #define DEFAULT_RCVBUFSIZE 0 #define DEFAULT_MAXRCVBUFSIZE 131072 -- 2.39.5