From b70f92e5702be780d51a4a164ff28cbc2c28001c Mon Sep 17 00:00:00 2001 From: Johann Fischer Date: Mon, 16 May 2022 14:47:56 +0200 Subject: [PATCH] net: buf: keep memory alignment provided by k_heap_alloc and k_malloc Allocation callback in net_buf_heap_cb and net_buf_var_cb used for net_bufs with variable size payloads, defined by NET_BUF_POOL_HEAP_DEFINE or NET_BUF_POOL_VAR_DEFINE, allocate one more octet for internal variable ref_count, used in function generic_data_ref(), which in turn is needed for net_buf_clone()). The user gets a buffer which is shifted by one octet in memory block. This breaks alignment provided k_heap_alloc and k_malloc. Signed-off-by: Johann Fischer --- subsys/net/buf.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/subsys/net/buf.c b/subsys/net/buf.c index 01e379da39f..887e75e4be8 100644 --- a/subsys/net/buf.c +++ b/subsys/net/buf.c @@ -107,7 +107,7 @@ static uint8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, uint8_t *ref_count; /* Reserve extra space for a ref-count (uint8_t) */ - void *b = k_heap_alloc(pool, 1 + *size, timeout); + void *b = k_heap_alloc(pool, sizeof(void *) + *size, timeout); if (b == NULL) { return NULL; @@ -117,7 +117,7 @@ static uint8_t *mem_pool_data_alloc(struct net_buf *buf, size_t *size, *ref_count = 1U; /* Return pointer to the byte following the ref count */ - return ref_count + 1; + return ref_count + sizeof(void *); } static void mem_pool_data_unref(struct net_buf *buf, uint8_t *data) @@ -126,7 +126,7 @@ static void mem_pool_data_unref(struct net_buf *buf, uint8_t *data) struct k_heap *pool = buf_pool->alloc->alloc_data; uint8_t *ref_count; - ref_count = data - 1; + ref_count = data - sizeof(void *); if (--(*ref_count)) { return; } @@ -169,21 +169,21 @@ static uint8_t *heap_data_alloc(struct net_buf *buf, size_t *size, { uint8_t *ref_count; - ref_count = k_malloc(1 + *size); + ref_count = k_malloc(sizeof(void *) + *size); if (!ref_count) { return NULL; } *ref_count = 1U; - return ref_count + 1; + return ref_count + sizeof(void *); } static void heap_data_unref(struct net_buf *buf, uint8_t *data) { uint8_t *ref_count; - ref_count = data - 1; + ref_count = data - sizeof(void *); if (--(*ref_count)) { return; }