summaryrefslogtreecommitdiffstats
path: root/contrib
diff options
context:
space:
mode:
authorVladimír Čunát <vladimir.cunat@nic.cz>2020-12-22 14:09:20 +0100
committerVladimír Čunát <vladimir.cunat@nic.cz>2021-01-13 09:49:13 +0100
commitae8d7714dc7078fa8e4ae270169e3f676208877d (patch)
tree8426f5cfe9efd2fef2fac73defdcba7d6f10a12e /contrib
parentcopy mempattern files from Knot DNS as they are (diff)
downloadknot-resolver-ae8d7714dc7078fa8e4ae270169e3f676208877d.tar.xz
knot-resolver-ae8d7714dc7078fa8e4ae270169e3f676208877d.zip
contrib/mempattern: integrate other related functions
Diffstat (limited to 'contrib')
-rw-r--r--contrib/mempattern.c17
-rw-r--r--contrib/mempattern.h28
2 files changed, 44 insertions, 1 deletions
diff --git a/contrib/mempattern.c b/contrib/mempattern.c
index 96715c9e..177e5bae 100644
--- a/contrib/mempattern.c
+++ b/contrib/mempattern.c
@@ -119,3 +119,20 @@ void mm_ctx_mempool(knot_mm_t *mm, size_t chunk_size)
mm->alloc = (knot_mm_alloc_t)mp_alloc;
mm->free = mm_nofree;
}
+
+
+/* Code in addition to Knot's mempattern. */
+
+void *mm_malloc_aligned(void *ctx, size_t n)
+{
+ size_t alignment = (size_t)ctx;
+ void *res;
+ int err = posix_memalign(&res, alignment, n);
+ if (err == 0) {
+ return res;
+ } else {
+ assert(err == -1 && errno == ENOMEM);
+ return NULL;
+ }
+}
+
diff --git a/contrib/mempattern.h b/contrib/mempattern.h
index f8ed5c45..f277b672 100644
--- a/contrib/mempattern.h
+++ b/contrib/mempattern.h
@@ -22,6 +22,8 @@
#include <libknot/mm_ctx.h>
#include "lib/defines.h"
+#include <assert.h>
+#include <stdint.h>
/*! \brief Default memory block size. */
#define MM_DEFAULT_BLKSIZE 4096
@@ -50,6 +52,30 @@ void mm_ctx_init(knot_mm_t *mm);
/*! \brief Memory pool context. */
void mm_ctx_mempool(knot_mm_t *mm, size_t chunk_size);
-/*! \brief Simple malloc wrapper. Not exposed in knot's mempattern. */
+
+/* API in addition to Knot's mempattern. */
+
+/*! \brief Simple malloc wrapper. */
void *mm_malloc(void *ctx, size_t n);
+/*! \brief Readability: avoid const-casts in code. */
+static inline void free_const(const void *what)
+{
+ free((void *)what);
+}
+
+/*! \brief posix_memalign() wrapper. */
+void *mm_malloc_aligned(void *ctx, size_t n);
+
+/*! \brief Initialize mm with malloc+free with specified alignment (a power of two). */
+static inline void mm_ctx_init_aligned(knot_mm_t *mm, size_t alignment)
+{
+ assert(__builtin_popcount(alignment) == 1);
+ mm->ctx = (uint8_t *)NULL + alignment; /*< roundabout to satisfy linters */
+ /* posix_memalign() doesn't allow alignment < sizeof(void*),
+ * and there's no point in using it for small values anyway,
+ * as plain malloc() guarantees at least max_align_t. */
+ mm->alloc = alignment > sizeof(max_align_t) ? mm_malloc_aligned : mm_malloc;
+ mm->free = free;
+}
+